mirror of
https://github.com/jhd3197/ServerKit.git
synced 2026-12-06 07:01:52 +09:00
Merge plan-47 lean-core (wizard installs + 4 backend extractions + security tab-group)
This commit is contained in:
commit
b7911026be
51 files changed
+1410
-309
No files matched your search
+35
-15
@@ -117,7 +117,6 @@ def create_app(config_name=None):
|
||||
# Register blueprints - Core
|
||||
from app.api.apps import apps_bp
|
||||
from app.api.domains import domains_bp
|
||||
from app.api.tunnels import tunnels_bp
|
||||
from app.api.private_urls import private_urls_bp
|
||||
app.register_blueprint(apps_bp, url_prefix='/api/v1/apps')
|
||||
# "Services" is the user-facing term for Applications (§1 unification).
|
||||
@@ -248,9 +247,9 @@ def create_app(config_name=None):
|
||||
from app.api.files import files_bp
|
||||
app.register_blueprint(files_bp, url_prefix='/api/v1/files')
|
||||
|
||||
# Register blueprints - FTP Server
|
||||
from app.api.ftp import ftp_bp
|
||||
app.register_blueprint(ftp_bp, url_prefix='/api/v1/ftp')
|
||||
# FTP Server is an opt-in builtin extension (serverkit-ftp, plan 47) — its
|
||||
# blueprint loads from builtin-extensions/serverkit-ftp/ when installed, not
|
||||
# from core. A fresh panel that never touches FTP loads none of it.
|
||||
|
||||
# Register blueprints - Firewall
|
||||
from app.api.firewall import firewall_bp
|
||||
@@ -421,16 +420,21 @@ def create_app(config_name=None):
|
||||
from app.api.nginx_advanced import nginx_advanced_bp
|
||||
app.register_blueprint(nginx_advanced_bp, url_prefix='/api/v1/nginx/advanced')
|
||||
|
||||
# Register blueprints - Status Pages
|
||||
from app.api.status_pages import status_pages_bp
|
||||
app.register_blueprint(status_pages_bp, url_prefix='/api/v1/status')
|
||||
# Status Pages is an opt-in builtin extension (serverkit-status, plan 47) —
|
||||
# its blueprint (public + management routes) loads from builtin-extensions/
|
||||
# when installed, not from core. The StatusPage/StatusComponent models stay
|
||||
# core (G2); the WordPress health-check job reaches the extension's sync
|
||||
# helper via get_installed_extension_attr only when installed.
|
||||
|
||||
# Register blueprints - Cloud Provisioning
|
||||
from app.api.cloud_provisioning import cloud_provisioning_bp
|
||||
app.register_blueprint(cloud_provisioning_bp, url_prefix='/api/v1/cloud')
|
||||
# Cloud Provisioning is an opt-in builtin extension (serverkit-cloud-provision,
|
||||
# plan 47) — its blueprint loads from builtin-extensions/ when installed, not
|
||||
# from core. The CloudProvider/CloudServer models stay core (G2).
|
||||
|
||||
# Register blueprints - Remote Access (WireGuard tunnels; imported above)
|
||||
app.register_blueprint(tunnels_bp, url_prefix='/api/v1/tunnels')
|
||||
# Remote Access (WireGuard tunnels) is an opt-in builtin extension
|
||||
# (serverkit-remote-access, plan 47) — its blueprint loads from
|
||||
# builtin-extensions/ when installed, not from core. The Tunnel/ExposedService
|
||||
# models stay core (G2); the agent gateway reaches its reconcile helper via
|
||||
# get_installed_extension_attr only when the extension is present.
|
||||
|
||||
# Register blueprints - Performance
|
||||
from app.api.performance import performance_bp
|
||||
@@ -479,7 +483,9 @@ def create_app(config_name=None):
|
||||
app.register_blueprint(telemetry_bp, url_prefix='/api/v1/observability/events', name='obs_events')
|
||||
app.register_blueprint(uptime_bp, url_prefix='/api/v1/observability/uptime', name='obs_uptime')
|
||||
app.register_blueprint(fleet_monitor_bp, url_prefix='/api/v1/observability/fleet', name='obs_fleet')
|
||||
app.register_blueprint(status_pages_bp, url_prefix='/api/v1/observability/status-pages', name='obs_status_pages')
|
||||
# status-pages observability alias dropped with the serverkit-status
|
||||
# extraction (plan 47) — it was unused by the frontend; status pages mount at
|
||||
# /api/v1/status from the extension when installed.
|
||||
|
||||
# Register blueprints - Agent Pairing (RustDesk-style short-code flow)
|
||||
from app.api.pairing import pairing_bp
|
||||
@@ -529,10 +535,14 @@ def create_app(config_name=None):
|
||||
try:
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
from app.services.storage_provider_service import StorageProviderService
|
||||
from app.services.cloud_provisioning_service import CloudProvisioningService
|
||||
n_dns = DNSProviderService.encrypt_legacy_secrets()
|
||||
n_store = StorageProviderService.encrypt_legacy_secrets()
|
||||
n_cloud = CloudProvisioningService.encrypt_legacy_secrets()
|
||||
# Cloud-provider legacy-secret encryption moved out with the
|
||||
# serverkit-cloud-provision extension (plan 47). It was a one-time
|
||||
# migration of pre-encryption rows; any panel reaching this version
|
||||
# already ran it in an earlier boot (idempotent), and the extension
|
||||
# encrypts on write, so there's nothing left for core to do here.
|
||||
n_cloud = 0
|
||||
n_settings = SettingsService.migrate_legacy_secrets()
|
||||
# Migrate DNS zones with an inline Cloudflare token onto the canonical
|
||||
# connection store (idempotent), so every zone resolves creds the same way.
|
||||
@@ -598,6 +608,16 @@ def create_app(config_name=None):
|
||||
import logging
|
||||
logging.getLogger(__name__).warning(f'Extension auto-install: {e}')
|
||||
|
||||
# One-shot: re-acquire the now-extracted backend for converted builtins
|
||||
# that first shipped frontend-only (plan 47 Phase 2), so an upgraded panel
|
||||
# that installed them frontend-only doesn't lose the API. Best-effort.
|
||||
try:
|
||||
from app.services.extension_migration import run_backend_acquisition
|
||||
run_backend_acquisition()
|
||||
except Exception as e:
|
||||
import logging
|
||||
logging.getLogger(__name__).warning(f'Extension backend acquisition: {e}')
|
||||
|
||||
# Start metrics history collection in background
|
||||
from app.services.metrics_history_service import MetricsHistoryService
|
||||
if not MetricsHistoryService.is_running():
|
||||
|
||||
@@ -303,8 +303,14 @@ class AgentNamespace(Namespace):
|
||||
try:
|
||||
caps = (data or {}).get('capabilities') or {}
|
||||
if caps.get('wireguard'):
|
||||
from app.services.tunnel_broker_service import TunnelBrokerService
|
||||
TunnelBrokerService.schedule_reconcile(agent.server_id)
|
||||
# TunnelBrokerService now lives in the serverkit-remote-access
|
||||
# extension (plan 47); reach it only when installed, no-op otherwise.
|
||||
from app.services.plugin_service import get_installed_extension_attr
|
||||
TunnelBrokerService = get_installed_extension_attr(
|
||||
'serverkit-remote-access', 'tunnel_broker_service',
|
||||
'TunnelBrokerService')
|
||||
if TunnelBrokerService is not None:
|
||||
TunnelBrokerService.schedule_reconcile(agent.server_id)
|
||||
except Exception:
|
||||
logger.debug("tunnel reconcile scheduling skipped", exc_info=True)
|
||||
|
||||
|
||||
+21
-1
@@ -183,8 +183,28 @@ def complete_onboarding():
|
||||
if invalid:
|
||||
return jsonify({'error': f'Invalid use cases: {", ".join(invalid)}'}), 400
|
||||
|
||||
# Save onboarding use cases
|
||||
# Slugs the wizard installed (recorded for Setup Health / support). The
|
||||
# actual installs happen client-side via the plugin install endpoints; this
|
||||
# just persists what onboarding did (plan 47).
|
||||
installed_extensions = data.get('installed_extensions', [])
|
||||
if not isinstance(installed_extensions, list):
|
||||
return jsonify({'error': 'installed_extensions must be a list'}), 400
|
||||
installed_extensions = [
|
||||
s for s in installed_extensions if isinstance(s, str) and s.strip()
|
||||
]
|
||||
|
||||
# Save onboarding use cases + what the wizard installed
|
||||
SettingsService.set('onboarding_use_cases', use_cases, user_id=user.id)
|
||||
SettingsService.set('onboarding_installed_extensions', installed_extensions,
|
||||
user_id=user.id)
|
||||
|
||||
# Keep the panel lean: suppress wizard-optional flagships (WordPress) the
|
||||
# user didn't install so the boot seeder won't re-add them (plan 47).
|
||||
try:
|
||||
from app.services import plugin_service
|
||||
plugin_service.finalize_setup_flagships()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Mark setup as complete
|
||||
SettingsService.complete_setup(user_id=user.id)
|
||||
|
||||
@@ -1,162 +0,0 @@
|
||||
from flask import Blueprint, request, jsonify
|
||||
from flask_jwt_extended import jwt_required
|
||||
from app.services.cloud_provisioning_service import CloudProvisioningService
|
||||
|
||||
cloud_provisioning_bp = Blueprint('cloud_provisioning', __name__)
|
||||
|
||||
|
||||
def get_current_user():
|
||||
from flask_jwt_extended import get_jwt_identity
|
||||
from app.models.user import User
|
||||
return User.query.get(get_jwt_identity())
|
||||
|
||||
|
||||
# --- Providers ---
|
||||
|
||||
@cloud_provisioning_bp.route('/providers', methods=['GET'])
|
||||
@jwt_required()
|
||||
def list_providers():
|
||||
providers = CloudProvisioningService.list_providers()
|
||||
return jsonify({'providers': [p.to_dict() for p in providers]})
|
||||
|
||||
|
||||
@cloud_provisioning_bp.route('/providers', methods=['POST'])
|
||||
@jwt_required()
|
||||
def create_provider():
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
data = request.get_json()
|
||||
try:
|
||||
provider = CloudProvisioningService.create_provider(data, user.id)
|
||||
return jsonify(provider.to_dict()), 201
|
||||
except ValueError as e:
|
||||
return jsonify({'error': str(e)}), 400
|
||||
|
||||
|
||||
@cloud_provisioning_bp.route('/providers/<int:provider_id>', methods=['DELETE'])
|
||||
@jwt_required()
|
||||
def delete_provider(provider_id):
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
if not CloudProvisioningService.delete_provider(provider_id):
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
return jsonify({'message': 'Provider removed'})
|
||||
|
||||
|
||||
@cloud_provisioning_bp.route('/providers/<provider_type>/options', methods=['GET'])
|
||||
@jwt_required()
|
||||
def get_options(provider_type):
|
||||
options = CloudProvisioningService.get_provider_options(provider_type)
|
||||
if not options:
|
||||
return jsonify({'error': 'Unknown provider'}), 404
|
||||
return jsonify(options)
|
||||
|
||||
|
||||
# --- Servers ---
|
||||
|
||||
@cloud_provisioning_bp.route('/servers', methods=['GET'])
|
||||
@jwt_required()
|
||||
def list_servers():
|
||||
provider_id = request.args.get('provider_id', type=int)
|
||||
servers = CloudProvisioningService.list_servers(provider_id)
|
||||
return jsonify({'servers': [s.to_dict() for s in servers]})
|
||||
|
||||
|
||||
@cloud_provisioning_bp.route('/servers/<int:server_id>', methods=['GET'])
|
||||
@jwt_required()
|
||||
def get_server(server_id):
|
||||
server = CloudProvisioningService.get_server(server_id)
|
||||
if not server:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
return jsonify(server.to_dict())
|
||||
|
||||
|
||||
@cloud_provisioning_bp.route('/servers', methods=['POST'])
|
||||
@jwt_required()
|
||||
def create_server():
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
data = request.get_json()
|
||||
if not data or 'name' not in data or 'provider_id' not in data:
|
||||
return jsonify({'error': 'name and provider_id required'}), 400
|
||||
try:
|
||||
server = CloudProvisioningService.create_server(data, user.id)
|
||||
return jsonify(server.to_dict()), 201
|
||||
except (ValueError, Exception) as e:
|
||||
return jsonify({'error': str(e)}), 400
|
||||
|
||||
|
||||
@cloud_provisioning_bp.route('/servers/<int:server_id>', methods=['DELETE'])
|
||||
@jwt_required()
|
||||
def destroy_server(server_id):
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
if not CloudProvisioningService.destroy_server(server_id):
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
return jsonify({'message': 'Server destroyed'})
|
||||
|
||||
|
||||
@cloud_provisioning_bp.route('/servers/<int:server_id>/resize', methods=['POST'])
|
||||
@jwt_required()
|
||||
def resize_server(server_id):
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
data = request.get_json() or {}
|
||||
new_size = data.get('size')
|
||||
if not new_size:
|
||||
return jsonify({'error': 'size required'}), 400
|
||||
try:
|
||||
server = CloudProvisioningService.resize_server(server_id, new_size)
|
||||
if not server:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
return jsonify(server.to_dict())
|
||||
except ValueError as e:
|
||||
return jsonify({'error': str(e)}), 400
|
||||
|
||||
|
||||
# --- Snapshots ---
|
||||
|
||||
@cloud_provisioning_bp.route('/servers/<int:server_id>/snapshots', methods=['GET'])
|
||||
@jwt_required()
|
||||
def list_snapshots(server_id):
|
||||
snapshots = CloudProvisioningService.get_snapshots(server_id)
|
||||
return jsonify({'snapshots': [s.to_dict() for s in snapshots]})
|
||||
|
||||
|
||||
@cloud_provisioning_bp.route('/servers/<int:server_id>/snapshots', methods=['POST'])
|
||||
@jwt_required()
|
||||
def create_snapshot(server_id):
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
data = request.get_json() or {}
|
||||
name = data.get('name', f'snapshot-{server_id}')
|
||||
try:
|
||||
snapshot = CloudProvisioningService.create_snapshot(server_id, name)
|
||||
return jsonify(snapshot.to_dict()), 201
|
||||
except ValueError as e:
|
||||
return jsonify({'error': str(e)}), 400
|
||||
|
||||
|
||||
@cloud_provisioning_bp.route('/snapshots/<int:snapshot_id>', methods=['DELETE'])
|
||||
@jwt_required()
|
||||
def delete_snapshot(snapshot_id):
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
if not CloudProvisioningService.delete_snapshot(snapshot_id):
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
return jsonify({'message': 'Snapshot deleted'})
|
||||
|
||||
|
||||
# --- Cost ---
|
||||
|
||||
@cloud_provisioning_bp.route('/costs', methods=['GET'])
|
||||
@jwt_required()
|
||||
def cost_summary():
|
||||
return jsonify(CloudProvisioningService.get_cost_summary())
|
||||
@@ -1,224 +0,0 @@
|
||||
"""FTP Server API endpoints for managing FTP services and users."""
|
||||
|
||||
from flask import Blueprint, request, jsonify
|
||||
|
||||
from ..middleware.rbac import admin_required, viewer_required
|
||||
from ..services.ftp_service import FTPService
|
||||
|
||||
ftp_bp = Blueprint('ftp', __name__)
|
||||
|
||||
|
||||
@ftp_bp.route('/status', methods=['GET'])
|
||||
@viewer_required
|
||||
def get_status():
|
||||
"""Get FTP server status."""
|
||||
result = FTPService.get_status()
|
||||
return jsonify(result), 200
|
||||
|
||||
|
||||
@ftp_bp.route('/service/<action>', methods=['POST'])
|
||||
@admin_required
|
||||
def control_service(action):
|
||||
"""Start, stop, restart, or reload FTP service."""
|
||||
if action not in ['start', 'stop', 'restart', 'reload']:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'Invalid action. Use: start, stop, restart, or reload'
|
||||
}), 400
|
||||
|
||||
data = request.get_json() or {}
|
||||
service = data.get('service') # Optional: specify vsftpd or proftpd
|
||||
|
||||
result = FTPService.control_service(service, action)
|
||||
|
||||
if result.get('success'):
|
||||
return jsonify(result), 200
|
||||
return jsonify(result), 400
|
||||
|
||||
|
||||
@ftp_bp.route('/config', methods=['GET'])
|
||||
@viewer_required
|
||||
def get_config():
|
||||
"""Get FTP server configuration."""
|
||||
service = request.args.get('service') # Optional
|
||||
result = FTPService.get_config(service)
|
||||
|
||||
if result.get('success'):
|
||||
return jsonify(result), 200
|
||||
return jsonify(result), 400
|
||||
|
||||
|
||||
@ftp_bp.route('/config', methods=['POST'])
|
||||
@admin_required
|
||||
def update_config():
|
||||
"""Update FTP server configuration."""
|
||||
data = request.get_json()
|
||||
|
||||
if not data:
|
||||
return jsonify({'success': False, 'error': 'Request body is required'}), 400
|
||||
|
||||
service = data.get('service')
|
||||
config_content = data.get('config')
|
||||
|
||||
if not config_content:
|
||||
return jsonify({'success': False, 'error': 'Configuration content is required'}), 400
|
||||
|
||||
result = FTPService.update_config(service, config_content)
|
||||
|
||||
if result.get('success'):
|
||||
return jsonify(result), 200
|
||||
return jsonify(result), 400
|
||||
|
||||
|
||||
@ftp_bp.route('/users', methods=['GET'])
|
||||
@viewer_required
|
||||
def list_users():
|
||||
"""List FTP users."""
|
||||
result = FTPService.list_users()
|
||||
|
||||
if result.get('success'):
|
||||
return jsonify(result), 200
|
||||
return jsonify(result), 400
|
||||
|
||||
|
||||
@ftp_bp.route('/users', methods=['POST'])
|
||||
@admin_required
|
||||
def create_user():
|
||||
"""Create a new FTP user."""
|
||||
data = request.get_json()
|
||||
|
||||
if not data:
|
||||
return jsonify({'success': False, 'error': 'Request body is required'}), 400
|
||||
|
||||
username = data.get('username')
|
||||
password = data.get('password') # Optional, can be auto-generated
|
||||
home_dir = data.get('home_dir') # Optional
|
||||
|
||||
if not username:
|
||||
return jsonify({'success': False, 'error': 'Username is required'}), 400
|
||||
|
||||
# Validate username
|
||||
if not username.isalnum() and '_' not in username:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'Username must contain only alphanumeric characters and underscores'
|
||||
}), 400
|
||||
|
||||
result = FTPService.create_user(username, password, home_dir)
|
||||
|
||||
if result.get('success'):
|
||||
return jsonify(result), 201
|
||||
return jsonify(result), 400
|
||||
|
||||
|
||||
@ftp_bp.route('/users/<username>', methods=['DELETE'])
|
||||
@admin_required
|
||||
def delete_user(username):
|
||||
"""Delete an FTP user."""
|
||||
delete_home = request.args.get('delete_home', 'false').lower() == 'true'
|
||||
|
||||
result = FTPService.delete_user(username, delete_home=delete_home)
|
||||
|
||||
if result.get('success'):
|
||||
return jsonify(result), 200
|
||||
return jsonify(result), 400
|
||||
|
||||
|
||||
@ftp_bp.route('/users/<username>/password', methods=['POST'])
|
||||
@admin_required
|
||||
def change_password(username):
|
||||
"""Change FTP user password."""
|
||||
data = request.get_json() or {}
|
||||
new_password = data.get('password') # Optional, can be auto-generated
|
||||
|
||||
result = FTPService.change_password(username, new_password)
|
||||
|
||||
if result.get('success'):
|
||||
return jsonify(result), 200
|
||||
return jsonify(result), 400
|
||||
|
||||
|
||||
@ftp_bp.route('/users/<username>/toggle', methods=['POST'])
|
||||
@admin_required
|
||||
def toggle_user(username):
|
||||
"""Enable or disable an FTP user."""
|
||||
data = request.get_json() or {}
|
||||
enabled = data.get('enabled', True)
|
||||
|
||||
result = FTPService.toggle_user(username, enabled)
|
||||
|
||||
if result.get('success'):
|
||||
return jsonify(result), 200
|
||||
return jsonify(result), 400
|
||||
|
||||
|
||||
@ftp_bp.route('/connections', methods=['GET'])
|
||||
@viewer_required
|
||||
def get_connections():
|
||||
"""Get active FTP connections."""
|
||||
result = FTPService.get_connections()
|
||||
|
||||
if result.get('success'):
|
||||
return jsonify(result), 200
|
||||
return jsonify(result), 400
|
||||
|
||||
|
||||
@ftp_bp.route('/connections/<int:pid>', methods=['DELETE'])
|
||||
@admin_required
|
||||
def disconnect_user(pid):
|
||||
"""Disconnect an active FTP session."""
|
||||
result = FTPService.disconnect_session(pid)
|
||||
|
||||
if result.get('success'):
|
||||
return jsonify(result), 200
|
||||
return jsonify(result), 400
|
||||
|
||||
|
||||
@ftp_bp.route('/logs', methods=['GET'])
|
||||
@viewer_required
|
||||
def get_logs():
|
||||
"""Get FTP server logs."""
|
||||
lines = request.args.get('lines', 100, type=int)
|
||||
|
||||
result = FTPService.get_logs(lines)
|
||||
|
||||
if result.get('success'):
|
||||
return jsonify(result), 200
|
||||
return jsonify(result), 400
|
||||
|
||||
|
||||
@ftp_bp.route('/install', methods=['POST'])
|
||||
@admin_required
|
||||
def install_ftp():
|
||||
"""Install FTP server (vsftpd or proftpd)."""
|
||||
data = request.get_json() or {}
|
||||
service = data.get('service', 'vsftpd')
|
||||
|
||||
if service not in ['vsftpd', 'proftpd']:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'Invalid service. Use: vsftpd or proftpd'
|
||||
}), 400
|
||||
|
||||
result = FTPService.install_ftp_server(service)
|
||||
|
||||
if result.get('success'):
|
||||
return jsonify(result), 200
|
||||
return jsonify(result), 400
|
||||
|
||||
|
||||
@ftp_bp.route('/test', methods=['POST'])
|
||||
@admin_required
|
||||
def test_connection():
|
||||
"""Test FTP connection."""
|
||||
data = request.get_json() or {}
|
||||
host = data.get('host', 'localhost')
|
||||
port = data.get('port', 21)
|
||||
username = data.get('username')
|
||||
password = data.get('password')
|
||||
|
||||
result = FTPService.test_connection(host, port, username, password)
|
||||
|
||||
if result.get('success'):
|
||||
return jsonify(result), 200
|
||||
return jsonify(result), 400
|
||||
@@ -336,6 +336,20 @@ def list_builtin():
|
||||
return jsonify({'builtin': list_builtin_extensions()})
|
||||
|
||||
|
||||
@plugins_bp.route('/recommendations', methods=['GET'])
|
||||
@jwt_required()
|
||||
def recommendations():
|
||||
"""Extensions recommended for the given onboarding use cases (setup wizard).
|
||||
|
||||
Query: ``?use_cases=wordpress,web-apps``. Returns each recommended
|
||||
extension's real display_name/description + install source, so the wizard
|
||||
can render checkboxes that install the actual extension on Finish."""
|
||||
from app.services.plugin_service import recommend_extensions_for_use_cases
|
||||
raw = request.args.get('use_cases', '')
|
||||
use_cases = [u.strip() for u in raw.split(',') if u.strip()]
|
||||
return jsonify({'recommendations': recommend_extensions_for_use_cases(use_cases)})
|
||||
|
||||
|
||||
@plugins_bp.route('/builtin/<slug>/install', methods=['POST'])
|
||||
@jwt_required()
|
||||
def install_builtin(slug):
|
||||
|
||||
@@ -1,205 +0,0 @@
|
||||
from flask import Blueprint, request, jsonify
|
||||
from flask_jwt_extended import jwt_required
|
||||
from app.services.status_page_service import StatusPageService
|
||||
|
||||
status_pages_bp = Blueprint('status_pages', __name__)
|
||||
|
||||
|
||||
def get_current_user():
|
||||
from flask_jwt_extended import get_jwt_identity
|
||||
from app.models.user import User
|
||||
return User.query.get(get_jwt_identity())
|
||||
|
||||
|
||||
# --- Public endpoints (no auth) ---
|
||||
|
||||
@status_pages_bp.route('/public/<slug>', methods=['GET'])
|
||||
def get_public_page(slug):
|
||||
data = StatusPageService.get_public_page(slug)
|
||||
if not data:
|
||||
return jsonify({'error': 'Status page not found'}), 404
|
||||
return jsonify(data)
|
||||
|
||||
|
||||
@status_pages_bp.route('/badge/<slug>', methods=['GET'])
|
||||
def get_badge(slug):
|
||||
badge = StatusPageService.get_badge(slug)
|
||||
if not badge:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
return jsonify(badge)
|
||||
|
||||
|
||||
# --- Admin endpoints ---
|
||||
|
||||
@status_pages_bp.route('/', methods=['GET'])
|
||||
@jwt_required()
|
||||
def list_pages():
|
||||
pages = StatusPageService.list_pages()
|
||||
return jsonify({'pages': [p.to_dict() for p in pages]})
|
||||
|
||||
|
||||
@status_pages_bp.route('/<int:page_id>', methods=['GET'])
|
||||
@jwt_required()
|
||||
def get_page(page_id):
|
||||
page = StatusPageService.get_page(page_id)
|
||||
if not page:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
return jsonify(page.to_dict())
|
||||
|
||||
|
||||
@status_pages_bp.route('/', methods=['POST'])
|
||||
@jwt_required()
|
||||
def create_page():
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
data = request.get_json()
|
||||
if not data or 'name' not in data or 'slug' not in data:
|
||||
return jsonify({'error': 'name and slug required'}), 400
|
||||
try:
|
||||
page = StatusPageService.create_page(data)
|
||||
return jsonify(page.to_dict()), 201
|
||||
except ValueError as e:
|
||||
return jsonify({'error': str(e)}), 400
|
||||
|
||||
|
||||
@status_pages_bp.route('/<int:page_id>', methods=['PUT'])
|
||||
@jwt_required()
|
||||
def update_page(page_id):
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
data = request.get_json()
|
||||
page = StatusPageService.update_page(page_id, data)
|
||||
if not page:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
return jsonify(page.to_dict())
|
||||
|
||||
|
||||
@status_pages_bp.route('/<int:page_id>', methods=['DELETE'])
|
||||
@jwt_required()
|
||||
def delete_page(page_id):
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
if not StatusPageService.delete_page(page_id):
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
return jsonify({'message': 'Status page deleted'})
|
||||
|
||||
|
||||
# --- Components ---
|
||||
|
||||
@status_pages_bp.route('/<int:page_id>/components', methods=['GET'])
|
||||
@jwt_required()
|
||||
def get_components(page_id):
|
||||
page = StatusPageService.get_page(page_id)
|
||||
if not page:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
return jsonify({'components': [c.to_dict() for c in page.components.all()]})
|
||||
|
||||
|
||||
@status_pages_bp.route('/<int:page_id>/components', methods=['POST'])
|
||||
@jwt_required()
|
||||
def create_component(page_id):
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
data = request.get_json()
|
||||
try:
|
||||
comp = StatusPageService.create_component(page_id, data)
|
||||
return jsonify(comp.to_dict()), 201
|
||||
except ValueError as e:
|
||||
return jsonify({'error': str(e)}), 400
|
||||
|
||||
|
||||
@status_pages_bp.route('/components/<int:comp_id>', methods=['PUT'])
|
||||
@jwt_required()
|
||||
def update_component(comp_id):
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
data = request.get_json()
|
||||
comp = StatusPageService.update_component(comp_id, data)
|
||||
if not comp:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
return jsonify(comp.to_dict())
|
||||
|
||||
|
||||
@status_pages_bp.route('/components/<int:comp_id>', methods=['DELETE'])
|
||||
@jwt_required()
|
||||
def delete_component(comp_id):
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
if not StatusPageService.delete_component(comp_id):
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
return jsonify({'message': 'Component deleted'})
|
||||
|
||||
|
||||
@status_pages_bp.route('/components/<int:comp_id>/check', methods=['POST'])
|
||||
@jwt_required()
|
||||
def run_check(comp_id):
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
hc = StatusPageService.run_check(comp_id)
|
||||
if not hc:
|
||||
return jsonify({'error': 'Component not found'}), 404
|
||||
return jsonify(hc.to_dict())
|
||||
|
||||
|
||||
@status_pages_bp.route('/components/<int:comp_id>/history', methods=['GET'])
|
||||
@jwt_required()
|
||||
def get_history(comp_id):
|
||||
hours = request.args.get('hours', 24, type=int)
|
||||
checks = StatusPageService.get_check_history(comp_id, hours)
|
||||
return jsonify({'checks': [c.to_dict() for c in checks]})
|
||||
|
||||
|
||||
# --- Incidents ---
|
||||
|
||||
@status_pages_bp.route('/<int:page_id>/incidents', methods=['GET'])
|
||||
@jwt_required()
|
||||
def list_incidents(page_id):
|
||||
page = StatusPageService.get_page(page_id)
|
||||
if not page:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
incidents = page.incidents.limit(50).all()
|
||||
return jsonify({'incidents': [i.to_dict() for i in incidents]})
|
||||
|
||||
|
||||
@status_pages_bp.route('/<int:page_id>/incidents', methods=['POST'])
|
||||
@jwt_required()
|
||||
def create_incident(page_id):
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
data = request.get_json()
|
||||
if not data or 'title' not in data:
|
||||
return jsonify({'error': 'title required'}), 400
|
||||
incident = StatusPageService.create_incident(page_id, data)
|
||||
return jsonify(incident.to_dict()), 201
|
||||
|
||||
|
||||
@status_pages_bp.route('/incidents/<int:incident_id>', methods=['PUT'])
|
||||
@jwt_required()
|
||||
def update_incident(incident_id):
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
data = request.get_json()
|
||||
incident = StatusPageService.update_incident(incident_id, data)
|
||||
if not incident:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
return jsonify(incident.to_dict())
|
||||
|
||||
|
||||
@status_pages_bp.route('/incidents/<int:incident_id>', methods=['DELETE'])
|
||||
@jwt_required()
|
||||
def delete_incident(incident_id):
|
||||
user = get_current_user()
|
||||
if not user or not user.is_admin:
|
||||
return jsonify({'error': 'Admin access required'}), 403
|
||||
if not StatusPageService.delete_incident(incident_id):
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
return jsonify({'message': 'Incident deleted'})
|
||||
@@ -1,123 +0,0 @@
|
||||
"""Tunnels API (roadmap Phase 1 — #9).
|
||||
|
||||
Brokers WireGuard pairings between two agents (a public-IP edge + a NAT'd
|
||||
private host) so a service behind NAT can be reached over the tunnel.
|
||||
See docs/REMOTE_ACCESS_ROADMAP.md.
|
||||
"""
|
||||
|
||||
from flask import Blueprint, request, jsonify
|
||||
from flask_jwt_extended import jwt_required, get_jwt_identity
|
||||
|
||||
from app.models.tunnel import Tunnel
|
||||
from app.services.tunnel_broker_service import TunnelBrokerService, TunnelBrokerError
|
||||
from app.services.tunnel_publish_service import TunnelPublishService, TunnelPublishError
|
||||
from app.middleware.rbac import developer_required
|
||||
|
||||
tunnels_bp = Blueprint('tunnels', __name__)
|
||||
|
||||
|
||||
def _error(e):
|
||||
return jsonify({'error': e.message, 'code': e.code}), e.status
|
||||
|
||||
|
||||
@tunnels_bp.route('/', methods=['GET'])
|
||||
@jwt_required()
|
||||
def list_tunnels():
|
||||
tunnels = Tunnel.query.order_by(Tunnel.created_at.desc()).all()
|
||||
return jsonify({'tunnels': [t.to_dict() for t in tunnels]})
|
||||
|
||||
|
||||
@tunnels_bp.route('/', methods=['POST'])
|
||||
@jwt_required()
|
||||
@developer_required
|
||||
def create_tunnel():
|
||||
data = request.get_json(silent=True) or {}
|
||||
edge = (data.get('edge_server_id') or '').strip()
|
||||
private = (data.get('private_server_id') or '').strip()
|
||||
name = (data.get('name') or '').strip() or None
|
||||
if not edge or not private:
|
||||
return jsonify({'error': 'edge_server_id and private_server_id are required'}), 400
|
||||
try:
|
||||
tunnel = TunnelBrokerService.create_tunnel(edge, private, name=name, user_id=get_jwt_identity())
|
||||
except TunnelBrokerError as e:
|
||||
return _error(e)
|
||||
body = tunnel.to_dict()
|
||||
fw = TunnelBrokerService.firewall_hint(tunnel.listen_port)
|
||||
auto = getattr(tunnel, 'firewall_status', None)
|
||||
if auto is not None:
|
||||
fw['auto_open'] = auto # outcome of the agent-driven open (#10)
|
||||
body['firewall'] = fw
|
||||
return jsonify(body), 201
|
||||
|
||||
|
||||
@tunnels_bp.route('/<tunnel_id>', methods=['GET'])
|
||||
@jwt_required()
|
||||
def get_tunnel(tunnel_id):
|
||||
try:
|
||||
tunnel = TunnelBrokerService.get_tunnel(tunnel_id)
|
||||
except TunnelBrokerError as e:
|
||||
return _error(e)
|
||||
# Default: refresh live status. Pass ?refresh=0 for the cached row only.
|
||||
if request.args.get('refresh', '1') in ('0', 'false', 'no'):
|
||||
return jsonify({'tunnel': tunnel.to_dict()})
|
||||
try:
|
||||
return jsonify(TunnelBrokerService.refresh_status(tunnel, user_id=get_jwt_identity()))
|
||||
except TunnelBrokerError as e:
|
||||
return _error(e)
|
||||
|
||||
|
||||
@tunnels_bp.route('/<tunnel_id>', methods=['DELETE'])
|
||||
@jwt_required()
|
||||
@developer_required
|
||||
def delete_tunnel(tunnel_id):
|
||||
try:
|
||||
TunnelBrokerService.teardown_tunnel(tunnel_id, user_id=get_jwt_identity())
|
||||
except TunnelBrokerError as e:
|
||||
return _error(e)
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
# ---- exposed services (Phase 2: publish a service over a tunnel) --------
|
||||
|
||||
@tunnels_bp.route('/<tunnel_id>/services', methods=['GET'])
|
||||
@jwt_required()
|
||||
def list_services(tunnel_id):
|
||||
services = TunnelPublishService.list_for_tunnel(tunnel_id)
|
||||
return jsonify({'services': [s.to_dict() for s in services]})
|
||||
|
||||
|
||||
@tunnels_bp.route('/<tunnel_id>/services', methods=['POST'])
|
||||
@jwt_required()
|
||||
@developer_required
|
||||
def publish_service(tunnel_id):
|
||||
data = request.get_json(silent=True) or {}
|
||||
hostname = (data.get('hostname') or '').strip()
|
||||
port = data.get('port')
|
||||
if not hostname or port is None:
|
||||
return jsonify({'error': 'hostname and port are required'}), 400
|
||||
try:
|
||||
svc, steps = TunnelPublishService.publish(
|
||||
tunnel_id, hostname, port,
|
||||
require_auth=bool(data.get('require_auth')),
|
||||
auth_username=(data.get('auth_username') or '').strip() or None,
|
||||
auth_password=data.get('auth_password'),
|
||||
ssl=data.get('ssl', True),
|
||||
email=(data.get('email') or '').strip() or None,
|
||||
user_id=get_jwt_identity(),
|
||||
)
|
||||
except TunnelPublishError as e:
|
||||
return _error(e)
|
||||
body = svc.to_dict()
|
||||
body['steps'] = steps
|
||||
return jsonify(body), 201
|
||||
|
||||
|
||||
@tunnels_bp.route('/<tunnel_id>/services/<service_id>', methods=['DELETE'])
|
||||
@jwt_required()
|
||||
@developer_required
|
||||
def unpublish_service(tunnel_id, service_id):
|
||||
try:
|
||||
TunnelPublishService.unpublish(service_id, user_id=get_jwt_identity())
|
||||
except TunnelPublishError as e:
|
||||
return _error(e)
|
||||
return jsonify({'success': True})
|
||||
@@ -90,10 +90,16 @@ def run_health_checks():
|
||||
from app.models.wordpress_site import WordPressSite
|
||||
from app.models.status_page import StatusComponent
|
||||
from app.services.environment_health_service import EnvironmentHealthService
|
||||
from app.services.status_page_service import StatusPageService
|
||||
from app.services.plugin_service import get_installed_extension_attr
|
||||
|
||||
_prune_old_health_checks()
|
||||
|
||||
# Status-page component sync lives in the serverkit-status extension (plan 47);
|
||||
# reach it only when installed. StatusComponent rows can't exist without it,
|
||||
# so a lean panel simply runs the health checks without the sync.
|
||||
StatusPageService = get_installed_extension_attr(
|
||||
'serverkit-status', 'status_page_service', 'StatusPageService')
|
||||
|
||||
sites = WordPressSite.query.filter_by(is_production=True).all()
|
||||
for site in sites:
|
||||
try:
|
||||
@@ -105,9 +111,10 @@ def run_health_checks():
|
||||
overall = result.get('overall_status')
|
||||
if not overall:
|
||||
continue
|
||||
components = StatusComponent.query.filter_by(wordpress_site_id=site.id).all()
|
||||
for comp in components:
|
||||
StatusPageService.sync_component_from_health(comp, overall)
|
||||
if StatusPageService is not None:
|
||||
components = StatusComponent.query.filter_by(wordpress_site_id=site.id).all()
|
||||
for comp in components:
|
||||
StatusPageService.sync_component_from_health(comp, overall)
|
||||
except Exception as e:
|
||||
logger.error(f'Health check failed for site {site.id}: {e}')
|
||||
try:
|
||||
|
||||
@@ -1,548 +0,0 @@
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from app import db
|
||||
from app.models.cloud_server import CloudProvider, CloudServer, CloudSnapshot
|
||||
from app.utils.crypto import encrypt_secret, decrypt_secret_safe, is_encrypted
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class CloudProvisioningService:
|
||||
"""Service for provisioning cloud servers via provider APIs."""
|
||||
|
||||
SUPPORTED_PROVIDERS = {
|
||||
'digitalocean': {
|
||||
'name': 'DigitalOcean',
|
||||
'regions': ['nyc1', 'nyc3', 'sfo3', 'ams3', 'lon1', 'fra1', 'sgp1', 'blr1', 'tor1', 'syd1'],
|
||||
'sizes': ['s-1vcpu-1gb', 's-1vcpu-2gb', 's-2vcpu-2gb', 's-2vcpu-4gb', 's-4vcpu-8gb', 's-8vcpu-16gb'],
|
||||
'images': ['ubuntu-22-04-x64', 'ubuntu-24-04-x64', 'debian-12-x64', 'centos-stream-9-x64', 'rocky-9-x64'],
|
||||
},
|
||||
'hetzner': {
|
||||
'name': 'Hetzner Cloud',
|
||||
'regions': ['nbg1', 'fsn1', 'hel1', 'ash', 'hil'],
|
||||
'sizes': ['cx22', 'cx32', 'cx42', 'cx52', 'cpx11', 'cpx21', 'cpx31'],
|
||||
'images': ['ubuntu-22.04', 'ubuntu-24.04', 'debian-12', 'centos-stream-9', 'rocky-9'],
|
||||
},
|
||||
'vultr': {
|
||||
'name': 'Vultr',
|
||||
'regions': ['ewr', 'ord', 'dfw', 'sea', 'lax', 'atl', 'ams', 'lhr', 'fra', 'nrt', 'icn', 'sgp', 'syd'],
|
||||
'sizes': ['vc2-1c-1gb', 'vc2-1c-2gb', 'vc2-2c-4gb', 'vc2-4c-8gb', 'vc2-6c-16gb'],
|
||||
'images': ['Ubuntu 22.04', 'Ubuntu 24.04', 'Debian 12', 'CentOS Stream 9'],
|
||||
},
|
||||
'linode': {
|
||||
'name': 'Linode (Akamai)',
|
||||
'regions': ['us-east', 'us-central', 'us-west', 'eu-west', 'eu-central', 'ap-south', 'ap-northeast', 'ap-southeast'],
|
||||
'sizes': ['g6-nanode-1', 'g6-standard-1', 'g6-standard-2', 'g6-standard-4', 'g6-standard-6'],
|
||||
'images': ['linode/ubuntu22.04', 'linode/ubuntu24.04', 'linode/debian12'],
|
||||
},
|
||||
}
|
||||
|
||||
# --- Providers ---
|
||||
|
||||
@staticmethod
|
||||
def list_providers():
|
||||
return CloudProvider.query.filter_by(is_active=True).all()
|
||||
|
||||
@staticmethod
|
||||
def get_provider(provider_id):
|
||||
return CloudProvider.query.get(provider_id)
|
||||
|
||||
@staticmethod
|
||||
def create_provider(data, user_id=None):
|
||||
ptype = data.get('provider_type')
|
||||
if ptype not in CloudProvisioningService.SUPPORTED_PROVIDERS:
|
||||
raise ValueError(f'Unsupported provider: {ptype}')
|
||||
|
||||
provider = CloudProvider(
|
||||
name=data.get('name', CloudProvisioningService.SUPPORTED_PROVIDERS[ptype]['name']),
|
||||
provider_type=ptype,
|
||||
api_key_encrypted=encrypt_secret(data['api_key']) if data.get('api_key') else '',
|
||||
created_by=user_id,
|
||||
)
|
||||
db.session.add(provider)
|
||||
db.session.commit()
|
||||
return provider
|
||||
|
||||
@staticmethod
|
||||
def delete_provider(provider_id):
|
||||
provider = CloudProvider.query.get(provider_id)
|
||||
if not provider:
|
||||
return False
|
||||
provider.is_active = False
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def get_provider_options(provider_type):
|
||||
return CloudProvisioningService.SUPPORTED_PROVIDERS.get(provider_type, {})
|
||||
|
||||
@staticmethod
|
||||
def encrypt_legacy_secrets():
|
||||
"""One-time, idempotent: encrypt any cloud-provider API tokens still stored
|
||||
in plaintext (the column predates encryption-at-rest)."""
|
||||
changed = 0
|
||||
for provider in CloudProvider.query.all():
|
||||
if provider.api_key_encrypted and not is_encrypted(provider.api_key_encrypted):
|
||||
provider.api_key_encrypted = encrypt_secret(provider.api_key_encrypted)
|
||||
changed += 1
|
||||
if changed:
|
||||
db.session.commit()
|
||||
return changed
|
||||
|
||||
# --- Servers ---
|
||||
|
||||
@staticmethod
|
||||
def list_servers(provider_id=None):
|
||||
query = CloudServer.query.filter(CloudServer.status != CloudServer.STATUS_DESTROYED)
|
||||
if provider_id:
|
||||
query = query.filter_by(provider_id=provider_id)
|
||||
return query.order_by(CloudServer.created_at.desc()).all()
|
||||
|
||||
@staticmethod
|
||||
def get_server(server_id):
|
||||
return CloudServer.query.get(server_id)
|
||||
|
||||
@staticmethod
|
||||
def create_server(data, user_id=None):
|
||||
"""Provision a new cloud server."""
|
||||
provider = CloudProvider.query.get(data['provider_id'])
|
||||
if not provider:
|
||||
raise ValueError('Provider not found')
|
||||
|
||||
server = CloudServer(
|
||||
provider_id=provider.id,
|
||||
name=data['name'],
|
||||
region=data.get('region'),
|
||||
size=data.get('size'),
|
||||
image=data.get('image'),
|
||||
ssh_key_id=data.get('ssh_key_id'),
|
||||
created_by=user_id,
|
||||
)
|
||||
db.session.add(server)
|
||||
db.session.commit()
|
||||
|
||||
# Call provider API to create server
|
||||
try:
|
||||
result = CloudProvisioningService._provider_create(provider, server, data)
|
||||
server.external_id = result.get('id')
|
||||
server.ip_address = result.get('ip_address')
|
||||
server.ipv6_address = result.get('ipv6_address')
|
||||
server.monthly_cost = result.get('monthly_cost', 0)
|
||||
server.status = CloudServer.STATUS_ACTIVE
|
||||
server.hostname = result.get('hostname', server.name)
|
||||
db.session.commit()
|
||||
except Exception as e:
|
||||
server.status = CloudServer.STATUS_ERROR
|
||||
server.server_metadata = {'error': str(e)}
|
||||
db.session.commit()
|
||||
raise
|
||||
|
||||
# Auto-install agent if requested
|
||||
if data.get('install_agent') and server.ip_address:
|
||||
try:
|
||||
CloudProvisioningService._install_agent(server)
|
||||
server.agent_installed = True
|
||||
db.session.commit()
|
||||
except Exception as e:
|
||||
logger.warning(f'Agent install failed for {server.name}: {e}')
|
||||
|
||||
return server
|
||||
|
||||
@staticmethod
|
||||
def destroy_server(server_id):
|
||||
server = CloudServer.query.get(server_id)
|
||||
if not server:
|
||||
return False
|
||||
|
||||
try:
|
||||
CloudProvisioningService._provider_destroy(server.provider, server)
|
||||
except Exception as e:
|
||||
logger.error(f'Provider destroy failed: {e}')
|
||||
|
||||
server.status = CloudServer.STATUS_DESTROYED
|
||||
server.destroyed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def resize_server(server_id, new_size):
|
||||
server = CloudServer.query.get(server_id)
|
||||
if not server:
|
||||
return None
|
||||
try:
|
||||
CloudProvisioningService._provider_resize(server.provider, server, new_size)
|
||||
server.size = new_size
|
||||
db.session.commit()
|
||||
return server
|
||||
except Exception as e:
|
||||
raise ValueError(f'Resize failed: {e}')
|
||||
|
||||
# --- Snapshots ---
|
||||
|
||||
@staticmethod
|
||||
def create_snapshot(server_id, name):
|
||||
server = CloudServer.query.get(server_id)
|
||||
if not server:
|
||||
raise ValueError('Server not found')
|
||||
|
||||
snapshot = CloudSnapshot(
|
||||
server_id=server_id,
|
||||
name=name,
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
result = CloudProvisioningService._provider_snapshot(server.provider, server, name)
|
||||
snapshot.external_id = result.get('id')
|
||||
snapshot.size_gb = result.get('size_gb')
|
||||
snapshot.status = 'available'
|
||||
db.session.commit()
|
||||
except Exception as e:
|
||||
snapshot.status = 'error'
|
||||
db.session.commit()
|
||||
raise
|
||||
|
||||
return snapshot
|
||||
|
||||
@staticmethod
|
||||
def get_snapshots(server_id):
|
||||
return CloudSnapshot.query.filter_by(server_id=server_id).order_by(CloudSnapshot.created_at.desc()).all()
|
||||
|
||||
@staticmethod
|
||||
def delete_snapshot(snapshot_id):
|
||||
snapshot = CloudSnapshot.query.get(snapshot_id)
|
||||
if not snapshot:
|
||||
return False
|
||||
# Delete from cloud provider first
|
||||
try:
|
||||
server = snapshot.server
|
||||
if server and server.provider:
|
||||
CloudProvisioningService._provider_delete_snapshot(
|
||||
server.provider, server, snapshot)
|
||||
except Exception as e:
|
||||
logger.warning(f'Provider snapshot delete failed: {e}')
|
||||
db.session.delete(snapshot)
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def get_cost_summary():
|
||||
"""Get total monthly cost across all active servers."""
|
||||
servers = CloudServer.query.filter(
|
||||
CloudServer.status.in_([CloudServer.STATUS_ACTIVE, CloudServer.STATUS_OFF])
|
||||
).all()
|
||||
|
||||
by_provider = {}
|
||||
total = 0
|
||||
for s in servers:
|
||||
key = s.provider.name if s.provider else 'Unknown'
|
||||
by_provider.setdefault(key, {'count': 0, 'cost': 0})
|
||||
by_provider[key]['count'] += 1
|
||||
by_provider[key]['cost'] += s.monthly_cost or 0
|
||||
total += s.monthly_cost or 0
|
||||
|
||||
return {
|
||||
'total_monthly': round(total, 2),
|
||||
'server_count': len(servers),
|
||||
'by_provider': by_provider,
|
||||
}
|
||||
|
||||
# --- Provider API helpers ---
|
||||
|
||||
@staticmethod
|
||||
def _auth_headers(provider):
|
||||
return {
|
||||
'Authorization': f'Bearer {decrypt_secret_safe(provider.api_key_encrypted)}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
# Vultr uses os_id integers instead of image name strings
|
||||
VULTR_OS_MAP = {
|
||||
'Ubuntu 22.04': 1743,
|
||||
'Ubuntu 24.04': 2284,
|
||||
'Debian 12': 2136,
|
||||
'CentOS Stream 9': 2072,
|
||||
}
|
||||
|
||||
# --- Provider API calls ---
|
||||
|
||||
@staticmethod
|
||||
def _provider_create(provider, server, data):
|
||||
"""Call provider API to create server. Returns dict with id, ip_address, etc."""
|
||||
import requests
|
||||
ptype = provider.provider_type
|
||||
headers = CloudProvisioningService._auth_headers(provider)
|
||||
|
||||
if ptype == 'digitalocean':
|
||||
resp = requests.post('https://api.digitalocean.com/v2/droplets', json={
|
||||
'name': server.name,
|
||||
'region': server.region,
|
||||
'size': server.size,
|
||||
'image': server.image,
|
||||
'ssh_keys': [data.get('ssh_key_id')] if data.get('ssh_key_id') else [],
|
||||
}, headers=headers, timeout=30)
|
||||
resp.raise_for_status()
|
||||
droplet = resp.json().get('droplet', {})
|
||||
networks = droplet.get('networks', {})
|
||||
ipv4 = next((n['ip_address'] for n in networks.get('v4', []) if n['type'] == 'public'), None)
|
||||
return {
|
||||
'id': str(droplet.get('id')),
|
||||
'ip_address': ipv4,
|
||||
'monthly_cost': droplet.get('size', {}).get('price_monthly', 0),
|
||||
}
|
||||
|
||||
elif ptype == 'hetzner':
|
||||
resp = requests.post('https://api.hetzner.cloud/v1/servers', json={
|
||||
'name': server.name,
|
||||
'server_type': server.size,
|
||||
'image': server.image,
|
||||
'location': server.region,
|
||||
}, headers=headers, timeout=30)
|
||||
resp.raise_for_status()
|
||||
srv = resp.json().get('server', {})
|
||||
return {
|
||||
'id': str(srv.get('id')),
|
||||
'ip_address': srv.get('public_net', {}).get('ipv4', {}).get('ip'),
|
||||
}
|
||||
|
||||
elif ptype == 'vultr':
|
||||
os_id = CloudProvisioningService.VULTR_OS_MAP.get(server.image, 1743)
|
||||
payload = {
|
||||
'region': server.region,
|
||||
'plan': server.size,
|
||||
'os_id': os_id,
|
||||
'label': server.name,
|
||||
'hostname': server.name,
|
||||
}
|
||||
if data.get('ssh_key_id'):
|
||||
payload['sshkey_id'] = [data['ssh_key_id']]
|
||||
resp = requests.post('https://api.vultr.com/v2/instances', json=payload,
|
||||
headers=headers, timeout=30)
|
||||
resp.raise_for_status()
|
||||
instance = resp.json().get('instance', {})
|
||||
return {
|
||||
'id': instance.get('id', ''),
|
||||
'ip_address': instance.get('main_ip'),
|
||||
'ipv6_address': instance.get('v6_main_ip'),
|
||||
'monthly_cost': instance.get('monthly_cost', 0),
|
||||
}
|
||||
|
||||
elif ptype == 'linode':
|
||||
payload = {
|
||||
'region': server.region,
|
||||
'type': server.size,
|
||||
'image': server.image,
|
||||
'label': server.name,
|
||||
'booted': True,
|
||||
}
|
||||
if data.get('root_pass'):
|
||||
payload['root_pass'] = data['root_pass']
|
||||
if data.get('ssh_key_id'):
|
||||
payload['authorized_keys'] = [data['ssh_key_id']]
|
||||
resp = requests.post('https://api.linode.com/v4/linode/instances', json=payload,
|
||||
headers=headers, timeout=30)
|
||||
resp.raise_for_status()
|
||||
linode = resp.json()
|
||||
ipv4_list = linode.get('ipv4', [])
|
||||
# Fetch monthly cost from the type endpoint
|
||||
monthly_cost = 0
|
||||
try:
|
||||
type_resp = requests.get(
|
||||
f'https://api.linode.com/v4/linode/types/{server.size}',
|
||||
headers=headers, timeout=10)
|
||||
if type_resp.ok:
|
||||
monthly_cost = type_resp.json().get('price', {}).get('monthly', 0)
|
||||
except Exception:
|
||||
pass
|
||||
return {
|
||||
'id': str(linode.get('id', '')),
|
||||
'ip_address': ipv4_list[0] if ipv4_list else None,
|
||||
'ipv6_address': linode.get('ipv6'),
|
||||
'monthly_cost': monthly_cost,
|
||||
}
|
||||
|
||||
raise ValueError(f'Unsupported provider type: {ptype}')
|
||||
|
||||
@staticmethod
|
||||
def _provider_destroy(provider, server):
|
||||
"""Delete server from the cloud provider."""
|
||||
if not server.external_id:
|
||||
return
|
||||
import requests
|
||||
ptype = provider.provider_type
|
||||
headers = CloudProvisioningService._auth_headers(provider)
|
||||
|
||||
if ptype == 'digitalocean':
|
||||
requests.delete(
|
||||
f'https://api.digitalocean.com/v2/droplets/{server.external_id}',
|
||||
headers=headers, timeout=30)
|
||||
|
||||
elif ptype == 'hetzner':
|
||||
requests.delete(
|
||||
f'https://api.hetzner.cloud/v1/servers/{server.external_id}',
|
||||
headers=headers, timeout=30)
|
||||
|
||||
elif ptype == 'vultr':
|
||||
requests.delete(
|
||||
f'https://api.vultr.com/v2/instances/{server.external_id}',
|
||||
headers=headers, timeout=30)
|
||||
|
||||
elif ptype == 'linode':
|
||||
requests.delete(
|
||||
f'https://api.linode.com/v4/linode/instances/{server.external_id}',
|
||||
headers=headers, timeout=30)
|
||||
|
||||
@staticmethod
|
||||
def _provider_resize(provider, server, new_size):
|
||||
"""Resize a server to a new plan/type."""
|
||||
if not server.external_id:
|
||||
raise ValueError('Server has no external ID')
|
||||
import requests
|
||||
ptype = provider.provider_type
|
||||
headers = CloudProvisioningService._auth_headers(provider)
|
||||
|
||||
if ptype == 'digitalocean':
|
||||
resp = requests.post(
|
||||
f'https://api.digitalocean.com/v2/droplets/{server.external_id}/actions',
|
||||
json={'type': 'resize', 'size': new_size, 'disk': True},
|
||||
headers=headers, timeout=30)
|
||||
resp.raise_for_status()
|
||||
|
||||
elif ptype == 'hetzner':
|
||||
resp = requests.post(
|
||||
f'https://api.hetzner.cloud/v1/servers/{server.external_id}/actions/change_type',
|
||||
json={'server_type': new_size, 'upgrade_disk': True},
|
||||
headers=headers, timeout=30)
|
||||
resp.raise_for_status()
|
||||
|
||||
elif ptype == 'vultr':
|
||||
resp = requests.patch(
|
||||
f'https://api.vultr.com/v2/instances/{server.external_id}',
|
||||
json={'plan': new_size},
|
||||
headers=headers, timeout=30)
|
||||
resp.raise_for_status()
|
||||
|
||||
elif ptype == 'linode':
|
||||
resp = requests.post(
|
||||
f'https://api.linode.com/v4/linode/instances/{server.external_id}/resize',
|
||||
json={'type': new_size, 'allow_auto_disk_resize': True},
|
||||
headers=headers, timeout=30)
|
||||
resp.raise_for_status()
|
||||
|
||||
else:
|
||||
raise ValueError(f'Unsupported provider type: {ptype}')
|
||||
|
||||
@staticmethod
|
||||
def _provider_snapshot(provider, server, name):
|
||||
"""Create a snapshot via the provider API. Returns dict with id, size_gb."""
|
||||
if not server.external_id:
|
||||
raise ValueError('Server has no external ID')
|
||||
import requests
|
||||
ptype = provider.provider_type
|
||||
headers = CloudProvisioningService._auth_headers(provider)
|
||||
|
||||
if ptype == 'digitalocean':
|
||||
resp = requests.post(
|
||||
f'https://api.digitalocean.com/v2/droplets/{server.external_id}/actions',
|
||||
json={'type': 'snapshot', 'name': name},
|
||||
headers=headers, timeout=30)
|
||||
resp.raise_for_status()
|
||||
# Snapshot ID isn't in the action response; fetch from droplet snapshots
|
||||
try:
|
||||
snap_resp = requests.get(
|
||||
f'https://api.digitalocean.com/v2/droplets/{server.external_id}/snapshots',
|
||||
headers=headers, timeout=15)
|
||||
if snap_resp.ok:
|
||||
snapshots = snap_resp.json().get('snapshots', [])
|
||||
if snapshots:
|
||||
latest = snapshots[-1]
|
||||
return {
|
||||
'id': str(latest.get('id')),
|
||||
'size_gb': latest.get('size_gigabytes', 0),
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
return {'id': None, 'size_gb': 0}
|
||||
|
||||
elif ptype == 'hetzner':
|
||||
resp = requests.post(
|
||||
f'https://api.hetzner.cloud/v1/servers/{server.external_id}/actions/create_image',
|
||||
json={'type': 'snapshot', 'description': name},
|
||||
headers=headers, timeout=30)
|
||||
resp.raise_for_status()
|
||||
image = resp.json().get('image', {})
|
||||
return {
|
||||
'id': str(image.get('id', '')),
|
||||
'size_gb': image.get('disk_size', 0),
|
||||
}
|
||||
|
||||
elif ptype == 'vultr':
|
||||
resp = requests.post('https://api.vultr.com/v2/snapshots', json={
|
||||
'instance_id': server.external_id,
|
||||
'description': name,
|
||||
}, headers=headers, timeout=30)
|
||||
resp.raise_for_status()
|
||||
snap = resp.json().get('snapshot', {})
|
||||
return {
|
||||
'id': snap.get('id', ''),
|
||||
'size_gb': round(snap.get('size', 0) / (1024 ** 3), 2) if snap.get('size') else 0,
|
||||
}
|
||||
|
||||
elif ptype == 'linode':
|
||||
resp = requests.post(
|
||||
f'https://api.linode.com/v4/linode/instances/{server.external_id}/backups',
|
||||
json={'label': name},
|
||||
headers=headers, timeout=30)
|
||||
resp.raise_for_status()
|
||||
backup = resp.json()
|
||||
return {
|
||||
'id': str(backup.get('id', '')),
|
||||
'size_gb': 0,
|
||||
}
|
||||
|
||||
raise ValueError(f'Unsupported provider type: {ptype}')
|
||||
|
||||
@staticmethod
|
||||
def _provider_delete_snapshot(provider, server, snapshot):
|
||||
"""Delete a snapshot from the provider."""
|
||||
if not snapshot.external_id:
|
||||
return
|
||||
import requests
|
||||
ptype = provider.provider_type
|
||||
headers = CloudProvisioningService._auth_headers(provider)
|
||||
|
||||
if ptype == 'digitalocean':
|
||||
requests.delete(
|
||||
f'https://api.digitalocean.com/v2/snapshots/{snapshot.external_id}',
|
||||
headers=headers, timeout=30)
|
||||
|
||||
elif ptype == 'hetzner':
|
||||
requests.delete(
|
||||
f'https://api.hetzner.cloud/v1/images/{snapshot.external_id}',
|
||||
headers=headers, timeout=30)
|
||||
|
||||
elif ptype == 'vultr':
|
||||
requests.delete(
|
||||
f'https://api.vultr.com/v2/snapshots/{snapshot.external_id}',
|
||||
headers=headers, timeout=30)
|
||||
|
||||
elif ptype == 'linode':
|
||||
requests.delete(
|
||||
f'https://api.linode.com/v4/linode/instances/{server.external_id}/backups/{snapshot.external_id}',
|
||||
headers=headers, timeout=30)
|
||||
|
||||
@staticmethod
|
||||
def _install_agent(server):
|
||||
"""SSH into server and run the ServerKit agent install script."""
|
||||
import subprocess
|
||||
if not server.ip_address:
|
||||
raise ValueError('Server has no IP address')
|
||||
# Use ssh with strict host key checking disabled for fresh servers
|
||||
install_cmd = 'curl -fsSL https://get.serverkit.dev/agent.sh | bash'
|
||||
result = subprocess.run(
|
||||
['ssh', '-o', 'StrictHostKeyChecking=no', '-o', 'ConnectTimeout=30',
|
||||
f'root@{server.ip_address}', install_cmd],
|
||||
capture_output=True, text=True, timeout=120)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(f'Agent install failed: {result.stderr}')
|
||||
@@ -108,6 +108,10 @@ GATED_BUILTIN_SLUGS = {
|
||||
}
|
||||
|
||||
_MARKER_KEY = 'extensions.auto_installed_slugs'
|
||||
# Slugs whose now-extracted backend has been re-acquired on an upgraded panel
|
||||
# (plan 47 Phase 2). Separate from _MARKER_KEY so the one-shot backend pickup
|
||||
# runs even for slugs already auto-installed frontend-only in a prior release.
|
||||
_BACKEND_ACQUIRED_KEY = 'extensions.backend_acquired_slugs'
|
||||
|
||||
|
||||
def _processed_slugs():
|
||||
@@ -193,3 +197,72 @@ def run_auto_install():
|
||||
|
||||
if changed:
|
||||
_save_processed(processed)
|
||||
|
||||
|
||||
def _backend_acquired_slugs():
|
||||
from app.services.settings_service import SettingsService
|
||||
raw = SettingsService.get(_BACKEND_ACQUIRED_KEY, '')
|
||||
if not raw:
|
||||
return set()
|
||||
try:
|
||||
return set(json.loads(raw))
|
||||
except (ValueError, TypeError):
|
||||
return {s.strip() for s in str(raw).split(',') if s.strip()}
|
||||
|
||||
|
||||
def run_backend_acquisition():
|
||||
"""Re-acquire the backend for converted builtins that gained one (plan 47).
|
||||
|
||||
Some builtins (ftp, cloud-provision, remote-access, status) first shipped as
|
||||
*frontend-only* extensions whose API was still served by CORE. Plan 47 moves
|
||||
that backend into the extension and deregisters it from core. On an upgraded
|
||||
panel that already installed such an extension frontend-only, the installed
|
||||
row has ``has_backend=False`` and no backend on disk — so without this pass
|
||||
the API would simply vanish. For each converted slug that is installed but
|
||||
missing the now-available backend, force-reinstall from ``builtin-extensions/``
|
||||
once (idempotent via a marker). Best-effort; never blocks startup.
|
||||
"""
|
||||
import os
|
||||
|
||||
done = _backend_acquired_slugs()
|
||||
try:
|
||||
from app.services import plugin_service
|
||||
builtins = {e['slug']: e for e in plugin_service.list_builtin_extensions()}
|
||||
except Exception as e:
|
||||
logger.warning(f'Backend acquisition skipped (builtins unavailable): {e}')
|
||||
return
|
||||
|
||||
changed = False
|
||||
for slug in CONVERTED_BUILTIN_SLUGS:
|
||||
if slug in done:
|
||||
continue
|
||||
entry = builtins.get(slug)
|
||||
# Only slugs that now actually ship a backend/ dir are candidates.
|
||||
if not entry or not os.path.isdir(os.path.join(entry['path'], 'backend')):
|
||||
continue
|
||||
row = InstalledPlugin.query.filter_by(slug=slug).first()
|
||||
if not row:
|
||||
# Not installed — run_auto_install handles fresh (re-)acquisition,
|
||||
# and a fresh panel discovers it in the Marketplace.
|
||||
continue
|
||||
backend_on_disk = os.path.isdir(
|
||||
os.path.join(plugin_service.BACKEND_PLUGINS_DIR, slug))
|
||||
if row.has_backend and backend_on_disk:
|
||||
done.add(slug)
|
||||
changed = True
|
||||
continue
|
||||
try:
|
||||
plugin_service.install_from_path(
|
||||
entry['path'], user_id=row.installed_by, force=True,
|
||||
source_type='builtin')
|
||||
logger.info(f'Acquired extracted backend for {slug} (plan 47)')
|
||||
done.add(slug)
|
||||
changed = True
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f'Backend acquisition for {slug} failed (retry next boot): {e}')
|
||||
continue # leave unmarked so we retry
|
||||
|
||||
if changed:
|
||||
from app.services.settings_service import SettingsService
|
||||
SettingsService.set(_BACKEND_ACQUIRED_KEY, json.dumps(sorted(done)))
|
||||
@@ -1,717 +0,0 @@
|
||||
"""FTP server management service for vsftpd and proftpd."""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import re
|
||||
|
||||
from app.utils.formatting import format_bytes
|
||||
from app.utils.system import PackageManager, ServiceControl, run_privileged, privileged_cmd
|
||||
try:
|
||||
import pwd
|
||||
except ImportError:
|
||||
# Provide a Windows-compatible alternative here
|
||||
pwd = None
|
||||
#import crypt
|
||||
from passlib.hash import sha512_crypt # Or your preferred hash scheme
|
||||
import platform
|
||||
import secrets
|
||||
from typing import Dict, List, Optional
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class FTPService:
|
||||
"""Service for managing FTP servers (vsftpd, proftpd)."""
|
||||
|
||||
# Configuration file locations
|
||||
VSFTPD_CONF = '/etc/vsftpd.conf'
|
||||
VSFTPD_USER_LIST = '/etc/vsftpd.userlist'
|
||||
PROFTPD_CONF = '/etc/proftpd/proftpd.conf'
|
||||
|
||||
# FTP user home base directory
|
||||
FTP_HOME_BASE = '/home/ftp'
|
||||
|
||||
@classmethod
|
||||
def get_status(cls) -> Dict:
|
||||
"""Get FTP server status and information."""
|
||||
vsftpd = cls._check_service('vsftpd')
|
||||
proftpd = cls._check_service('proftpd')
|
||||
|
||||
# Determine which server is installed/active
|
||||
active_server = None
|
||||
if vsftpd['installed'] and vsftpd['running']:
|
||||
active_server = 'vsftpd'
|
||||
elif proftpd['installed'] and proftpd['running']:
|
||||
active_server = 'proftpd'
|
||||
elif vsftpd['installed']:
|
||||
active_server = 'vsftpd'
|
||||
elif proftpd['installed']:
|
||||
active_server = 'proftpd'
|
||||
|
||||
return {
|
||||
'vsftpd': vsftpd,
|
||||
'proftpd': proftpd,
|
||||
'active_server': active_server,
|
||||
'any_installed': vsftpd['installed'] or proftpd['installed'],
|
||||
'any_running': vsftpd['running'] or proftpd['running']
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _check_service(cls, service: str) -> Dict:
|
||||
"""Check if a service is installed and running."""
|
||||
installed = False
|
||||
running = False
|
||||
enabled = False
|
||||
version = None
|
||||
|
||||
try:
|
||||
# Check if installed via which or package manager
|
||||
result = subprocess.run(
|
||||
['which', service],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
installed = result.returncode == 0
|
||||
|
||||
if not installed:
|
||||
installed = PackageManager.is_installed(service)
|
||||
|
||||
if installed:
|
||||
running = ServiceControl.is_active(service)
|
||||
enabled = ServiceControl.is_enabled(service)
|
||||
|
||||
# Get version
|
||||
if service == 'vsftpd':
|
||||
result = subprocess.run(
|
||||
['vsftpd', '-v'],
|
||||
capture_output=True, text=True, stderr=subprocess.STDOUT
|
||||
)
|
||||
version_match = re.search(r'version (\d+\.\d+\.\d+)', result.stdout)
|
||||
if version_match:
|
||||
version = version_match.group(1)
|
||||
elif service == 'proftpd':
|
||||
result = subprocess.run(
|
||||
['proftpd', '-v'],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
version_match = re.search(r'ProFTPD Version (\d+\.\d+\.\d+)', result.stdout)
|
||||
if version_match:
|
||||
version = version_match.group(1)
|
||||
|
||||
except (subprocess.SubprocessError, FileNotFoundError):
|
||||
pass
|
||||
|
||||
return {
|
||||
'installed': installed,
|
||||
'running': running,
|
||||
'enabled': enabled,
|
||||
'version': version
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def control_service(cls, service: str, action: str) -> Dict:
|
||||
"""Control FTP service (start, stop, restart, enable, disable)."""
|
||||
if service not in ['vsftpd', 'proftpd']:
|
||||
return {'success': False, 'error': 'Invalid service name'}
|
||||
|
||||
if action not in ['start', 'stop', 'restart', 'enable', 'disable']:
|
||||
return {'success': False, 'error': 'Invalid action'}
|
||||
|
||||
try:
|
||||
handler = getattr(ServiceControl, action)
|
||||
result = handler(service, timeout=30)
|
||||
|
||||
if result.returncode == 0:
|
||||
return {'success': True, 'service': service, 'action': action}
|
||||
else:
|
||||
return {'success': False, 'error': result.stderr or 'Operation failed'}
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
return {'success': False, 'error': 'Operation timed out'}
|
||||
except subprocess.SubprocessError as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def get_config(cls, service: str = None) -> Dict:
|
||||
"""Get FTP server configuration."""
|
||||
if service is None:
|
||||
status = cls.get_status()
|
||||
service = status['active_server']
|
||||
|
||||
if service == 'vsftpd':
|
||||
return cls._get_vsftpd_config()
|
||||
elif service == 'proftpd':
|
||||
return cls._get_proftpd_config()
|
||||
else:
|
||||
return {'success': False, 'error': 'No FTP server found'}
|
||||
|
||||
@classmethod
|
||||
def _get_vsftpd_config(cls) -> Dict:
|
||||
"""Parse vsftpd configuration."""
|
||||
if not os.path.exists(cls.VSFTPD_CONF):
|
||||
return {'success': False, 'error': 'vsftpd.conf not found'}
|
||||
|
||||
try:
|
||||
config = {}
|
||||
with open(cls.VSFTPD_CONF, 'r') as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line and not line.startswith('#'):
|
||||
if '=' in line:
|
||||
key, value = line.split('=', 1)
|
||||
config[key.strip()] = value.strip()
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'service': 'vsftpd',
|
||||
'config_file': cls.VSFTPD_CONF,
|
||||
'config': config,
|
||||
'settings': {
|
||||
'anonymous_enable': config.get('anonymous_enable', 'NO') == 'YES',
|
||||
'local_enable': config.get('local_enable', 'NO') == 'YES',
|
||||
'write_enable': config.get('write_enable', 'NO') == 'YES',
|
||||
'chroot_local_user': config.get('chroot_local_user', 'NO') == 'YES',
|
||||
'ssl_enable': config.get('ssl_enable', 'NO') == 'YES',
|
||||
'pasv_enable': config.get('pasv_enable', 'YES') == 'YES',
|
||||
'listen_port': int(config.get('listen_port', 21)),
|
||||
'max_clients': int(config.get('max_clients', 0)),
|
||||
'max_per_ip': int(config.get('max_per_ip', 0)),
|
||||
'local_umask': config.get('local_umask', '022'),
|
||||
}
|
||||
}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def _get_proftpd_config(cls) -> Dict:
|
||||
"""Parse proftpd configuration."""
|
||||
if not os.path.exists(cls.PROFTPD_CONF):
|
||||
return {'success': False, 'error': 'proftpd.conf not found'}
|
||||
|
||||
try:
|
||||
config = {}
|
||||
with open(cls.PROFTPD_CONF, 'r') as f:
|
||||
content = f.read()
|
||||
|
||||
# Parse basic directives
|
||||
directives = [
|
||||
'ServerName', 'ServerType', 'Port', 'MaxClients',
|
||||
'MaxClientsPerHost', 'DefaultRoot', 'RequireValidShell'
|
||||
]
|
||||
for directive in directives:
|
||||
match = re.search(rf'^{directive}\s+(.+)$', content, re.MULTILINE)
|
||||
if match:
|
||||
config[directive] = match.group(1).strip().strip('"')
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'service': 'proftpd',
|
||||
'config_file': cls.PROFTPD_CONF,
|
||||
'config': config,
|
||||
'settings': {
|
||||
'server_name': config.get('ServerName', 'ProFTPD'),
|
||||
'port': int(config.get('Port', 21)),
|
||||
'max_clients': int(config.get('MaxClients', 0)) if config.get('MaxClients') else 0,
|
||||
'max_per_ip': int(config.get('MaxClientsPerHost', 0)) if config.get('MaxClientsPerHost') else 0,
|
||||
'default_root': config.get('DefaultRoot', '~'),
|
||||
'require_valid_shell': config.get('RequireValidShell', 'on') == 'on',
|
||||
}
|
||||
}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def update_config(cls, service: str, settings: Dict) -> Dict:
|
||||
"""Update FTP server configuration."""
|
||||
if service == 'vsftpd':
|
||||
return cls._update_vsftpd_config(settings)
|
||||
elif service == 'proftpd':
|
||||
return cls._update_proftpd_config(settings)
|
||||
else:
|
||||
return {'success': False, 'error': 'Invalid service'}
|
||||
|
||||
@classmethod
|
||||
def _update_vsftpd_config(cls, settings: Dict) -> Dict:
|
||||
"""Update vsftpd configuration."""
|
||||
if not os.path.exists(cls.VSFTPD_CONF):
|
||||
return {'success': False, 'error': 'vsftpd.conf not found'}
|
||||
|
||||
try:
|
||||
# Read current config
|
||||
with open(cls.VSFTPD_CONF, 'r') as f:
|
||||
lines = f.readlines()
|
||||
|
||||
# Map settings to config keys
|
||||
mapping = {
|
||||
'anonymous_enable': ('anonymous_enable', lambda v: 'YES' if v else 'NO'),
|
||||
'local_enable': ('local_enable', lambda v: 'YES' if v else 'NO'),
|
||||
'write_enable': ('write_enable', lambda v: 'YES' if v else 'NO'),
|
||||
'chroot_local_user': ('chroot_local_user', lambda v: 'YES' if v else 'NO'),
|
||||
'ssl_enable': ('ssl_enable', lambda v: 'YES' if v else 'NO'),
|
||||
'listen_port': ('listen_port', str),
|
||||
'max_clients': ('max_clients', str),
|
||||
'max_per_ip': ('max_per_ip', str),
|
||||
'local_umask': ('local_umask', str),
|
||||
}
|
||||
|
||||
# Update lines
|
||||
updated_keys = set()
|
||||
for i, line in enumerate(lines):
|
||||
stripped = line.strip()
|
||||
if stripped and not stripped.startswith('#') and '=' in stripped:
|
||||
key = stripped.split('=')[0].strip()
|
||||
for setting_key, (config_key, transform) in mapping.items():
|
||||
if key == config_key and setting_key in settings:
|
||||
lines[i] = f"{config_key}={transform(settings[setting_key])}\n"
|
||||
updated_keys.add(config_key)
|
||||
|
||||
# Add missing settings
|
||||
for setting_key, (config_key, transform) in mapping.items():
|
||||
if setting_key in settings and config_key not in updated_keys:
|
||||
lines.append(f"{config_key}={transform(settings[setting_key])}\n")
|
||||
|
||||
# Write config
|
||||
with open(cls.VSFTPD_CONF, 'w') as f:
|
||||
f.writelines(lines)
|
||||
|
||||
return {'success': True, 'message': 'Configuration updated. Restart vsftpd to apply changes.'}
|
||||
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def _update_proftpd_config(cls, settings: Dict) -> Dict:
|
||||
"""Update proftpd configuration."""
|
||||
# Similar implementation for proftpd
|
||||
return {'success': False, 'error': 'ProFTPD configuration update not yet implemented'}
|
||||
|
||||
@classmethod
|
||||
def list_users(cls) -> Dict:
|
||||
"""List FTP users."""
|
||||
if pwd is None:
|
||||
return {'success': False, 'error': 'User management requires Linux'}
|
||||
|
||||
try:
|
||||
users = []
|
||||
|
||||
# Get system users that have FTP access
|
||||
# Check vsftpd userlist if exists
|
||||
allowed_users = set()
|
||||
if os.path.exists(cls.VSFTPD_USER_LIST):
|
||||
with open(cls.VSFTPD_USER_LIST, 'r') as f:
|
||||
allowed_users = set(line.strip() for line in f if line.strip())
|
||||
|
||||
# Get users from /etc/passwd with home in FTP directories
|
||||
for user in pwd.getpwall():
|
||||
# Skip system users
|
||||
if user.pw_uid < 1000 or user.pw_uid == 65534:
|
||||
continue
|
||||
|
||||
# Check if user has FTP-related home directory or is in userlist
|
||||
is_ftp_user = (
|
||||
user.pw_dir.startswith(cls.FTP_HOME_BASE) or
|
||||
user.pw_name in allowed_users or
|
||||
'/ftp' in user.pw_dir.lower()
|
||||
)
|
||||
|
||||
if is_ftp_user or allowed_users:
|
||||
home_exists = os.path.exists(user.pw_dir)
|
||||
home_size = 0
|
||||
if home_exists:
|
||||
try:
|
||||
for root, dirs, files in os.walk(user.pw_dir):
|
||||
for f in files:
|
||||
home_size += os.path.getsize(os.path.join(root, f))
|
||||
except (OSError, PermissionError):
|
||||
pass
|
||||
|
||||
users.append({
|
||||
'username': user.pw_name,
|
||||
'uid': user.pw_uid,
|
||||
'gid': user.pw_gid,
|
||||
'home': user.pw_dir,
|
||||
'shell': user.pw_shell,
|
||||
'home_exists': home_exists,
|
||||
'home_size': home_size,
|
||||
'home_size_human': cls._format_size(home_size),
|
||||
'in_userlist': user.pw_name in allowed_users,
|
||||
'is_active': user.pw_shell not in ['/usr/sbin/nologin', '/bin/false']
|
||||
})
|
||||
|
||||
return {'success': True, 'users': users}
|
||||
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def create_user(cls, username: str, password: str = None, home_dir: str = None) -> Dict:
|
||||
"""Create a new FTP user."""
|
||||
if pwd is None:
|
||||
return {'success': False, 'error': 'User management requires Linux'}
|
||||
|
||||
# Validate username
|
||||
if not re.match(r'^[a-z][a-z0-9_-]{2,31}$', username):
|
||||
return {'success': False, 'error': 'Invalid username. Use lowercase letters, numbers, underscore, hyphen. 3-32 chars.'}
|
||||
|
||||
# Check if user exists
|
||||
try:
|
||||
pwd.getpwnam(username)
|
||||
return {'success': False, 'error': 'User already exists'}
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
# Generate password if not provided
|
||||
if not password:
|
||||
password = secrets.token_urlsafe(16)
|
||||
|
||||
# Set home directory
|
||||
if not home_dir:
|
||||
home_dir = os.path.join(cls.FTP_HOME_BASE, username)
|
||||
|
||||
try:
|
||||
# Create user with restricted shell
|
||||
result = run_privileged([
|
||||
'useradd',
|
||||
'-m', # Create home directory
|
||||
'-d', home_dir,
|
||||
'-s', '/usr/sbin/nologin', # No shell access
|
||||
'-c', f'FTP User {username}',
|
||||
username
|
||||
])
|
||||
|
||||
if result.returncode != 0:
|
||||
return {'success': False, 'error': result.stderr or 'Failed to create user'}
|
||||
|
||||
# Set password
|
||||
proc = subprocess.Popen(
|
||||
privileged_cmd(['chpasswd']),
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE
|
||||
)
|
||||
stdout, stderr = proc.communicate(input=f'{username}:{password}'.encode())
|
||||
|
||||
if proc.returncode != 0:
|
||||
return {'success': False, 'error': stderr.decode() or 'Failed to set password'}
|
||||
|
||||
# Add to vsftpd userlist if it exists
|
||||
if os.path.exists(cls.VSFTPD_USER_LIST):
|
||||
with open(cls.VSFTPD_USER_LIST, 'a') as f:
|
||||
f.write(f'{username}\n')
|
||||
|
||||
# Set proper permissions on home directory
|
||||
run_privileged(['chmod', '755', home_dir])
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'username': username,
|
||||
'password': password,
|
||||
'home': home_dir,
|
||||
'message': 'FTP user created successfully'
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def delete_user(cls, username: str, delete_home: bool = False) -> Dict:
|
||||
"""Delete an FTP user."""
|
||||
if pwd is None:
|
||||
return {'success': False, 'error': 'User management requires Linux'}
|
||||
|
||||
try:
|
||||
# Check if user exists
|
||||
try:
|
||||
pwd.getpwnam(username)
|
||||
except KeyError:
|
||||
return {'success': False, 'error': 'User not found'}
|
||||
|
||||
# Delete user
|
||||
cmd = ['userdel']
|
||||
if delete_home:
|
||||
cmd.append('-r')
|
||||
cmd.append(username)
|
||||
|
||||
result = run_privileged(cmd)
|
||||
|
||||
if result.returncode != 0:
|
||||
return {'success': False, 'error': result.stderr or 'Failed to delete user'}
|
||||
|
||||
# Remove from vsftpd userlist if exists
|
||||
if os.path.exists(cls.VSFTPD_USER_LIST):
|
||||
with open(cls.VSFTPD_USER_LIST, 'r') as f:
|
||||
users = [line.strip() for line in f if line.strip() != username]
|
||||
with open(cls.VSFTPD_USER_LIST, 'w') as f:
|
||||
f.write('\n'.join(users) + '\n')
|
||||
|
||||
return {'success': True, 'message': f'User {username} deleted'}
|
||||
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def change_password(cls, username: str, new_password: str = None) -> Dict:
|
||||
"""Change FTP user password."""
|
||||
if pwd is None:
|
||||
return {'success': False, 'error': 'User management requires Linux'}
|
||||
|
||||
try:
|
||||
# Check if user exists
|
||||
try:
|
||||
pwd.getpwnam(username)
|
||||
except KeyError:
|
||||
return {'success': False, 'error': 'User not found'}
|
||||
|
||||
# Generate password if not provided
|
||||
if not new_password:
|
||||
new_password = secrets.token_urlsafe(16)
|
||||
|
||||
# Set password
|
||||
proc = subprocess.Popen(
|
||||
privileged_cmd(['chpasswd']),
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE
|
||||
)
|
||||
stdout, stderr = proc.communicate(input=f'{username}:{new_password}'.encode())
|
||||
|
||||
if proc.returncode != 0:
|
||||
return {'success': False, 'error': stderr.decode() or 'Failed to change password'}
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'username': username,
|
||||
'password': new_password,
|
||||
'message': 'Password changed successfully'
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def get_connections(cls) -> Dict:
|
||||
"""Get active FTP connections."""
|
||||
try:
|
||||
connections = []
|
||||
|
||||
# Check for vsftpd connections
|
||||
result = subprocess.run(
|
||||
['ss', '-tnp', 'state', 'established', 'sport', '=', ':21'],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
|
||||
for line in result.stdout.strip().split('\n')[1:]: # Skip header
|
||||
if line:
|
||||
parts = line.split()
|
||||
if len(parts) >= 5:
|
||||
local = parts[3]
|
||||
remote = parts[4]
|
||||
connections.append({
|
||||
'local': local,
|
||||
'remote': remote,
|
||||
'state': 'ESTABLISHED'
|
||||
})
|
||||
|
||||
return {'success': True, 'connections': connections, 'count': len(connections)}
|
||||
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def get_logs(cls, lines: int = 100) -> Dict:
|
||||
"""Get FTP server logs."""
|
||||
log_files = [
|
||||
'/var/log/vsftpd.log',
|
||||
'/var/log/proftpd/proftpd.log',
|
||||
'/var/log/xferlog',
|
||||
'/var/log/syslog'
|
||||
]
|
||||
|
||||
for log_file in log_files:
|
||||
if os.path.exists(log_file):
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['tail', '-n', str(lines), log_file],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
# Filter FTP-related entries if using syslog
|
||||
log_content = result.stdout
|
||||
if 'syslog' in log_file:
|
||||
log_content = '\n'.join(
|
||||
line for line in log_content.split('\n')
|
||||
if 'ftp' in line.lower() or 'vsftpd' in line.lower() or 'proftpd' in line.lower()
|
||||
)
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'log_file': log_file,
|
||||
'content': log_content
|
||||
}
|
||||
except Exception as e:
|
||||
continue
|
||||
|
||||
return {'success': False, 'error': 'No FTP log files found'}
|
||||
|
||||
@classmethod
|
||||
def toggle_user(cls, username: str, enabled: bool) -> Dict:
|
||||
"""Enable or disable an FTP user."""
|
||||
if pwd is None:
|
||||
return {'success': False, 'error': 'User management requires Linux'}
|
||||
|
||||
try:
|
||||
# Check if user exists
|
||||
try:
|
||||
pwd.getpwnam(username)
|
||||
except KeyError:
|
||||
return {'success': False, 'error': 'User not found'}
|
||||
|
||||
if enabled:
|
||||
# Change shell to allow FTP (but still no login)
|
||||
shell = '/usr/sbin/nologin'
|
||||
else:
|
||||
# Change shell to /bin/false to disable
|
||||
shell = '/bin/false'
|
||||
|
||||
result = run_privileged(
|
||||
['usermod', '-s', shell, username]
|
||||
)
|
||||
|
||||
if result.returncode != 0:
|
||||
return {'success': False, 'error': result.stderr or 'Failed to update user'}
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'username': username,
|
||||
'enabled': enabled,
|
||||
'message': f'User {username} {"enabled" if enabled else "disabled"}'
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def disconnect_session(cls, pid: int) -> Dict:
|
||||
"""Disconnect an active FTP session by PID."""
|
||||
try:
|
||||
result = run_privileged(
|
||||
['kill', str(pid)]
|
||||
)
|
||||
|
||||
if result.returncode != 0:
|
||||
return {'success': False, 'error': result.stderr or 'Failed to disconnect session'}
|
||||
|
||||
return {'success': True, 'message': f'Session {pid} disconnected'}
|
||||
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def install_ftp_server(cls, service: str = 'vsftpd') -> Dict:
|
||||
"""Install FTP server (vsftpd or proftpd)."""
|
||||
if service not in ['vsftpd', 'proftpd']:
|
||||
return {'success': False, 'error': 'Invalid service. Use vsftpd or proftpd'}
|
||||
|
||||
try:
|
||||
result = PackageManager.install(service)
|
||||
|
||||
if result.returncode != 0:
|
||||
return {'success': False, 'error': result.stderr or 'Installation failed'}
|
||||
|
||||
# Create FTP home base directory
|
||||
os.makedirs(cls.FTP_HOME_BASE, exist_ok=True)
|
||||
|
||||
# Create default configuration for vsftpd
|
||||
if service == 'vsftpd':
|
||||
default_config = """# vsftpd configuration
|
||||
listen=YES
|
||||
listen_ipv6=NO
|
||||
anonymous_enable=NO
|
||||
local_enable=YES
|
||||
write_enable=YES
|
||||
local_umask=022
|
||||
dirmessage_enable=YES
|
||||
use_localtime=YES
|
||||
xferlog_enable=YES
|
||||
connect_from_port_20=YES
|
||||
chroot_local_user=YES
|
||||
allow_writeable_chroot=YES
|
||||
secure_chroot_dir=/var/run/vsftpd/empty
|
||||
pam_service_name=vsftpd
|
||||
rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
|
||||
rsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
|
||||
ssl_enable=NO
|
||||
userlist_enable=YES
|
||||
userlist_file=/etc/vsftpd.userlist
|
||||
userlist_deny=NO
|
||||
"""
|
||||
with open(cls.VSFTPD_CONF, 'w') as f:
|
||||
f.write(default_config)
|
||||
|
||||
# Create empty userlist
|
||||
with open(cls.VSFTPD_USER_LIST, 'w') as f:
|
||||
f.write('')
|
||||
|
||||
# Enable and start the service
|
||||
ServiceControl.enable(service)
|
||||
ServiceControl.start(service)
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'service': service,
|
||||
'message': f'{service} installed and started successfully'
|
||||
}
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
return {'success': False, 'error': 'Installation timed out'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@classmethod
|
||||
def test_connection(cls, host: str = 'localhost', port: int = 21,
|
||||
username: str = None, password: str = None) -> Dict:
|
||||
"""Test FTP connection."""
|
||||
import socket
|
||||
|
||||
try:
|
||||
# Basic connection test
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.settimeout(10)
|
||||
result = sock.connect_ex((host, port))
|
||||
sock.close()
|
||||
|
||||
if result != 0:
|
||||
return {
|
||||
'success': False,
|
||||
'error': f'Cannot connect to {host}:{port}'
|
||||
}
|
||||
|
||||
# If credentials provided, try to authenticate
|
||||
if username and password:
|
||||
try:
|
||||
from ftplib import FTP
|
||||
ftp = FTP()
|
||||
ftp.connect(host, port, timeout=10)
|
||||
ftp.login(username, password)
|
||||
ftp.quit()
|
||||
return {
|
||||
'success': True,
|
||||
'message': f'Successfully connected and authenticated to {host}:{port}'
|
||||
}
|
||||
except Exception as e:
|
||||
return {
|
||||
'success': False,
|
||||
'error': f'Connection succeeded but authentication failed: {str(e)}'
|
||||
}
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'message': f'FTP server is reachable at {host}:{port}'
|
||||
}
|
||||
|
||||
except socket.timeout:
|
||||
return {'success': False, 'error': 'Connection timed out'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'error': str(e)}
|
||||
|
||||
@staticmethod
|
||||
def _format_size(size: int) -> str:
|
||||
"""Format size in human-readable format."""
|
||||
return format_bytes(size, suffix_sep=' ')
|
||||
@@ -65,6 +65,14 @@ BUILTIN_EXTENSIONS_DIR = os.environ.get(
|
||||
FLAGSHIP_SLUGS = ['serverkit-wordpress', 'serverkit-cloudflare-ops']
|
||||
_FLAGSHIP_UNINSTALLED_KEY = 'extensions.flagship_uninstalled'
|
||||
|
||||
# Wizard-optional flagships (plan 47): offered — not force-installed — during
|
||||
# onboarding. On a FRESH install (setup wizard not yet completed) the boot-time
|
||||
# seeder skips these so the panel stays lean; the wizard installs them only when
|
||||
# their use case is picked. Existing installs (setup already completed) keep the
|
||||
# prior always-seeded behavior — zero regression. cloudflare-ops is NOT here: it
|
||||
# is route-only (no sidebar item) and stays seeded for the CF connection surface.
|
||||
WIZARD_OPTIONAL_FLAGSHIP_SLUGS = ['serverkit-wordpress']
|
||||
|
||||
|
||||
def _ensure_builtin_backend_importable(slug):
|
||||
"""Register ``builtin-extensions/<slug>/backend`` as the dashed package
|
||||
@@ -1560,6 +1568,104 @@ def list_builtin_extensions():
|
||||
return out
|
||||
|
||||
|
||||
# ── Onboarding wizard: use-case → recommended extension slugs (plan 47) ──
|
||||
#
|
||||
# Drives the setup wizard's "Recommended for you" install checkboxes. Every slug
|
||||
# here MUST resolve to a real bundled builtin (builtin-extensions/) or a registry
|
||||
# entry — guarded by tests/test_onboarding_recommendations.py so the map can never
|
||||
# point at a dead slug. Order within a use case is significant; the resolver
|
||||
# de-dupes across the selected use cases preserving first-seen order.
|
||||
RECOMMENDED_EXTENSIONS_BY_USE_CASE = {
|
||||
'wordpress': ['serverkit-wordpress'],
|
||||
'web-apps': ['serverkit-git', 'serverkit-status'],
|
||||
'self-hosted': ['serverkit-dns-server', 'serverkit-status', 'serverkit-mail'],
|
||||
'devops': ['serverkit-k8s', 'serverkit-tramo', 'serverkit-git'],
|
||||
}
|
||||
|
||||
|
||||
def _recommendation_index():
|
||||
"""slug -> {slug, display_name, description, category, source, installed,
|
||||
status}. Merges the registry catalog with bundled builtins so a recommended
|
||||
slug resolves regardless of where it lives; builtins win on slug collision."""
|
||||
index = {}
|
||||
try:
|
||||
from app.services import registry_service
|
||||
for entry in registry_service.list_catalog(include_bundled=True):
|
||||
slug = entry.get('slug')
|
||||
if not slug:
|
||||
continue
|
||||
index[slug] = {
|
||||
'slug': slug,
|
||||
'display_name': entry.get('display_name') or slug,
|
||||
'description': entry.get('description') or '',
|
||||
'category': entry.get('category') or 'utility',
|
||||
'source': 'registry',
|
||||
'installed': bool(entry.get('installed')),
|
||||
'status': entry.get('status') or 'not_installed',
|
||||
}
|
||||
except Exception as e:
|
||||
logger.debug(f'Registry unavailable for onboarding recommendations: {e}')
|
||||
for entry in list_builtin_extensions():
|
||||
manifest = entry.get('manifest') or {}
|
||||
slug = entry['slug']
|
||||
index[slug] = {
|
||||
'slug': slug,
|
||||
'display_name': manifest.get('display_name') or slug,
|
||||
'description': manifest.get('description') or '',
|
||||
'category': manifest.get('category') or 'utility',
|
||||
'source': 'builtin',
|
||||
'installed': bool(entry.get('installed')),
|
||||
'status': entry.get('status') or 'not_installed',
|
||||
}
|
||||
return index
|
||||
|
||||
|
||||
def recommend_extensions_for_use_cases(use_cases):
|
||||
"""Resolve selected onboarding use cases to installable extension metadata.
|
||||
|
||||
Returns a de-duped, order-preserving list of dicts (one per recommended
|
||||
extension). Slugs that don't resolve to a builtin/registry entry are silently
|
||||
dropped (defensive — the map is test-guarded against dead slugs)."""
|
||||
index = _recommendation_index()
|
||||
seen = set()
|
||||
out = []
|
||||
for use_case in (use_cases or []):
|
||||
for slug in RECOMMENDED_EXTENSIONS_BY_USE_CASE.get(use_case, []):
|
||||
if slug in seen:
|
||||
continue
|
||||
seen.add(slug)
|
||||
meta = index.get(slug)
|
||||
if meta:
|
||||
out.append(meta)
|
||||
return out
|
||||
|
||||
|
||||
def finalize_setup_flagships():
|
||||
"""Keep the panel lean after onboarding completes: any wizard-optional
|
||||
flagship (WordPress) the user didn't install during the wizard gets the
|
||||
uninstall marker so the boot-time flagship seeder won't re-add it on later
|
||||
boots. Called from the complete-onboarding endpoint (plan 47)."""
|
||||
for slug in WIZARD_OPTIONAL_FLAGSHIP_SLUGS:
|
||||
if not InstalledPlugin.query.filter_by(slug=slug).first():
|
||||
_set_flagship_uninstalled(slug, True)
|
||||
|
||||
|
||||
def get_installed_extension_attr(slug, module, attr, default=None):
|
||||
"""Return ``attr`` from an installed extension's backend module, else default.
|
||||
|
||||
A core seam that calls into a feature which now lives in an extracted
|
||||
extension (plan 47) uses this so it no-ops cleanly when the extension isn't
|
||||
installed. Resolves ``app.plugins.<slug>.<module>`` (the dashed package the
|
||||
plugin loader wires up on install); any import/lookup failure yields
|
||||
``default``."""
|
||||
try:
|
||||
import importlib
|
||||
mod = importlib.import_module(f'app.plugins.{slug}.{module}')
|
||||
return getattr(mod, attr, default)
|
||||
except Exception:
|
||||
return default
|
||||
|
||||
|
||||
def install_builtin_extension(slug, user_id=None):
|
||||
"""Install a builtin extension by its slug (folder lookup)."""
|
||||
if not os.path.isdir(BUILTIN_EXTENSIONS_DIR):
|
||||
@@ -1682,6 +1788,26 @@ def _seed_flagship_row(entry):
|
||||
return plugin
|
||||
|
||||
|
||||
def _wizard_optional_flagships_suppressed():
|
||||
"""True when wizard-optional flagships (WordPress) should NOT be boot-seeded:
|
||||
a fresh install whose setup wizard hasn't completed (plan 47).
|
||||
|
||||
Bypassed under TESTING so the extensive WordPress test suite keeps its
|
||||
seeded flagship; the real gate is exercised by dedicated proving tests that
|
||||
toggle ``app.config['TESTING']``."""
|
||||
try:
|
||||
from flask import current_app
|
||||
if current_app and current_app.config.get('TESTING'):
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
from app.services.settings_service import SettingsService
|
||||
return bool(SettingsService.needs_setup())
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def seed_flagship_extensions():
|
||||
"""Ensure bundled flagship extensions (D4) have an active row on EVERY panel
|
||||
— fresh AND upgrade — unless the user explicitly uninstalled them.
|
||||
@@ -1690,10 +1816,16 @@ def seed_flagship_extensions():
|
||||
picks up the seeded row and registers the blueprints (in-place). Best-effort.
|
||||
"""
|
||||
uninstalled = _flagship_uninstalled_set()
|
||||
suppress_optional = _wizard_optional_flagships_suppressed()
|
||||
available = {e['slug']: e for e in list_builtin_extensions()}
|
||||
for slug in FLAGSHIP_SLUGS:
|
||||
if slug in uninstalled:
|
||||
continue
|
||||
# Fresh install (plan 47): don't seed wizard-optional flagships (WordPress)
|
||||
# until the setup wizard installs them. Existing/completed-setup installs
|
||||
# fall through and seed as before.
|
||||
if suppress_optional and slug in WIZARD_OPTIONAL_FLAGSHIP_SLUGS:
|
||||
continue
|
||||
entry = available.get(slug)
|
||||
if not entry:
|
||||
continue
|
||||
|
||||
@@ -54,6 +54,11 @@ class SettingsService:
|
||||
'type': 'json',
|
||||
'description': 'Use cases selected during onboarding wizard'
|
||||
},
|
||||
'onboarding_installed_extensions': {
|
||||
'value': [],
|
||||
'type': 'json',
|
||||
'description': 'Extension slugs installed by the setup wizard'
|
||||
},
|
||||
'dev_mode': {
|
||||
'value': False,
|
||||
'type': 'boolean',
|
||||
|
||||
@@ -1,425 +0,0 @@
|
||||
import logging
|
||||
import socket
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from app import db
|
||||
from app.models.status_page import (
|
||||
StatusPage, StatusComponent, HealthCheck, StatusIncident, StatusIncidentUpdate
|
||||
)
|
||||
from app.utils.slug import validate_slug
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class StatusPageService:
|
||||
"""Service for public status pages and automated health checks."""
|
||||
|
||||
@staticmethod
|
||||
def normalize_slug(value):
|
||||
return validate_slug(value)
|
||||
|
||||
# --- Pages ---
|
||||
|
||||
@staticmethod
|
||||
def list_pages():
|
||||
return StatusPage.query.order_by(StatusPage.name).all()
|
||||
|
||||
@staticmethod
|
||||
def get_page(page_id):
|
||||
return StatusPage.query.get(page_id)
|
||||
|
||||
@staticmethod
|
||||
def get_page_by_slug(slug):
|
||||
return StatusPage.query.filter_by(slug=slug).first()
|
||||
|
||||
@staticmethod
|
||||
def create_page(data):
|
||||
slug = StatusPageService.normalize_slug(data.get('slug'))
|
||||
if StatusPage.query.filter_by(slug=slug).first():
|
||||
raise ValueError(f"Status page '{slug}' already exists")
|
||||
|
||||
page = StatusPage(
|
||||
name=data['name'],
|
||||
slug=slug,
|
||||
description=data.get('description', ''),
|
||||
logo_url=data.get('logo_url'),
|
||||
primary_color=data.get('primary_color', '#4f46e5'),
|
||||
custom_domain=data.get('custom_domain'),
|
||||
is_public=data.get('is_public', True),
|
||||
show_uptime=data.get('show_uptime', True),
|
||||
show_history=data.get('show_history', True),
|
||||
)
|
||||
db.session.add(page)
|
||||
db.session.commit()
|
||||
return page
|
||||
|
||||
@staticmethod
|
||||
def update_page(page_id, data):
|
||||
page = StatusPage.query.get(page_id)
|
||||
if not page:
|
||||
return None
|
||||
for field in ['name', 'description', 'logo_url', 'primary_color',
|
||||
'custom_domain', 'is_public', 'show_uptime', 'show_history']:
|
||||
if field in data:
|
||||
setattr(page, field, data[field])
|
||||
db.session.commit()
|
||||
return page
|
||||
|
||||
@staticmethod
|
||||
def delete_page(page_id):
|
||||
page = StatusPage.query.get(page_id)
|
||||
if not page:
|
||||
return False
|
||||
db.session.delete(page)
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def get_public_page(slug):
|
||||
"""Get public status page data (no auth required)."""
|
||||
page = StatusPage.query.filter_by(slug=slug, is_public=True).first()
|
||||
if not page:
|
||||
return None
|
||||
|
||||
# Internal probe config must not appear on the unauthenticated public page
|
||||
# (a health-driven WP component may carry an internal localhost:port target).
|
||||
public_hidden = ('check_type', 'check_target', 'check_interval', 'check_timeout')
|
||||
components = page.components.all()
|
||||
grouped = {}
|
||||
for comp in components:
|
||||
group = comp.group or 'Services'
|
||||
cd = comp.to_dict()
|
||||
for k in public_hidden:
|
||||
cd.pop(k, None)
|
||||
grouped.setdefault(group, []).append(cd)
|
||||
|
||||
# Active incidents
|
||||
active_incidents = page.incidents.filter(
|
||||
StatusIncident.status != 'resolved'
|
||||
).limit(10).all()
|
||||
|
||||
# Recent resolved
|
||||
resolved = page.incidents.filter_by(status='resolved').limit(5).all()
|
||||
|
||||
# Overall status
|
||||
statuses = [c.status for c in components]
|
||||
if any(s == 'major_outage' for s in statuses):
|
||||
overall = 'major_outage'
|
||||
elif any(s in ('partial_outage', 'degraded') for s in statuses):
|
||||
overall = 'degraded'
|
||||
elif any(s == 'maintenance' for s in statuses):
|
||||
overall = 'maintenance'
|
||||
else:
|
||||
overall = 'operational'
|
||||
|
||||
return {
|
||||
'page': page.to_dict(),
|
||||
'overall_status': overall,
|
||||
'groups': grouped,
|
||||
'active_incidents': [i.to_dict() for i in active_incidents],
|
||||
'recent_incidents': [i.to_dict() for i in resolved],
|
||||
}
|
||||
|
||||
# --- Components ---
|
||||
|
||||
@staticmethod
|
||||
def create_component(page_id, data):
|
||||
page = StatusPage.query.get(page_id)
|
||||
if not page:
|
||||
raise ValueError('Status page not found')
|
||||
|
||||
comp = StatusComponent(
|
||||
page_id=page_id,
|
||||
name=data['name'],
|
||||
description=data.get('description', ''),
|
||||
group=data.get('group', 'Services'),
|
||||
sort_order=data.get('sort_order', 0),
|
||||
check_type=data.get('check_type', 'http'),
|
||||
check_target=data.get('check_target', ''),
|
||||
check_interval=data.get('check_interval', 60),
|
||||
check_timeout=data.get('check_timeout', 10),
|
||||
wordpress_site_id=data.get('wordpress_site_id'),
|
||||
)
|
||||
db.session.add(comp)
|
||||
db.session.commit()
|
||||
return comp
|
||||
|
||||
@staticmethod
|
||||
def update_component(comp_id, data):
|
||||
comp = StatusComponent.query.get(comp_id)
|
||||
if not comp:
|
||||
return None
|
||||
for field in ['name', 'description', 'group', 'sort_order', 'check_type',
|
||||
'check_target', 'check_interval', 'check_timeout', 'status']:
|
||||
if field in data:
|
||||
setattr(comp, field, data[field])
|
||||
db.session.commit()
|
||||
return comp
|
||||
|
||||
@staticmethod
|
||||
def delete_component(comp_id):
|
||||
comp = StatusComponent.query.get(comp_id)
|
||||
if not comp:
|
||||
return False
|
||||
# Resolve + unlink any incidents referencing this component first, so we
|
||||
# never dangle the component_id FK (enforced on PostgreSQL) or leave a
|
||||
# stale active incident on the public page after the component is gone.
|
||||
for inc in StatusIncident.query.filter_by(component_id=comp_id).all():
|
||||
if inc.status != 'resolved':
|
||||
inc.status = 'resolved'
|
||||
inc.resolved_at = datetime.utcnow()
|
||||
inc.component_id = None
|
||||
db.session.delete(comp)
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
# --- Health Checks ---
|
||||
|
||||
@staticmethod
|
||||
def run_check(component_id):
|
||||
"""Run a health check for a component."""
|
||||
comp = StatusComponent.query.get(component_id)
|
||||
if not comp:
|
||||
return None
|
||||
|
||||
check_result = StatusPageService._perform_check(comp)
|
||||
|
||||
hc = HealthCheck(
|
||||
component_id=component_id,
|
||||
status=check_result['status'],
|
||||
response_time=check_result.get('response_time'),
|
||||
status_code=check_result.get('status_code'),
|
||||
error=check_result.get('error'),
|
||||
)
|
||||
db.session.add(hc)
|
||||
|
||||
# Update component
|
||||
comp.last_check_at = datetime.utcnow()
|
||||
comp.last_response_time = check_result.get('response_time')
|
||||
if check_result['status'] == 'up':
|
||||
comp.status = StatusComponent.STATUS_OPERATIONAL
|
||||
elif check_result['status'] == 'degraded':
|
||||
comp.status = StatusComponent.STATUS_DEGRADED
|
||||
else:
|
||||
comp.status = StatusComponent.STATUS_MAJOR
|
||||
|
||||
db.session.commit()
|
||||
return hc
|
||||
|
||||
@staticmethod
|
||||
def _perform_check(comp):
|
||||
"""Execute the actual health check."""
|
||||
start = time.time()
|
||||
result = {'status': 'down', 'response_time': None, 'error': None}
|
||||
|
||||
try:
|
||||
if comp.check_type == 'http':
|
||||
import requests
|
||||
resp = requests.get(comp.check_target, timeout=comp.check_timeout, verify=True)
|
||||
result['response_time'] = int((time.time() - start) * 1000)
|
||||
result['status_code'] = resp.status_code
|
||||
if resp.status_code < 400:
|
||||
result['status'] = 'up'
|
||||
elif resp.status_code < 500:
|
||||
result['status'] = 'degraded'
|
||||
else:
|
||||
result['status'] = 'down'
|
||||
|
||||
elif comp.check_type == 'tcp':
|
||||
host, port = comp.check_target.rsplit(':', 1)
|
||||
sock = socket.create_connection((host, int(port)), timeout=comp.check_timeout)
|
||||
result['response_time'] = int((time.time() - start) * 1000)
|
||||
result['status'] = 'up'
|
||||
sock.close()
|
||||
|
||||
elif comp.check_type == 'ping':
|
||||
from app.utils.system import run_command
|
||||
res = run_command(['ping', '-c', '1', '-W', str(comp.check_timeout), comp.check_target])
|
||||
result['response_time'] = int((time.time() - start) * 1000)
|
||||
result['status'] = 'up'
|
||||
|
||||
elif comp.check_type == 'dns':
|
||||
socket.getaddrinfo(comp.check_target, None)
|
||||
result['response_time'] = int((time.time() - start) * 1000)
|
||||
result['status'] = 'up'
|
||||
|
||||
except Exception as e:
|
||||
result['response_time'] = int((time.time() - start) * 1000)
|
||||
result['error'] = str(e)
|
||||
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def get_check_history(component_id, hours=24):
|
||||
since = datetime.utcnow() - timedelta(hours=hours)
|
||||
return HealthCheck.query.filter(
|
||||
HealthCheck.component_id == component_id,
|
||||
HealthCheck.checked_at >= since
|
||||
).order_by(HealthCheck.checked_at.desc()).all()
|
||||
|
||||
@staticmethod
|
||||
def recompute_uptime(comp):
|
||||
"""Recompute uptime_24h/7d/30d/90d for a component from its HealthCheck
|
||||
rows (fraction of recorded checks with status 'up'). Only fully-healthy
|
||||
checks count as up — 'degraded' periods reduce the percentage, matching
|
||||
the status-page convention where degraded is not "operational". Leaves a
|
||||
window's existing value untouched when it has no samples yet."""
|
||||
windows = {'uptime_24h': 24, 'uptime_7d': 24 * 7,
|
||||
'uptime_30d': 24 * 30, 'uptime_90d': 24 * 90}
|
||||
now = datetime.utcnow()
|
||||
for field, hours in windows.items():
|
||||
since = now - timedelta(hours=hours)
|
||||
base = HealthCheck.query.filter(
|
||||
HealthCheck.component_id == comp.id,
|
||||
HealthCheck.checked_at >= since,
|
||||
)
|
||||
total = base.count()
|
||||
if total:
|
||||
up = base.filter(HealthCheck.status == 'up').count()
|
||||
setattr(comp, field, round(up / total * 100, 2))
|
||||
db.session.commit()
|
||||
|
||||
# Map an EnvironmentHealthService overall_status to (HealthCheck status,
|
||||
# StatusComponent status). 'unknown' is intentionally absent — indeterminate
|
||||
# checks are not recorded so they don't pollute the uptime %.
|
||||
_HEALTH_MAP = {
|
||||
'healthy': ('up', StatusComponent.STATUS_OPERATIONAL),
|
||||
'degraded': ('degraded', StatusComponent.STATUS_DEGRADED),
|
||||
'unhealthy': ('down', StatusComponent.STATUS_MAJOR),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def sync_component_from_health(comp, overall_status, error=None):
|
||||
"""Drive a managed-site-bound component from an EnvironmentHealthService
|
||||
verdict instead of a network probe (#26): record a HealthCheck sample,
|
||||
update the component's live status, recompute uptime, and auto-open /
|
||||
auto-resolve an incident on the operational<->major_outage edge.
|
||||
|
||||
Returns the recorded HealthCheck, or None for an indeterminate
|
||||
('unknown') verdict (not recorded).
|
||||
"""
|
||||
mapped = StatusPageService._HEALTH_MAP.get(overall_status)
|
||||
if not mapped:
|
||||
return None
|
||||
check_status, comp_status = mapped
|
||||
prev_status = comp.status
|
||||
|
||||
hc = HealthCheck(component_id=comp.id, status=check_status, error=error)
|
||||
db.session.add(hc)
|
||||
comp.last_check_at = datetime.utcnow()
|
||||
comp.status = comp_status
|
||||
db.session.commit()
|
||||
|
||||
StatusPageService.recompute_uptime(comp)
|
||||
|
||||
# Open an incident when ENTERING a major outage; resolve it when LEAVING
|
||||
# major (to operational OR degraded). Resolving on the leaving-edge — not
|
||||
# only on a clean major->operational hop — ensures a recovery that passes
|
||||
# through an intermediate degraded poll (a common path) never leaves the
|
||||
# incident stuck open. Degraded itself never opens a full incident.
|
||||
if comp_status == StatusComponent.STATUS_MAJOR and prev_status != StatusComponent.STATUS_MAJOR:
|
||||
StatusPageService._open_incident_for_component(comp, error)
|
||||
elif comp_status != StatusComponent.STATUS_MAJOR and prev_status == StatusComponent.STATUS_MAJOR:
|
||||
StatusPageService._resolve_incident_for_component(comp)
|
||||
return hc
|
||||
|
||||
@staticmethod
|
||||
def _open_incident_for_component(comp, error=None):
|
||||
"""Open a major-impact incident for a component if one is not already open."""
|
||||
existing = StatusIncident.query.filter(
|
||||
StatusIncident.component_id == comp.id,
|
||||
StatusIncident.status != 'resolved',
|
||||
).first()
|
||||
if existing:
|
||||
return existing
|
||||
incident = StatusPageService.create_incident(comp.page_id, {
|
||||
'title': f'{comp.name} is experiencing an outage',
|
||||
'status': 'investigating',
|
||||
'impact': 'major',
|
||||
'body': error or 'Automated health check detected an outage.',
|
||||
})
|
||||
incident.component_id = comp.id
|
||||
db.session.commit()
|
||||
return incident
|
||||
|
||||
@staticmethod
|
||||
def _resolve_incident_for_component(comp):
|
||||
"""Resolve the open auto-incident for a component, if any."""
|
||||
existing = StatusIncident.query.filter(
|
||||
StatusIncident.component_id == comp.id,
|
||||
StatusIncident.status != 'resolved',
|
||||
).first()
|
||||
if existing:
|
||||
StatusPageService.update_incident(existing.id, {
|
||||
'status': 'resolved',
|
||||
'update_body': 'Automated health check detected recovery.',
|
||||
})
|
||||
|
||||
# --- Incidents ---
|
||||
|
||||
@staticmethod
|
||||
def create_incident(page_id, data):
|
||||
incident = StatusIncident(
|
||||
page_id=page_id,
|
||||
title=data['title'],
|
||||
status=data.get('status', 'investigating'),
|
||||
impact=data.get('impact', 'minor'),
|
||||
body=data.get('body', ''),
|
||||
is_maintenance=data.get('is_maintenance', False),
|
||||
scheduled_start=data.get('scheduled_start'),
|
||||
scheduled_end=data.get('scheduled_end'),
|
||||
)
|
||||
db.session.add(incident)
|
||||
db.session.commit()
|
||||
return incident
|
||||
|
||||
@staticmethod
|
||||
def update_incident(incident_id, data):
|
||||
incident = StatusIncident.query.get(incident_id)
|
||||
if not incident:
|
||||
return None
|
||||
for field in ['title', 'status', 'impact', 'body']:
|
||||
if field in data:
|
||||
setattr(incident, field, data[field])
|
||||
if data.get('status') == 'resolved':
|
||||
incident.resolved_at = datetime.utcnow()
|
||||
|
||||
# Add timeline update
|
||||
if data.get('update_body'):
|
||||
update = StatusIncidentUpdate(
|
||||
incident_id=incident_id,
|
||||
status=data.get('status', incident.status),
|
||||
body=data['update_body'],
|
||||
)
|
||||
db.session.add(update)
|
||||
|
||||
db.session.commit()
|
||||
return incident
|
||||
|
||||
@staticmethod
|
||||
def delete_incident(incident_id):
|
||||
incident = StatusIncident.query.get(incident_id)
|
||||
if not incident:
|
||||
return False
|
||||
db.session.delete(incident)
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def get_badge(slug):
|
||||
"""Generate status badge data."""
|
||||
page = StatusPage.query.filter_by(slug=slug).first()
|
||||
if not page:
|
||||
return None
|
||||
|
||||
components = page.components.all()
|
||||
statuses = [c.status for c in components]
|
||||
|
||||
if not statuses or all(s == 'operational' for s in statuses):
|
||||
return {'label': 'status', 'message': 'operational', 'color': 'brightgreen'}
|
||||
elif any(s == 'major_outage' for s in statuses):
|
||||
return {'label': 'status', 'message': 'major outage', 'color': 'red'}
|
||||
elif any(s in ('partial_outage', 'degraded') for s in statuses):
|
||||
return {'label': 'status', 'message': 'degraded', 'color': 'yellow'}
|
||||
else:
|
||||
return {'label': 'status', 'message': 'maintenance', 'color': 'blue'}
|
||||
@@ -1,394 +0,0 @@
|
||||
"""WireGuard tunnel broker (roadmap Phase 1 — #8 / #10 / #11).
|
||||
|
||||
Pairs two agents over the existing agent command channel:
|
||||
keygen → interface:up → peer:set → verify. The panel is the source of
|
||||
truth; private keys never leave the hosts (only public keys are brokered
|
||||
and persisted). See docs/REMOTE_ACCESS_ROADMAP.md.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models.server import Server
|
||||
from app.models.tunnel import Tunnel
|
||||
from app.services.agent_registry import agent_registry
|
||||
from app.services import tunnel_netutil
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
KEEPALIVE_SECONDS = 25
|
||||
|
||||
|
||||
class TunnelBrokerError(Exception):
|
||||
"""A broker step failed. ``code`` mirrors the agent send_command codes
|
||||
(AGENT_OFFLINE, PERMISSION_DENIED, TIMEOUT) plus broker-specific ones
|
||||
(NOT_CONNECTED, NO_WIREGUARD, NO_EDGE_IP, POOL_EXHAUSTED, NOT_FOUND,
|
||||
BAD_REQUEST). ``status`` is the HTTP status the API should return."""
|
||||
|
||||
def __init__(self, message, code='BROKER_ERROR', status=400):
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.code = code
|
||||
self.status = status
|
||||
|
||||
|
||||
class TunnelBrokerService:
|
||||
|
||||
# ---- agent command helper ------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _cmd(server_id, action, params=None, user_id=None, timeout=20.0):
|
||||
"""Send an agent command; raise TunnelBrokerError on failure.
|
||||
Returns the agent handler's ``data`` payload on success."""
|
||||
res = agent_registry.send_command(
|
||||
server_id=server_id, action=action, params=params or {},
|
||||
user_id=user_id, timeout=timeout,
|
||||
)
|
||||
if not res.get('success'):
|
||||
code = res.get('code', 'BROKER_ERROR')
|
||||
status = 409 if code == 'AGENT_OFFLINE' else (502 if code == 'TIMEOUT' else 400)
|
||||
raise TunnelBrokerError(
|
||||
"%s on %s failed: %s" % (action, server_id, res.get('error', 'unknown error')),
|
||||
code=code, status=status,
|
||||
)
|
||||
return res.get('data')
|
||||
|
||||
# ---- preflight -----------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _require_wireguard_agent(server_id, role):
|
||||
server = Server.query.get(server_id)
|
||||
if not server:
|
||||
raise TunnelBrokerError("%s server not found" % role, code='NOT_FOUND', status=404)
|
||||
agent = agent_registry.get_agent(server_id)
|
||||
if not agent:
|
||||
raise TunnelBrokerError(
|
||||
"%s server '%s' is not connected" % (role, server.name),
|
||||
code='NOT_CONNECTED', status=409,
|
||||
)
|
||||
if not (agent.capabilities or {}).get('wireguard'):
|
||||
raise TunnelBrokerError(
|
||||
"%s server '%s' lacks the wireguard capability "
|
||||
"(needs wireguard-tools + iproute2 on a Linux agent)" % (role, server.name),
|
||||
code='NO_WIREGUARD', status=409,
|
||||
)
|
||||
return server
|
||||
|
||||
# ---- create --------------------------------------------------------
|
||||
|
||||
@classmethod
|
||||
def create_tunnel(cls, edge_server_id, private_server_id, name=None, user_id=None):
|
||||
if not edge_server_id or not private_server_id:
|
||||
raise TunnelBrokerError("edge_server_id and private_server_id are required", code='BAD_REQUEST')
|
||||
if edge_server_id == private_server_id:
|
||||
raise TunnelBrokerError("edge and private servers must differ", code='BAD_REQUEST')
|
||||
|
||||
edge = cls._require_wireguard_agent(edge_server_id, 'edge')
|
||||
private = cls._require_wireguard_agent(private_server_id, 'private')
|
||||
|
||||
# The private peer dials the edge's public endpoint, so the edge
|
||||
# needs a reachable address.
|
||||
if not tunnel_netutil.validate_endpoint_host(edge.ip_address):
|
||||
raise TunnelBrokerError(
|
||||
"edge server '%s' has no usable public IP (ip_address=%r)" % (edge.name, edge.ip_address),
|
||||
code='NO_EDGE_IP', status=409,
|
||||
)
|
||||
|
||||
used = [t.subnet for t in Tunnel.query.with_entities(Tunnel.subnet).all()]
|
||||
try:
|
||||
subnet, edge_ip, private_ip = tunnel_netutil.pick_subnet(used)
|
||||
except RuntimeError as e:
|
||||
raise TunnelBrokerError(str(e), code='POOL_EXHAUSTED', status=409)
|
||||
|
||||
# Allocate a listen port unique to this edge (#20) so one edge can
|
||||
# front multiple private peers without UDP-port conflicts.
|
||||
used_ports = [t.listen_port for t in Tunnel.query
|
||||
.with_entities(Tunnel.listen_port)
|
||||
.filter(Tunnel.edge_server_id == edge_server_id).all()]
|
||||
try:
|
||||
listen_port = tunnel_netutil.pick_listen_port(used_ports)
|
||||
except RuntimeError as e:
|
||||
raise TunnelBrokerError(str(e), code='PORT_POOL_EXHAUSTED', status=409)
|
||||
|
||||
tunnel = Tunnel(
|
||||
name=name or ("%s → %s" % (edge.name, private.name)),
|
||||
edge_server_id=edge_server_id,
|
||||
private_server_id=private_server_id,
|
||||
subnet=subnet,
|
||||
edge_wg_ip=edge_ip,
|
||||
private_wg_ip=private_ip,
|
||||
listen_port=listen_port,
|
||||
status='pending',
|
||||
)
|
||||
db.session.add(tunnel)
|
||||
db.session.flush() # assign tunnel.id before deriving the interface name
|
||||
tunnel.interface_name = tunnel_netutil.interface_name_for(tunnel.id)
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
cls._bring_up(tunnel, edge, private, user_id)
|
||||
except TunnelBrokerError as e:
|
||||
tunnel.status = 'error'
|
||||
tunnel.last_error = e.message
|
||||
db.session.commit()
|
||||
raise
|
||||
|
||||
return tunnel
|
||||
|
||||
@classmethod
|
||||
def _bring_up(cls, tunnel, edge, private, user_id):
|
||||
iface = tunnel.interface_name
|
||||
|
||||
# 1. keygen on both ends — public keys only come back.
|
||||
edge_kg = cls._cmd(edge.id, 'wireguard:keygen', {'interface': iface}, user_id)
|
||||
priv_kg = cls._cmd(private.id, 'wireguard:keygen', {'interface': iface}, user_id)
|
||||
edge_pub = (edge_kg or {}).get('public_key')
|
||||
priv_pub = (priv_kg or {}).get('public_key')
|
||||
if not edge_pub or not priv_pub:
|
||||
raise TunnelBrokerError("agent keygen returned no public key", code='BROKER_ERROR', status=502)
|
||||
tunnel.edge_pubkey = edge_pub
|
||||
tunnel.private_pubkey = priv_pub
|
||||
db.session.commit()
|
||||
|
||||
# 2. interfaces up — the edge listens; the private side dials out.
|
||||
cls._cmd(edge.id, 'wireguard:interface:up',
|
||||
{'name': iface, 'address': tunnel.edge_address(), 'listen_port': tunnel.listen_port}, user_id)
|
||||
cls._cmd(private.id, 'wireguard:interface:up',
|
||||
{'name': iface, 'address': tunnel.private_address(), 'listen_port': 0}, user_id)
|
||||
|
||||
# 3. peers — the private peer carries the edge endpoint + keepalive
|
||||
# so it punches and holds the NAT mapping.
|
||||
cls._cmd(edge.id, 'wireguard:peer:set', {
|
||||
'interface': iface,
|
||||
'public_key': priv_pub,
|
||||
'allowed_ips': ["%s/32" % tunnel.private_wg_ip],
|
||||
}, user_id)
|
||||
cls._cmd(private.id, 'wireguard:peer:set', {
|
||||
'interface': iface,
|
||||
'public_key': edge_pub,
|
||||
'allowed_ips': ["%s/32" % tunnel.edge_wg_ip],
|
||||
'endpoint': "%s:%d" % (edge.ip_address, tunnel.listen_port),
|
||||
'persistent_keepalive': KEEPALIVE_SECONDS,
|
||||
}, user_id)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
# 4. open the edge's inbound WireGuard UDP port (best-effort, #10).
|
||||
tunnel.firewall_status = cls._ensure_edge_port(edge.id, tunnel.listen_port, user_id)
|
||||
|
||||
# 5. best-effort immediate verify (handshake may take a few seconds;
|
||||
# #11 health-refresh confirms it later regardless).
|
||||
try:
|
||||
cls.refresh_status(tunnel, user_id=user_id)
|
||||
except TunnelBrokerError:
|
||||
logger.info("post-create status refresh failed for tunnel %s (will settle on next refresh)", tunnel.id)
|
||||
|
||||
# ---- status / health (#11) -----------------------------------------
|
||||
|
||||
@classmethod
|
||||
def refresh_status(cls, tunnel, user_id=None):
|
||||
"""Poll wireguard:status on both ends and update the row's health.
|
||||
Returns {tunnel, edge, private}."""
|
||||
now = time.time()
|
||||
edge_status = cls._safe_status(tunnel.edge_server_id, tunnel.interface_name, user_id)
|
||||
private_status = cls._safe_status(tunnel.private_server_id, tunnel.interface_name, user_id)
|
||||
|
||||
latest = max(cls._latest_handshake(edge_status), cls._latest_handshake(private_status))
|
||||
iface_up = bool((edge_status or {}).get('up')) and bool((private_status or {}).get('up'))
|
||||
tunnel.status = tunnel_netutil.derive_status(latest, now, interface_up=iface_up)
|
||||
if latest:
|
||||
tunnel.last_handshake_at = datetime.utcfromtimestamp(latest)
|
||||
db.session.commit()
|
||||
# Reachability diagnostic (#21): flag a likely blocked-UDP case.
|
||||
age = None
|
||||
if tunnel.created_at:
|
||||
try:
|
||||
age = now - tunnel.created_at.timestamp()
|
||||
except Exception:
|
||||
age = None
|
||||
diagnostic = tunnel_netutil.diagnose_reachability(latest, age, iface_up)
|
||||
return {'tunnel': tunnel.to_dict(), 'edge': edge_status,
|
||||
'private': private_status, 'diagnostic': diagnostic}
|
||||
|
||||
@classmethod
|
||||
def _safe_status(cls, server_id, iface, user_id):
|
||||
"""wireguard:status that returns None instead of raising — a
|
||||
disconnected end shouldn't blow up the whole status read."""
|
||||
try:
|
||||
return cls._cmd(server_id, 'wireguard:status', {'interface': iface}, user_id, timeout=10.0)
|
||||
except TunnelBrokerError:
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _latest_handshake(status):
|
||||
if not status:
|
||||
return 0
|
||||
best = 0
|
||||
for p in (status.get('peers') or []):
|
||||
hs = p.get('latest_handshake') or 0
|
||||
if hs > best:
|
||||
best = hs
|
||||
return best
|
||||
|
||||
# ---- teardown ------------------------------------------------------
|
||||
|
||||
@classmethod
|
||||
def teardown_tunnel(cls, tunnel_id, user_id=None):
|
||||
tunnel = Tunnel.query.get(tunnel_id)
|
||||
if not tunnel:
|
||||
raise TunnelBrokerError("tunnel not found", code='NOT_FOUND', status=404)
|
||||
# Best-effort interface teardown on both ends — don't block delete on
|
||||
# a disconnected agent (the row is the source of truth; #19 reconciles).
|
||||
for sid in (tunnel.edge_server_id, tunnel.private_server_id):
|
||||
try:
|
||||
agent_registry.send_command(
|
||||
server_id=sid, action='wireguard:interface:down',
|
||||
params={'interface': tunnel.interface_name}, user_id=user_id, timeout=10.0,
|
||||
)
|
||||
except Exception:
|
||||
logger.info("interface:down on %s during teardown failed (continuing)", sid)
|
||||
db.session.delete(tunnel)
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
# ---- reads ---------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def get_tunnel(tunnel_id):
|
||||
tunnel = Tunnel.query.get(tunnel_id)
|
||||
if not tunnel:
|
||||
raise TunnelBrokerError("tunnel not found", code='NOT_FOUND', status=404)
|
||||
return tunnel
|
||||
|
||||
# ---- reconcile (#19: panel-authoritative persistence) --------------
|
||||
|
||||
@staticmethod
|
||||
def schedule_reconcile(server_id):
|
||||
"""Spawn a non-blocking background reconcile for a (re)connected
|
||||
server (#19). Safe to call from a Socket.IO handler — captures the
|
||||
Flask app and runs reconcile_server in its own context, so tunnels
|
||||
self-heal after an agent or panel restart."""
|
||||
try:
|
||||
from app import socketio
|
||||
from flask import current_app
|
||||
app = current_app._get_current_object()
|
||||
except Exception:
|
||||
logger.exception("reconcile: could not capture app/socketio")
|
||||
return
|
||||
|
||||
def _run():
|
||||
with app.app_context():
|
||||
try:
|
||||
TunnelBrokerService.reconcile_server(server_id)
|
||||
except Exception:
|
||||
logger.exception("tunnel reconcile failed for %s", server_id)
|
||||
|
||||
try:
|
||||
socketio.start_background_task(_run)
|
||||
except Exception:
|
||||
logger.exception("could not start reconcile task for %s", server_id)
|
||||
|
||||
@classmethod
|
||||
def reconcile_server(cls, server_id, user_id=None):
|
||||
"""Re-apply the config for every tunnel this server participates in.
|
||||
The panel is the source of truth; relies on the Phase-0 commands
|
||||
being idempotent. Best-effort per tunnel (a down peer doesn't block
|
||||
the others). Returns a per-tunnel result list."""
|
||||
from app.models.exposed_service import ExposedService
|
||||
tunnels = Tunnel.query.filter(
|
||||
((Tunnel.edge_server_id == server_id) | (Tunnel.private_server_id == server_id)),
|
||||
Tunnel.status.in_(('up', 'degraded', 'pending')),
|
||||
).all()
|
||||
out = []
|
||||
for t in tunnels:
|
||||
try:
|
||||
cls._reconcile_side(t, server_id, ExposedService, user_id)
|
||||
out.append({'tunnel_id': t.id, 'ok': True})
|
||||
except TunnelBrokerError as e:
|
||||
logger.info("reconcile of tunnel %s on %s failed: %s", t.id, server_id, e.message)
|
||||
out.append({'tunnel_id': t.id, 'ok': False, 'error': e.message})
|
||||
if out:
|
||||
logger.info("reconciled %d tunnel(s) for server %s", len(out), server_id)
|
||||
return out
|
||||
|
||||
@classmethod
|
||||
def _reconcile_side(cls, tunnel, server_id, exposed_service_model, user_id):
|
||||
"""Re-apply just the side of `tunnel` that belongs to server_id (the
|
||||
other end reconciles when it reconnects). Rebuilds from the stored
|
||||
public keys + endpoint — no private key ever needed here."""
|
||||
iface = tunnel.interface_name
|
||||
if tunnel.edge_server_id == server_id:
|
||||
cls._cmd(server_id, 'wireguard:interface:up',
|
||||
{'name': iface, 'address': tunnel.edge_address(),
|
||||
'listen_port': tunnel.listen_port}, user_id)
|
||||
if tunnel.private_pubkey:
|
||||
cls._cmd(server_id, 'wireguard:peer:set',
|
||||
{'interface': iface, 'public_key': tunnel.private_pubkey,
|
||||
'allowed_ips': ['%s/32' % tunnel.private_wg_ip]}, user_id)
|
||||
try:
|
||||
cls._ensure_edge_port(server_id, tunnel.listen_port, user_id)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
cls._cmd(server_id, 'wireguard:interface:up',
|
||||
{'name': iface, 'address': tunnel.private_address(),
|
||||
'listen_port': 0}, user_id)
|
||||
edge = Server.query.get(tunnel.edge_server_id)
|
||||
if tunnel.edge_pubkey and edge and edge.ip_address:
|
||||
cls._cmd(server_id, 'wireguard:peer:set',
|
||||
{'interface': iface, 'public_key': tunnel.edge_pubkey,
|
||||
'allowed_ips': ['%s/32' % tunnel.edge_wg_ip],
|
||||
'endpoint': '%s:%d' % (edge.ip_address, tunnel.listen_port),
|
||||
'persistent_keepalive': KEEPALIVE_SECONDS}, user_id)
|
||||
# Re-apply the service forwarders for this tunnel.
|
||||
for svc in exposed_service_model.query.filter_by(tunnel_id=tunnel.id).all():
|
||||
try:
|
||||
cls._cmd(server_id, 'wireguard:forward',
|
||||
{'interface': iface, 'listen_ip': tunnel.private_wg_ip,
|
||||
'listen_port': svc.port, 'target_host': '127.0.0.1',
|
||||
'target_port': svc.port}, user_id)
|
||||
except TunnelBrokerError:
|
||||
pass
|
||||
|
||||
# ---- firewall (#10) ------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _ensure_edge_port(edge_server_id, port, user_id=None):
|
||||
"""Open the edge's inbound UDP <port> via the agent's
|
||||
firewall:allow_port command (#10). Best-effort — a failure (no
|
||||
firewall present, missing `firewall:*` grant, or an older agent
|
||||
without the command) is non-fatal: the tunnel still works if the
|
||||
port is already open, and the create response always carries the
|
||||
manual commands too. Returns a small outcome dict for the UI."""
|
||||
try:
|
||||
res = agent_registry.send_command(
|
||||
server_id=edge_server_id, action='firewall:allow_port',
|
||||
params={'port': port, 'protocol': 'udp'}, user_id=user_id, timeout=15.0,
|
||||
)
|
||||
except Exception as e: # pragma: no cover - defensive
|
||||
logger.info("edge firewall open failed for %s: %s", edge_server_id, e)
|
||||
return {'opened': False, 'error': str(e)}
|
||||
if res.get('success'):
|
||||
data = res.get('data') or {}
|
||||
return {'opened': True, 'method': data.get('method')}
|
||||
logger.info("edge firewall open not applied for %s: %s", edge_server_id, res.get('error'))
|
||||
return {'opened': False, 'error': res.get('error'), 'code': res.get('code')}
|
||||
|
||||
@staticmethod
|
||||
def firewall_hint(port):
|
||||
"""The edge must accept inbound UDP for the WireGuard handshake.
|
||||
There's no dedicated firewall agent command yet (a small follow-up,
|
||||
like the wireguard:* primitives), so for now we surface the exact
|
||||
step/commands rather than guessing at system:exec."""
|
||||
return {
|
||||
'port': port,
|
||||
'protocol': 'udp',
|
||||
'target': 'edge',
|
||||
'note': "Open inbound UDP %d on the edge server for the WireGuard handshake." % port,
|
||||
'commands': [
|
||||
"ufw allow %d/udp" % port,
|
||||
"firewall-cmd --add-port=%d/udp --permanent && firewall-cmd --reload" % port,
|
||||
],
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
"""Pure, dependency-free helpers for the WireGuard tunnel broker.
|
||||
|
||||
Kept import-light (stdlib only) so the subnet allocator, interface-name
|
||||
derivation and health classification are unit-testable without booting
|
||||
Flask/SQLAlchemy. See docs/REMOTE_ACCESS_ROADMAP.md (Phase 1, #7 / #11).
|
||||
"""
|
||||
|
||||
import ipaddress
|
||||
|
||||
# The tunnel overlay pool: 10.88.0.0/16 carved into /24s. Deliberately an
|
||||
# uncommon RFC-1918 block so it won't collide with a typical home LAN
|
||||
# (192.168.x / 10.0.x). Each tunnel gets one /24 — .1 = edge, .2 = private.
|
||||
TUNNEL_POOL = "10.88.0.0/16"
|
||||
|
||||
# A peer counts as "live" if it handshook within this window. WireGuard
|
||||
# rehandshakes well inside it when persistent-keepalive is 25s.
|
||||
HANDSHAKE_FRESH_SECONDS = 180
|
||||
|
||||
# WireGuard listen ports are allocated per edge (#20) so ONE edge can front
|
||||
# many private peers — each tunnel needs its own UDP port. 51820..52019.
|
||||
DEFAULT_LISTEN_PORT = 51820
|
||||
LISTEN_PORT_RANGE = 200
|
||||
|
||||
# A tunnel with both interfaces up but no handshake after this long likely
|
||||
# has its outbound UDP blocked (#21).
|
||||
HANDSHAKE_GRACE_SECONDS = 45
|
||||
|
||||
|
||||
def pick_subnet(used_subnets):
|
||||
"""Return (subnet_cidr, edge_ip, private_ip) for the first free /24 in
|
||||
the pool. ``used_subnets`` is any iterable of CIDR strings already taken.
|
||||
|
||||
Raises RuntimeError if the pool is exhausted (256 /24s).
|
||||
"""
|
||||
used = set(used_subnets or [])
|
||||
for third in range(256):
|
||||
cidr = "10.88.%d.0/24" % third
|
||||
if cidr not in used:
|
||||
return cidr, "10.88.%d.1" % third, "10.88.%d.2" % third
|
||||
raise RuntimeError("tunnel subnet pool exhausted (10.88.0.0/16, 256 /24s)")
|
||||
|
||||
|
||||
def interface_name_for(tunnel_id):
|
||||
"""Derive a stable, kernel-valid WireGuard interface name from a tunnel
|
||||
id. Linux caps interface names at 15 chars; 'skwg' + 8 hex is 12. The
|
||||
same name is used on both ends (they're different hosts).
|
||||
"""
|
||||
compact = str(tunnel_id).replace("-", "")[:8] or "0"
|
||||
return "skwg%s" % compact
|
||||
|
||||
|
||||
def derive_status(latest_handshake_epoch, now_epoch, interface_up=True):
|
||||
"""Classify tunnel health from a peer's latest-handshake timestamp.
|
||||
|
||||
- 'down' — the interface isn't up
|
||||
- 'up' — handshook within HANDSHAKE_FRESH_SECONDS
|
||||
- 'degraded' — handshook before, but now stale (link may be recovering)
|
||||
- 'pending' — interface up but no handshake yet (just created)
|
||||
"""
|
||||
if not interface_up:
|
||||
return "down"
|
||||
if latest_handshake_epoch and latest_handshake_epoch > 0:
|
||||
age = now_epoch - latest_handshake_epoch
|
||||
return "up" if age <= HANDSHAKE_FRESH_SECONDS else "degraded"
|
||||
return "pending"
|
||||
|
||||
|
||||
def validate_endpoint_host(ip_address):
|
||||
"""True if ``ip_address`` is usable as the edge's public endpoint host.
|
||||
|
||||
Accepts IPv4/IPv6; rejects empty, malformed, loopback and unspecified
|
||||
addresses. Private ranges are allowed (a lab/LAN edge is valid).
|
||||
"""
|
||||
if not ip_address:
|
||||
return False
|
||||
try:
|
||||
ip = ipaddress.ip_address(str(ip_address).strip())
|
||||
except ValueError:
|
||||
return False
|
||||
return not (ip.is_loopback or ip.is_unspecified)
|
||||
|
||||
|
||||
def pick_listen_port(used_ports):
|
||||
"""First free WireGuard listen port for an edge, starting at
|
||||
DEFAULT_LISTEN_PORT. ``used_ports`` is the ports already taken by other
|
||||
tunnels on the SAME edge — so one edge can front many private peers (#20).
|
||||
Raises RuntimeError if the per-edge pool is exhausted.
|
||||
"""
|
||||
used = set(used_ports or [])
|
||||
for port in range(DEFAULT_LISTEN_PORT, DEFAULT_LISTEN_PORT + LISTEN_PORT_RANGE):
|
||||
if port not in used:
|
||||
return port
|
||||
raise RuntimeError(
|
||||
"listen-port pool exhausted on this edge (%d..%d)"
|
||||
% (DEFAULT_LISTEN_PORT, DEFAULT_LISTEN_PORT + LISTEN_PORT_RANGE - 1)
|
||||
)
|
||||
|
||||
|
||||
def diagnose_reachability(latest_handshake_epoch, age_seconds, both_interfaces_up):
|
||||
"""Near-term #21: classify why a tunnel isn't passing traffic, with an
|
||||
actionable hint. The actual relay data plane is deferred.
|
||||
|
||||
- 'interface_down' — an agent hasn't brought its interface up
|
||||
- 'ok' — a handshake has happened
|
||||
- 'connecting' — interfaces up, still within the handshake grace window
|
||||
- 'no_handshake' — up + past grace + no handshake → outbound UDP likely blocked
|
||||
"""
|
||||
if not both_interfaces_up:
|
||||
return {'state': 'interface_down',
|
||||
'hint': 'One or both agents have not brought the WireGuard interface up.'}
|
||||
if latest_handshake_epoch and latest_handshake_epoch > 0:
|
||||
return {'state': 'ok'}
|
||||
if age_seconds is not None and age_seconds < HANDSHAKE_GRACE_SECONDS:
|
||||
return {'state': 'connecting', 'hint': 'Waiting for the first WireGuard handshake.'}
|
||||
return {'state': 'no_handshake',
|
||||
'hint': ("No WireGuard handshake yet — the private host's outbound UDP to the "
|
||||
"edge may be blocked by its network. A relay (roadmap #21) would be "
|
||||
"needed to traverse it.")}
|
||||
@@ -1,175 +0,0 @@
|
||||
"""Publish a private service over a WireGuard tunnel (roadmap Phase 2).
|
||||
|
||||
Ties the pieces together: start a forwarder on the private peer (#13),
|
||||
write the edge nginx vhost that proxies to the peer's WG IP (#12), point
|
||||
DNS at the edge (#14), put basic-auth in front (#16), and obtain a cert
|
||||
(#15). The nginx / DNS / cert / auth steps run on the panel host, which
|
||||
acts as the edge (where the WG edge interface and nginx live). See
|
||||
docs/REMOTE_ACCESS_ROADMAP.md.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import re
|
||||
|
||||
from app import db
|
||||
from app.models.exposed_service import ExposedService
|
||||
from app.models.server import Server
|
||||
from app.models.tunnel import Tunnel
|
||||
from app.services.agent_registry import agent_registry
|
||||
from app.services.dns_provider_service import DNSProviderService
|
||||
from app.services.environment_domain_service import EnvironmentDomainService
|
||||
from app.services.nginx_service import NginxService
|
||||
from app.services.ssl_service import SSLService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_HOSTNAME_RE = re.compile(
|
||||
r'^(?=.{1,253}$)(?!-)[A-Za-z0-9-]{1,63}(?<!-)(\.[A-Za-z0-9-]{1,63})+$'
|
||||
)
|
||||
|
||||
|
||||
class TunnelPublishError(Exception):
|
||||
"""A publish step failed. ``status`` is the HTTP status the API returns."""
|
||||
|
||||
def __init__(self, message, code='PUBLISH_ERROR', status=400):
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.code = code
|
||||
self.status = status
|
||||
|
||||
|
||||
class TunnelPublishService:
|
||||
|
||||
@staticmethod
|
||||
def list_for_tunnel(tunnel_id):
|
||||
return (ExposedService.query
|
||||
.filter_by(tunnel_id=tunnel_id)
|
||||
.order_by(ExposedService.created_at.desc())
|
||||
.all())
|
||||
|
||||
@staticmethod
|
||||
def get(service_id):
|
||||
svc = ExposedService.query.get(service_id)
|
||||
if not svc:
|
||||
raise TunnelPublishError('exposed service not found', code='NOT_FOUND', status=404)
|
||||
return svc
|
||||
|
||||
@classmethod
|
||||
def publish(cls, tunnel_id, hostname, port, *, require_auth=False,
|
||||
auth_username=None, auth_password=None, ssl=True,
|
||||
email=None, user_id=None):
|
||||
"""Publish <hostname> → the private service on <port>. The forwarder
|
||||
and nginx steps are essential (failure aborts); DNS / auth / cert are
|
||||
best-effort and reported in the returned ``steps`` dict."""
|
||||
hostname = (hostname or '').strip().lower().rstrip('.')
|
||||
if not _HOSTNAME_RE.match(hostname):
|
||||
raise TunnelPublishError('invalid hostname', code='BAD_REQUEST')
|
||||
try:
|
||||
port = int(port)
|
||||
except (TypeError, ValueError):
|
||||
raise TunnelPublishError('port must be an integer', code='BAD_REQUEST')
|
||||
if port < 1 or port > 65535:
|
||||
raise TunnelPublishError('port out of range', code='BAD_REQUEST')
|
||||
if require_auth and (not auth_username or not auth_password):
|
||||
raise TunnelPublishError(
|
||||
'auth_username and auth_password are required when require_auth is set',
|
||||
code='BAD_REQUEST')
|
||||
|
||||
tunnel = Tunnel.query.get(tunnel_id)
|
||||
if not tunnel:
|
||||
raise TunnelPublishError('tunnel not found', code='NOT_FOUND', status=404)
|
||||
edge = Server.query.get(tunnel.edge_server_id)
|
||||
|
||||
svc = ExposedService(
|
||||
tunnel_id=tunnel.id, hostname=hostname, port=port,
|
||||
nginx_site_name=hostname, require_auth=require_auth,
|
||||
auth_username=auth_username if require_auth else None,
|
||||
status='pending',
|
||||
)
|
||||
db.session.add(svc)
|
||||
db.session.commit()
|
||||
|
||||
steps = {}
|
||||
try:
|
||||
# 1. Forwarder on the private peer (essential): WG IP:port → the
|
||||
# real local service on 127.0.0.1:port.
|
||||
fwd = agent_registry.send_command(
|
||||
server_id=tunnel.private_server_id, action='wireguard:forward',
|
||||
params={'interface': tunnel.interface_name, 'listen_ip': tunnel.private_wg_ip,
|
||||
'listen_port': port, 'target_host': '127.0.0.1', 'target_port': port},
|
||||
user_id=user_id, timeout=15.0,
|
||||
)
|
||||
if not fwd.get('success'):
|
||||
raise TunnelPublishError(
|
||||
'failed to start forwarder on private host: %s' % fwd.get('error'),
|
||||
code=fwd.get('code', 'FORWARD_FAILED'), status=502)
|
||||
steps['forward'] = {'ok': True}
|
||||
|
||||
# 2. Edge nginx vhost (essential): proxy to the peer's WG IP.
|
||||
upstream = '%s:%d' % (tunnel.private_wg_ip, port)
|
||||
created = NginxService.create_site(
|
||||
name=hostname, app_type='remote', domains=[hostname],
|
||||
root_path='', upstream=upstream)
|
||||
if not created.get('success'):
|
||||
raise TunnelPublishError(
|
||||
'failed to write nginx vhost: %s' % created.get('error'),
|
||||
code='NGINX_FAILED', status=500)
|
||||
enabled = NginxService.enable_site(hostname)
|
||||
if not enabled.get('success'):
|
||||
raise TunnelPublishError(
|
||||
'failed to enable nginx vhost: %s' % enabled.get('error'),
|
||||
code='NGINX_FAILED', status=500)
|
||||
steps['nginx'] = {'ok': True}
|
||||
|
||||
# 3. DNS A record → the edge's public IP (best-effort, #14).
|
||||
edge_ip = edge.ip_address if edge else None
|
||||
steps['dns'] = DNSProviderService.ensure_a_record(hostname, edge_ip)
|
||||
|
||||
# 4. Basic-auth in front (best-effort, #16).
|
||||
if require_auth:
|
||||
steps['auth'] = EnvironmentDomainService.enable_basic_auth(
|
||||
hostname, auth_username, auth_password)
|
||||
|
||||
# 5. Cert on the edge (best-effort, #15). certbot --nginx wires
|
||||
# the TLS into the vhost and reloads, so we only flag success.
|
||||
if ssl:
|
||||
cert = SSLService.obtain_certificate([hostname], email or ('admin@%s' % hostname))
|
||||
steps['ssl'] = {'ok': bool(cert.get('success')), 'error': cert.get('error')}
|
||||
if cert.get('success'):
|
||||
svc.ssl_enabled = True
|
||||
|
||||
svc.status = 'published'
|
||||
db.session.commit()
|
||||
return svc, steps
|
||||
except TunnelPublishError as e:
|
||||
svc.status = 'error'
|
||||
svc.last_error = e.message
|
||||
db.session.commit()
|
||||
raise
|
||||
|
||||
@classmethod
|
||||
def unpublish(cls, service_id, user_id=None):
|
||||
svc = ExposedService.query.get(service_id)
|
||||
if not svc:
|
||||
raise TunnelPublishError('exposed service not found', code='NOT_FOUND', status=404)
|
||||
tunnel = Tunnel.query.get(svc.tunnel_id)
|
||||
|
||||
# Remove the edge nginx vhost (best-effort).
|
||||
try:
|
||||
NginxService.delete_site(svc.nginx_site_name or svc.hostname)
|
||||
except Exception:
|
||||
logger.info('nginx delete_site failed during unpublish of %s', svc.hostname)
|
||||
|
||||
# Stop the forwarder on the private peer (best-effort).
|
||||
if tunnel:
|
||||
try:
|
||||
agent_registry.send_command(
|
||||
server_id=tunnel.private_server_id, action='wireguard:unforward',
|
||||
params={'interface': tunnel.interface_name, 'listen_port': svc.port},
|
||||
user_id=user_id, timeout=10.0)
|
||||
except Exception:
|
||||
logger.info('wireguard:unforward failed during unpublish of %s', svc.hostname)
|
||||
|
||||
db.session.delete(svc)
|
||||
db.session.commit()
|
||||
return True
|
||||
Reference in new issue
Block a user