From 43c87cd5eb9fbed0e06971d544406062602b1f2a Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sun, 22 Nov 2026 01:44:59 -0500 Subject: [PATCH 01/13] Scope fleet-wide server reads to the workspace GHSA-qcjj-hf95-6rgw: the workspace check landed on every route, but the routes that list, search or export across the fleet take no id in the path, so they kept answering from unfiltered Server and ServerMetrics queries. Any account, down to a viewer in no workspace, could enumerate other workspaces' servers and read their metric history. The fleet-monitor reads (heatmap, comparison, alerts, thresholds, anomalies, search, both exports) and the mobile summary and offline cache now take the caller and apply the rule GET /servers uses. A sweep over every parameterless GET route found three more of the same shape, fixed here too: the proxy overview, the metrics retention stats, and server-group membership. --- backend/app/api/fleet_monitor.py | 24 +- backend/app/api/mobile.py | 9 +- backend/app/api/proxy.py | 5 +- backend/app/api/servers.py | 23 +- backend/app/services/fleet_monitor_service.py | 83 +++++-- backend/app/services/proxy_stack_service.py | 10 +- .../app/services/server_metrics_service.py | 32 ++- backend/tests/test_fleet_metrics_batching.py | 6 +- backend/tests/test_fleet_proxy.py | 17 +- .../tests/test_fleet_read_workspace_access.py | 206 ++++++++++++++++++ backend/tests/test_ingress_plane.py | 5 +- 11 files changed, 360 insertions(+), 60 deletions(-) create mode 100644 backend/tests/test_fleet_read_workspace_access.py diff --git a/backend/app/api/fleet_monitor.py b/backend/app/api/fleet_monitor.py index 8802ba18..6e041b53 100644 --- a/backend/app/api/fleet_monitor.py +++ b/backend/app/api/fleet_monitor.py @@ -4,6 +4,10 @@ Fleet Monitor API Endpoints for fleet-wide monitoring: heatmaps, comparisons, alert thresholds, anomaly detection, capacity forecasting, fleet search, and metrics export. + +Every read passes the caller to the service, which answers only for servers +that caller can access — the workspace rule GET /servers applies. These routes +carry no server id in the path, so nothing else enforces it for them. """ from flask import Blueprint, request, jsonify, Response @@ -24,7 +28,7 @@ fleet_monitor_bp = Blueprint('fleet_monitor', __name__) def get_fleet_heatmap(): """Get latest metrics for all servers in heatmap format.""" group_id = request.args.get('group_id') - return jsonify(fleet_monitor_service.get_fleet_heatmap(group_id)) + return jsonify(fleet_monitor_service.get_fleet_heatmap(get_current_user(), group_id)) # ==================== Comparison ==================== @@ -41,7 +45,8 @@ def get_comparison(): if not server_ids: return jsonify({'error': 'ids parameter is required'}), 400 - return jsonify(fleet_monitor_service.get_comparison_timeseries(server_ids, metric, period)) + return jsonify(fleet_monitor_service.get_comparison_timeseries( + get_current_user(), server_ids, metric, period)) # ==================== Alerts ==================== @@ -55,7 +60,8 @@ def get_alerts(): server_id = request.args.get('server_id') limit = request.args.get('limit', 50, type=int) - return jsonify(fleet_monitor_service.get_alerts(status, severity, server_id, limit)) + return jsonify(fleet_monitor_service.get_alerts( + get_current_user(), status, severity, server_id, limit)) @fleet_monitor_bp.route('/alerts//acknowledge', methods=['POST']) @@ -89,7 +95,7 @@ def resolve_alert(alert_id): def get_thresholds(): """Get alert thresholds.""" server_id = request.args.get('server_id') - return jsonify(fleet_monitor_service.get_thresholds(server_id)) + return jsonify(fleet_monitor_service.get_thresholds(get_current_user(), server_id)) @fleet_monitor_bp.route('/thresholds', methods=['POST']) @@ -120,7 +126,7 @@ def delete_threshold(threshold_id): def get_anomalies(): """Get anomaly detection results.""" server_id = request.args.get('server_id') - return jsonify(fleet_monitor_service.detect_anomalies(server_id)) + return jsonify(fleet_monitor_service.detect_anomalies(get_current_user(), server_id)) # ==================== Capacity Forecast ==================== @@ -146,7 +152,7 @@ def search_fleet(): if not query or len(query) < 2: return jsonify({'error': 'Query must be at least 2 characters'}), 400 - return jsonify(fleet_monitor_service.search_fleet(query, search_type)) + return jsonify(fleet_monitor_service.search_fleet(get_current_user(), query, search_type)) # ==================== Export ==================== @@ -163,7 +169,8 @@ def export_csv(): if not server_ids: return jsonify({'error': 'ids parameter is required'}), 400 - csv_data = fleet_monitor_service.export_metrics_csv(server_ids, metric, period) + csv_data = fleet_monitor_service.export_metrics_csv( + get_current_user(), server_ids, metric, period) return Response( csv_data, mimetype='text/csv', @@ -183,7 +190,8 @@ def export_json(): if not server_ids: return jsonify({'error': 'ids parameter is required'}), 400 - return jsonify(fleet_monitor_service.get_comparison_timeseries(server_ids, metric, period)) + return jsonify(fleet_monitor_service.get_comparison_timeseries( + get_current_user(), server_ids, metric, period)) # ==================== Prometheus ==================== diff --git a/backend/app/api/mobile.py b/backend/app/api/mobile.py index 5b2a6e78..74ec231f 100644 --- a/backend/app/api/mobile.py +++ b/backend/app/api/mobile.py @@ -4,6 +4,8 @@ from app.models.user import User from app import db from app.exceptions import not_found from app.api._request import json_object +from app.middleware.rbac import get_current_user +from app.services.workspace_service import WorkspaceService mobile_bp = Blueprint('mobile', __name__) @@ -100,7 +102,9 @@ def get_mobile_summary(): from app.models.server import Server from app.models.security_alert import SecurityAlert - server_count = Server.query.count() + # Only the servers this caller can reach — the workspace rule /servers applies. + server_count = WorkspaceService.filter_accessible_servers( + Server.query, get_current_user()).count() active_alerts = SecurityAlert.query.filter_by(resolved=False).count() if hasattr(SecurityAlert, 'resolved') else 0 # MonitoringService returns nested sections; a section that could not be @@ -122,7 +126,8 @@ def get_offline_data(): """Get data for offline caching.""" from app.models.server import Server - servers = Server.query.limit(50).all() + servers = WorkspaceService.filter_accessible_servers( + Server.query, get_current_user()).limit(50).all() return jsonify({ 'servers': [{'id': s.id, 'name': s.name, 'hostname': s.hostname, 'status': s.status} for s in servers], 'cached_at': __import__('datetime').datetime.utcnow().isoformat(), diff --git a/backend/app/api/proxy.py b/backend/app/api/proxy.py index 1fe8e648..d1dee8dd 100644 --- a/backend/app/api/proxy.py +++ b/backend/app/api/proxy.py @@ -33,14 +33,15 @@ def _require_server(server_id): @proxy_bp.route('/proxy/overview', methods=['GET']) @jwt_required() def proxy_overview(): - """Fleet-wide proxy posture: one row per server. + """Fleet-wide proxy posture: one row per server the caller can access. Mounted under ``/api/v1/servers`` → full path ``/api/v1/servers/proxy/ overview``. The static ``proxy`` segment can't match the ```` converter on ``//proxy``, and Werkzeug prefers static rules over dynamic ones, so the two never collide. Best-effort; always returns JSON. """ - return jsonify({'servers': ProxyStackService.fleet_overview()}) + from app.middleware.rbac import get_current_user + return jsonify({'servers': ProxyStackService.fleet_overview(get_current_user())}) @proxy_bp.route('//proxy', methods=['GET']) diff --git a/backend/app/api/servers.py b/backend/app/api/servers.py index ff51cb0c..fa821e1d 100644 --- a/backend/app/api/servers.py +++ b/backend/app/api/servers.py @@ -100,6 +100,20 @@ def _get_operable_server(server_id): return server +def _group_dict(group, include_servers=False): + """A server group as the current user sees it: a group is a fleet-wide + label, but its members and their count stop at the servers the caller + can access, so a group never lists a foreign workspace's servers.""" + from app.services.workspace_service import WorkspaceService + user = get_current_user() + servers = [s for s in group.servers if WorkspaceService.can_access_server(user, s)] + result = group.to_dict() + result['server_count'] = len(servers) + if include_servers: + result['servers'] = [s.to_dict() for s in servers] + return result + + def _ip_pattern_errors(allowed_ips): """One message per invalid allow-list entry; empty when all are valid.""" if not isinstance(allowed_ips, list): @@ -217,9 +231,10 @@ PERMISSION_PROFILES = { @servers_bp.route('/groups', methods=['GET']) @jwt_required() def list_groups(): - """List all server groups""" + """List all server groups. Groups are fleet-wide labels; the member + count is of the servers the caller can access.""" groups = ServerGroup.query.all() - return jsonify([g.to_dict() for g in groups]) + return jsonify([_group_dict(g) for g in groups]) @servers_bp.route('/groups', methods=['POST']) @@ -253,7 +268,7 @@ def get_group(group_id): if not group: return jsonify({'error': 'Group not found'}), 404 - return jsonify(group.to_dict(include_servers=True)) + return jsonify(_group_dict(group, include_servers=True)) @servers_bp.route('/groups/', methods=['PUT']) @@ -1300,7 +1315,7 @@ def get_server_metrics_aggregated(server_id): @developer_required def get_metrics_retention_stats(): """Get metrics retention statistics.""" - result = ServerMetricsService.get_retention_stats() + result = ServerMetricsService.get_retention_stats(get_current_user()) return jsonify(result) diff --git a/backend/app/services/fleet_monitor_service.py b/backend/app/services/fleet_monitor_service.py index 8f2b8d74..9e5185e0 100644 --- a/backend/app/services/fleet_monitor_service.py +++ b/backend/app/services/fleet_monitor_service.py @@ -20,6 +20,7 @@ from app.models.server import Server, ServerMetrics, ServerGroup from app.models.metric_alert import ServerAlertThreshold, MetricAlert from app.services.agent_registry import agent_registry from app.services.server_metrics_service import latest_metrics_by_server +from app.services.workspace_service import WorkspaceService logger = logging.getLogger(__name__) @@ -32,15 +33,40 @@ METRIC_COLUMNS = { } +def _visible_servers(user, query=None): + """A Server query narrowed to what *user* may see — the same workspace + rule as GET /servers. Every read below goes through this or + `_visible_server`; the unscoped `Server.query` is for the system-level + passes only (threshold checks, the token-gated Prometheus scrape).""" + return WorkspaceService.filter_accessible_servers( + Server.query if query is None else query, user) + + +def _visible_server(user, server_id): + """The server if *user* may see it, else None — a foreign id reads + exactly like an unknown one.""" + return WorkspaceService.get_accessible_server(user, server_id) + + +def _visible_server_ids(user): + """Subquery of the server ids *user* may see, for filtering child rows.""" + return WorkspaceService.filter_accessible_servers( + db.session.query(Server.id), user) + + class FleetMonitorService: - """Service for fleet-wide monitoring and alerting.""" + """Service for fleet-wide monitoring and alerting. + + The read methods take the calling ``user`` and answer only for servers that + user can access (GHSA-qcjj-hf95-6rgw). + """ # ==================== Fleet Heatmap ==================== @staticmethod - def get_fleet_heatmap(group_id: str = None) -> List[Dict]: - """Get latest metrics for all servers, shaped for heatmap display.""" - query = Server.query + def get_fleet_heatmap(user, group_id: str = None) -> List[Dict]: + """Latest metrics for the servers *user* can access, shaped for heatmap display.""" + query = _visible_servers(user) if group_id: query = query.filter_by(group_id=group_id) @@ -70,9 +96,11 @@ class FleetMonitorService: @staticmethod def get_comparison_timeseries( - server_ids: List[str], metric: str = 'cpu', period: str = '24h' + user, server_ids: List[str], metric: str = 'cpu', period: str = '24h' ) -> Dict: - """Get time-series data for multiple servers for overlay charting.""" + """Get time-series data for multiple servers for overlay charting. + + Ids *user* cannot access are skipped, like ids that do not exist.""" hours_back = {'1h': 1, '6h': 6, '24h': 24, '7d': 168, '30d': 720}.get(period, 24) interval = {'1h': 1, '6h': 5, '24h': 15, '7d': 60, '30d': 360}.get(period, 15) cutoff = datetime.utcnow() - timedelta(hours=hours_back) @@ -80,7 +108,7 @@ class FleetMonitorService: series = [] for server_id in server_ids: - server = Server.query.get(server_id) + server = _visible_server(user, server_id) if not server: continue @@ -113,9 +141,17 @@ class FleetMonitorService: # ==================== Alert Thresholds ==================== @staticmethod - def get_thresholds(server_id: str = None) -> List[Dict]: - """Get alert thresholds, optionally filtered by server.""" + def get_thresholds(user, server_id: str = None) -> List[Dict]: + """Get alert thresholds, optionally filtered by server. + + Global defaults (no server) are fleet policy and visible to everyone; + per-server overrides only for servers *user* can access.""" query = ServerAlertThreshold.query + if not user.is_admin: + query = query.filter( + (ServerAlertThreshold.server_id == None) | # noqa: E711 + ServerAlertThreshold.server_id.in_(_visible_server_ids(user)) + ) if server_id: query = query.filter( (ServerAlertThreshold.server_id == server_id) | @@ -286,11 +322,13 @@ class FleetMonitorService: @staticmethod def get_alerts( - status: str = None, severity: str = None, + user, status: str = None, severity: str = None, server_id: str = None, limit: int = 50 ) -> List[Dict]: - """Get metric alerts with filters.""" + """Get metric alerts for the servers *user* can access, with filters.""" query = MetricAlert.query.order_by(MetricAlert.created_at.desc()) + if not user.is_admin: + query = query.filter(MetricAlert.server_id.in_(_visible_server_ids(user))) if status: query = query.filter_by(status=status) if severity: @@ -322,9 +360,12 @@ class FleetMonitorService: # ==================== Anomaly Detection ==================== @staticmethod - def detect_anomalies(server_id: str = None) -> List[Dict]: + def detect_anomalies(user, server_id: str = None) -> List[Dict]: """Simple z-score anomaly detection on 7-day hourly averages.""" - servers = [Server.query.get(server_id)] if server_id else Server.query.filter_by(status='online').all() + if server_id: + servers = [_visible_server(user, server_id)] + else: + servers = _visible_servers(user).filter_by(status='online').all() cutoff = datetime.utcnow() - timedelta(days=7) anomalies = [] @@ -484,14 +525,14 @@ class FleetMonitorService: # ==================== Fleet Search ==================== @staticmethod - def search_fleet(query: str, search_type: str = 'any') -> List[Dict]: - """Search across all servers for containers, services, or ports.""" + def search_fleet(user, query: str, search_type: str = 'any') -> List[Dict]: + """Search the servers *user* can access for containers, services, or ports.""" query_lower = query.lower() results = [] # Search server names and hostnames if search_type in ('any', 'server'): - servers = Server.query.filter( + servers = _visible_servers(user).filter( (Server.name.ilike(f'%{query}%')) | (Server.hostname.ilike(f'%{query}%')) | (Server.ip_address.ilike(f'%{query}%')) @@ -510,7 +551,7 @@ class FleetMonitorService: if search_type in ('any', 'container'): connected = agent_registry.get_connected_servers() for server_id in connected: - server = Server.query.get(server_id) + server = _visible_server(user, server_id) if not server: continue @@ -536,7 +577,7 @@ class FleetMonitorService: # Search tags if search_type in ('any', 'tag'): - all_servers = Server.query.all() + all_servers = _visible_servers(user).all() for s in all_servers: if s.tags: for tag in s.tags: @@ -608,8 +649,8 @@ class FleetMonitorService: # ==================== CSV Export ==================== @staticmethod - def export_metrics_csv(server_ids: List[str], metric: str = 'cpu', period: str = '24h') -> str: - """Export metrics as CSV string.""" + def export_metrics_csv(user, server_ids: List[str], metric: str = 'cpu', period: str = '24h') -> str: + """Export metrics as CSV string, for the ids *user* can access.""" hours_back = {'1h': 1, '6h': 6, '24h': 24, '7d': 168, '30d': 720}.get(period, 24) cutoff = datetime.utcnow() - timedelta(hours=hours_back) col_name = METRIC_COLUMNS.get(metric, 'cpu_percent') @@ -619,7 +660,7 @@ class FleetMonitorService: writer.writerow(['timestamp', 'server_id', 'server_name', metric]) for server_id in server_ids: - server = Server.query.get(server_id) + server = _visible_server(user, server_id) if not server: continue diff --git a/backend/app/services/proxy_stack_service.py b/backend/app/services/proxy_stack_service.py index 7056ae29..0abd502d 100644 --- a/backend/app/services/proxy_stack_service.py +++ b/backend/app/services/proxy_stack_service.py @@ -478,10 +478,10 @@ class ProxyStackService: return None @staticmethod - def fleet_overview(): - """Fleet-wide proxy posture: one row per server. + def fleet_overview(user): + """Fleet-wide proxy posture: one row per server *user* can access. - Best-effort and guarded — never raises. Joins every ``Server`` with its + Best-effort and guarded — never raises. Joins each such ``Server`` with its ``ProxyStack`` (if one exists). Servers that never opted into a managed stack report the host-nginx default (``proxy_type='nginx'``, ``status='host'``) rather than being omitted, so the dashboard shows the @@ -499,7 +499,9 @@ class ProxyStackService: return [] try: - servers = Server.query.order_by(Server.name).all() + from app.services.workspace_service import WorkspaceService + servers = WorkspaceService.filter_accessible_servers( + Server.query, user).order_by(Server.name).all() except Exception as e: # pragma: no cover - DB guard logger.warning(f"fleet_overview server query failed: {e}") return [] diff --git a/backend/app/services/server_metrics_service.py b/backend/app/services/server_metrics_service.py index 12356b7f..e9919e87 100644 --- a/backend/app/services/server_metrics_service.py +++ b/backend/app/services/server_metrics_service.py @@ -13,7 +13,7 @@ from typing import Dict, List, Optional, Any from sqlalchemy import func, and_ from app import db -from app.models.server import ServerMetrics +from app.models.server import Server, ServerMetrics logger = logging.getLogger(__name__) @@ -284,28 +284,38 @@ class ServerMetricsService: return deleted @classmethod - def get_retention_stats(cls) -> Dict[str, Any]: - """Get statistics about metrics retention. + def get_retention_stats(cls, user) -> Dict[str, Any]: + """Get statistics about metrics retention, over the servers *user* + can access (admins: all of them). Returns: Dict with record counts, date ranges, and storage info """ try: - # Total count - total_count = ServerMetrics.query.count() - - # Count per server - server_counts = db.session.query( + from app.services.workspace_service import WorkspaceService + metrics = ServerMetrics.query + counts = db.session.query( ServerMetrics.server_id, func.count().label('count') - ).group_by(ServerMetrics.server_id).all() + ) + if not user.is_admin: + visible = WorkspaceService.filter_accessible_servers( + db.session.query(Server.id), user) + metrics = metrics.filter(ServerMetrics.server_id.in_(visible)) + counts = counts.filter(ServerMetrics.server_id.in_(visible)) + + # Total count + total_count = metrics.count() + + # Count per server + server_counts = counts.group_by(ServerMetrics.server_id).all() # Date range - oldest = ServerMetrics.query.order_by( + oldest = metrics.order_by( ServerMetrics.timestamp.asc() ).first() - newest = ServerMetrics.query.order_by( + newest = metrics.order_by( ServerMetrics.timestamp.desc() ).first() diff --git a/backend/tests/test_fleet_metrics_batching.py b/backend/tests/test_fleet_metrics_batching.py index 7d7b07d3..55b9e994 100644 --- a/backend/tests/test_fleet_metrics_batching.py +++ b/backend/tests/test_fleet_metrics_batching.py @@ -8,6 +8,7 @@ from sqlalchemy import event from app import db from app.models.server import Server, ServerMetrics +from factories import make_user from app.services.fleet_monitor_service import FleetMonitorService from app.services.server_metrics_service import latest_metrics_by_server @@ -79,10 +80,11 @@ def test_each_fleet_reader_uses_one_metrics_query( # Arrives later, but describes an older observation. seed_sample(server, now - timedelta(hours=1), 20) db.session.commit() + admin = make_user(db, role='admin') with metric_queries() as queries: if reader == 'heatmap': - result = FleetMonitorService.get_fleet_heatmap() + result = FleetMonitorService.get_fleet_heatmap(admin) assert len(result) == size assert all(row['cpu'] == 10 for row in result) elif reader == 'prometheus': @@ -115,7 +117,7 @@ def test_heatmap_keeps_group_scope_and_missing_metrics(app, db_session): included.group_id = group.id seed_server('excluded') db.session.commit() - result = FleetMonitorService.get_fleet_heatmap(group.id) + result = FleetMonitorService.get_fleet_heatmap(make_user(db, role='admin'), group.id) assert len(result) == 1 assert result[0]['id'] == included.id assert result[0]['group_name'] == 'selected' diff --git a/backend/tests/test_fleet_proxy.py b/backend/tests/test_fleet_proxy.py index 7e5fbe0a..b39450cb 100644 --- a/backend/tests/test_fleet_proxy.py +++ b/backend/tests/test_fleet_proxy.py @@ -13,6 +13,13 @@ from app.services.proxy_stack_service import ProxyStackService as PS from app.models.proxy_stack import ProxyStack # noqa: F401 +def _admin(): + """The overview is scoped to its caller; an admin sees the whole fleet.""" + from app import db + from factories import make_user + return make_user(db, role='admin') + + def _make_server(name, agent_id): from app import db from app.models.server import Server @@ -28,7 +35,7 @@ def _make_server(name, agent_id): def test_fleet_overview_empty_when_no_servers(app): with app.app_context(): - assert PS.fleet_overview() == [] + assert PS.fleet_overview(_admin()) == [] def test_fleet_overview_one_row_per_server(app): @@ -37,7 +44,7 @@ def test_fleet_overview_one_row_per_server(app): sid_b = _make_server('bravo', 'agent-fp-b') sid_c = _make_server('charlie', 'agent-fp-c') - overview = PS.fleet_overview() + overview = PS.fleet_overview(_admin()) # A row for every server, even ones that never opted into a stack. assert len(overview) == 3 ids = {row['server_id'] for row in overview} @@ -61,7 +68,7 @@ def test_fleet_overview_one_row_per_server(app): def test_fleet_overview_host_default_for_unconfigured(app): with app.app_context(): sid = _make_server('hostonly', 'agent-fp-host') - overview = PS.fleet_overview() + overview = PS.fleet_overview(_admin()) assert len(overview) == 1 row = overview[0] # No managed stack → host nginx, status 'host'. @@ -80,7 +87,7 @@ def test_fleet_overview_reflects_configured_stack(app): # Configure one server onto a managed Traefik stack. PS.configure(sid_traefik, proxy_type='traefik') - overview = PS.fleet_overview() + overview = PS.fleet_overview(_admin()) by_id = {row['server_id']: row for row in overview} # Configured server reflects its stack type; not the host default. @@ -120,7 +127,7 @@ def test_fleet_overview_recommendation_levels(app): # info: a stack server running with no apps yet. PS.switch(sid_idle_stack, 'caddy') - rows = {r['server_id']: r for r in PS.fleet_overview()} + rows = {r['server_id']: r for r in PS.fleet_overview(_admin())} warn = rows[sid_warn]['recommendation'] assert warn['level'] == 'warn' diff --git a/backend/tests/test_fleet_read_workspace_access.py b/backend/tests/test_fleet_read_workspace_access.py new file mode 100644 index 00000000..788a0d8a --- /dev/null +++ b/backend/tests/test_fleet_read_workspace_access.py @@ -0,0 +1,206 @@ +"""Fleet-wide READ routes obey the same workspace rule as /servers +(GHSA-qcjj-hf95-6rgw). + +`test_server_workspace_access.py` sweeps every `` route. The +routes here take no id in the path — they list, search or export across the +fleet, or take ids in the query string — so that sweep never reached them and +they answered from unfiltered `Server` / `ServerMetrics` queries. +""" +import re +from datetime import datetime, timedelta + +import pytest + +from factories import headers_for, make_server, make_user + +NAME = 'frw-tenantb-billing-db' +HOST = 'frw-billing.internal' +IP = '10.99.77.5' +CONTAINER = 'frw-ledger-postgres' +TAG = 'frw-pci-scope' + + +@pytest.fixture +def setup(app): + from app import db + from app.models.metric_alert import MetricAlert, ServerAlertThreshold + from app.models.server import ServerGroup, ServerMetrics + from app.services.workspace_service import WorkspaceService + + admin = make_user(db, 'frw_admin', 'admin') + member = make_user(db, 'frw_member', 'developer') + outsider = make_user(db, 'frw_outsider', 'developer') + viewer = make_user(db, 'frw_viewer', 'viewer') + ws = WorkspaceService.create_workspace({'name': 'FRW'}, admin.id) + WorkspaceService.add_member(ws.id, member.id) + WorkspaceService.create_workspace({'name': 'FRW-out'}, outsider.id) + + # Groups are fleet-wide labels, so a foreign server can sit in one. + group = ServerGroup(name='frw-group') + db.session.add(group) + db.session.commit() + server = make_server(db, name=NAME, hostname=HOST, ip_address=IP, + status='online', tags=[TAG], workspace_id=ws.id, + group_id=group.id) + # A flat week with a spike at the end: enough samples for the comparison + # and export routes, and an outlier for the anomaly detector. + now = datetime.utcnow() + for i in range(30): + last = i == 29 + db.session.add(ServerMetrics( + server_id=server.id, + timestamp=now - timedelta(minutes=(29 - i) * 20), + cpu_percent=99.0 if last else 10.0 + (i % 2), + memory_percent=88.2, disk_percent=91.4, + extra={'containers': [{'name': CONTAINER, 'image': 'postgres:16', + 'status': 'running'}]})) + db.session.add(MetricAlert(server_id=server.id, metric='cpu', + severity='critical', value=99.0, threshold=95.0)) + db.session.add(ServerAlertThreshold(server_id=server.id, metric='cpu')) + db.session.add(ServerAlertThreshold(server_id=None, metric='disk')) + db.session.commit() + return {'server': server.id, 'group': group.id, 'admin': admin.id, + 'member': member.id, 'outsider': outsider.id, 'viewer': viewer.id} + + +def _leaks(setup, text): + return [needle for needle in (setup['server'], NAME, HOST, IP, CONTAINER, TAG) + if needle in text] + + +def _fleet_reads(sid, gid): + return [ + f'/api/v1/servers/groups/{gid}', + '/api/v1/servers/proxy/overview', + '/api/v1/fleet-monitor/heatmap', + f'/api/v1/fleet-monitor/comparison?ids={sid}&metric=cpu&period=24h', + '/api/v1/fleet-monitor/alerts', + f'/api/v1/fleet-monitor/alerts?server_id={sid}', + '/api/v1/fleet-monitor/thresholds', + f'/api/v1/fleet-monitor/thresholds?server_id={sid}', + '/api/v1/fleet-monitor/anomalies', + f'/api/v1/fleet-monitor/anomalies?server_id={sid}', + '/api/v1/fleet-monitor/search?q=frw-', + '/api/v1/fleet-monitor/search?q=10.99', + '/api/v1/fleet-monitor/search?q=frw-ledger&type=container', + '/api/v1/fleet-monitor/search?q=frw-pci&type=tag', + f'/api/v1/fleet-monitor/export/csv?ids={sid}&metric=memory', + f'/api/v1/fleet-monitor/export/json?ids={sid}&metric=cpu', + '/api/v1/mobile/offline-cache', + ] + + +# Developer-only reads: a viewer is refused outright, before any scoping. +_DEVELOPER_READS = ['/api/v1/servers/metrics/retention'] + + +@pytest.mark.parametrize('who', ['outsider', 'viewer']) +def test_non_member_reads_nothing_about_a_foreign_server(client, setup, who): + leaked = {} + with _connected(setup['server']): + for url in _fleet_reads(setup['server'], setup['group']) + _DEVELOPER_READS: + resp = client.get(url, headers=headers_for(setup[who])) + if who == 'viewer' and url in _DEVELOPER_READS: + assert resp.status_code == 403, (url, resp.status_code) + else: + assert resp.status_code == 200, (url, resp.status_code) + found = _leaks(setup, resp.get_data(as_text=True)) + if found: + leaked[url] = found + assert not leaked, leaked + + +@pytest.mark.parametrize('who', ['member', 'admin']) +def test_member_and_admin_still_read_their_server(client, setup, who): + """The fix narrows, it must not blank the page for people who belong.""" + missing = [] + with _connected(setup['server']): + for url in _fleet_reads(setup['server'], setup['group']) + _DEVELOPER_READS: + resp = client.get(url, headers=headers_for(setup[who])) + assert resp.status_code == 200, (url, resp.status_code) + if not _leaks(setup, resp.get_data(as_text=True)): + missing.append(url) + assert not missing, missing + + +def test_global_thresholds_stay_visible_to_everyone(client, setup): + """A threshold with no server is fleet policy, not a tenant's data.""" + rows = client.get('/api/v1/fleet-monitor/thresholds', + headers=headers_for(setup['outsider'])).get_json() + assert [r['metric'] for r in rows] == ['disk'] + assert rows[0]['server_id'] is None + + +def test_mobile_summary_counts_only_accessible_servers(client, setup): + def count(who): + return client.get('/api/v1/mobile/summary', + headers=headers_for(setup[who])).get_json()['servers'] + assert count('member') == count('outsider') + 1 + assert count('admin') == count('member') + + +def test_comparison_keeps_accessible_ids_and_drops_foreign_ones(client, setup, app): + """A mixed id list answers for the caller's own servers only — the foreign + id is dropped silently, exactly as an unknown id already was.""" + from app import db + from app.models.server import ServerMetrics + own = make_server(db, name='frw-shared-box') + db.session.add(ServerMetrics(server_id=own.id, cpu_percent=5.0)) + db.session.commit() + body = client.get( + f"/api/v1/fleet-monitor/comparison?ids={setup['server']},{own.id}", + headers=headers_for(setup['outsider'])).get_json() + assert [s['server_id'] for s in body['series']] == [own.id] + + +def _connected(server_id): + from unittest.mock import patch + return patch('app.services.agent_registry.agent_registry.get_connected_servers', + return_value=[server_id]) + + +def test_group_member_count_stops_at_accessible_servers(client, setup): + def count(who): + rows = client.get('/api/v1/servers/groups', + headers=headers_for(setup[who])).get_json() + return next(r['server_count'] for r in rows if r['id'] == setup['group']) + assert (count('outsider'), count('member'), count('admin')) == (0, 1, 1) + + +def _fleet_get_rules(app, setup): + """Every GET route with no path parameter, plus the ones keyed by a server + group. `` routes have their own sweep in + test_server_workspace_access.py.""" + for rule in app.url_map.iter_rules(): + if not rule.rule.startswith('/api/v1/') or 'GET' not in rule.methods: + continue + url = rule.rule.replace('', setup['group']) + if '<' in url: + continue + yield url + + +def test_no_fleet_read_route_leaks_a_foreign_server(app, client, setup): + """Sweep: whatever list/search/export/summary route exists — including one + added after this test — a developer outside the workspace never gets the + foreign server's id, name, hostname, IP, tag or container back. The + member test above proves those needles are reachable through the same + routes, so an empty answer here is the filter and not a blank fixture.""" + sid = setup['server'] + # Ask for the foreign server every way a route might accept: an id-taking + # route answers for it, a search route matches it, the rest ignore it. + query = f'?ids={sid}&server_id={sid}&q=frw-&query=frw-&search=frw-' + leaks = [] + with _connected(sid): + for rule in sorted(set(_fleet_get_rules(app, setup))): + url = rule + query + try: + resp = client.get(url, headers=headers_for(setup['outsider'])) + except Exception as exc: # a route that crashes is not a leak + if re.search('frw-', str(exc)): + leaks.append(f'GET {url} raised with the server in it') + continue + found = _leaks(setup, resp.get_data(as_text=True)) + if found: + leaks.append(f'GET {url} -> {resp.status_code} {found}') + assert not leaks, '\n'.join(leaks) diff --git a/backend/tests/test_ingress_plane.py b/backend/tests/test_ingress_plane.py index bb0e529d..c830dce1 100644 --- a/backend/tests/test_ingress_plane.py +++ b/backend/tests/test_ingress_plane.py @@ -104,7 +104,10 @@ def test_fleet_overview_reports_mismatch_counts(app): s = _make_server(app, 'fleet-srv') ProxyStackService.switch(s.id, 'caddy') _make_app(s.id, 'php', name='php-site') # nginx plane on a caddy server -> mismatch - rows = {r['server_id']: r for r in ProxyStackService.fleet_overview()} + from app import db + from factories import make_user + admin = make_user(db, role='admin') + rows = {r['server_id']: r for r in ProxyStackService.fleet_overview(admin)} row = rows[s.id] assert row['proxy_type'] == 'caddy' assert row['app_count'] == 1 From f68819da02ce758d9c15a3725b93a0b86f30e157 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sun, 22 Nov 2026 01:50:15 -0500 Subject: [PATCH 02/13] Let ACME challenges past the dotfile deny The shipped vhosts deny dotfiles with `location ~ /\.`, which also matches /.well-known/acme-challenge/. nginx prefers a matching regex location over a plain prefix one, so on the plain HTTP vhost (both in one server block) HTTP-01 answered 403 and issuance and renewal failed; a hand fix was undone by the next update re-copying the file. `^~` stops the regex pass. Part of #269. --- .../test_nginx_acme_challenge_location.py | 49 +++++++++++++++++++ nginx/nginx.conf | 2 +- nginx/sites-available/example.conf.template | 2 +- nginx/sites-available/serverkit-insecure.conf | 2 +- nginx/sites-available/serverkit.conf | 2 +- 5 files changed, 53 insertions(+), 4 deletions(-) create mode 100644 backend/tests/test_nginx_acme_challenge_location.py diff --git a/backend/tests/test_nginx_acme_challenge_location.py b/backend/tests/test_nginx_acme_challenge_location.py new file mode 100644 index 00000000..912b97a9 --- /dev/null +++ b/backend/tests/test_nginx_acme_challenge_location.py @@ -0,0 +1,49 @@ +"""The shipped nginx configs must let Let's Encrypt HTTP-01 through (issue #269). + +Each vhost denies dotfiles with the regex location ``location ~ /\\.``. That +regex also matches ``/.well-known/acme-challenge/``, and nginx prefers +a matching regex location over a plain prefix location — so a plain +``location /.well-known/acme-challenge/`` in the same server block loses and +the challenge answers 403. Issuance and renewal then fail, and a hand fix was +undone by the next ``serverkit update`` re-copying the shipped file. + +``^~`` on the prefix location tells nginx to stop there and skip the regex +pass, which is the only form that wins. +""" +import re +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] + +CONFIGS = [ + ROOT / 'nginx' / 'nginx.conf', + ROOT / 'nginx' / 'sites-available' / 'serverkit.conf', + ROOT / 'nginx' / 'sites-available' / 'serverkit-insecure.conf', + ROOT / 'nginx' / 'sites-available' / 'example.conf.template', +] + +_ACME = re.compile(r'^\s*location\s+(?P\S+\s+)?/\.well-known/acme-challenge/\s*\{', + re.MULTILINE) +_DOTFILE_DENY = re.compile(r'^\s*location\s+~\*?\s+/\\\.\s*\{', re.MULTILINE) + + +@pytest.mark.parametrize('config', CONFIGS, ids=lambda p: p.name) +def test_acme_challenge_location_beats_the_dotfile_deny(config): + text = config.read_text(encoding='utf-8') + locations = list(_ACME.finditer(text)) + assert locations, f'{config.name}: no ACME challenge location to serve HTTP-01' + for match in locations: + assert (match.group('modifier') or '').strip() == '^~', ( + f'{config.name}: the ACME challenge location must be ' + f'`location ^~ /.well-known/acme-challenge/` or the dotfile deny wins') + + +def test_the_collision_this_guards_is_real(): + """At least one shipped server block carries both locations — the plain + HTTP vhost — so the modifier is load-bearing, not decoration.""" + text = (ROOT / 'nginx' / 'sites-available' / 'serverkit-insecure.conf').read_text( + encoding='utf-8') + assert _ACME.search(text) and _DOTFILE_DENY.search(text) + assert text.count('server {') == 1 diff --git a/nginx/nginx.conf b/nginx/nginx.conf index 66d0624e..f8a03ace 100644 --- a/nginx/nginx.conf +++ b/nginx/nginx.conf @@ -67,7 +67,7 @@ http { server_name _; # Allow Let's Encrypt verification - location /.well-known/acme-challenge/ { + location ^~ /.well-known/acme-challenge/ { root /var/www/certbot; } diff --git a/nginx/sites-available/example.conf.template b/nginx/sites-available/example.conf.template index adf08076..bbf024ed 100644 --- a/nginx/sites-available/example.conf.template +++ b/nginx/sites-available/example.conf.template @@ -15,7 +15,7 @@ server { listen 80; server_name example.builditdesign.com; # Change this to your domain - location /.well-known/acme-challenge/ { + location ^~ /.well-known/acme-challenge/ { root /var/www/certbot; } diff --git a/nginx/sites-available/serverkit-insecure.conf b/nginx/sites-available/serverkit-insecure.conf index c417aca0..16c41fc8 100644 --- a/nginx/sites-available/serverkit-insecure.conf +++ b/nginx/sites-available/serverkit-insecure.conf @@ -26,7 +26,7 @@ server { # scanners (Shodan/Censys) ignore this; real hiding is access control. add_header X-Robots-Tag "noindex, nofollow, noarchive" always; - location /.well-known/acme-challenge/ { + location ^~ /.well-known/acme-challenge/ { root /var/www/certbot; } diff --git a/nginx/sites-available/serverkit.conf b/nginx/sites-available/serverkit.conf index eaeb561a..e30ff377 100644 --- a/nginx/sites-available/serverkit.conf +++ b/nginx/sites-available/serverkit.conf @@ -46,7 +46,7 @@ server { server_name _; # Allow Let's Encrypt validation over plain HTTP - location /.well-known/acme-challenge/ { + location ^~ /.well-known/acme-challenge/ { root /var/www/certbot; } From 73e2251e2870b6b4e91625c9fd73fa4ed407fb2c Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sun, 22 Nov 2026 01:50:18 -0500 Subject: [PATCH 03/13] Stop --help from running site commands `serverkit add-site --help` wrote a vhost for a site named "--help" and `setup-proxy --help` reran the proxy setup, which reset the panel's certificate paths. Subcommands that take plain positionals now print their usage for --help/-h and stop before any command code runs, and add-site/remove-site refuse a name that is not a hostname. Part of #269. --- scripts/test/test_cli.sh | 80 ++++++++++++++++++++++++++++++++++++++++ serverkit | 64 ++++++++++++++++++++++++++++++++ 2 files changed, 144 insertions(+) diff --git a/scripts/test/test_cli.sh b/scripts/test/test_cli.sh index ab5995ff..80d999c3 100644 --- a/scripts/test/test_cli.sh +++ b/scripts/test/test_cli.sh @@ -835,6 +835,86 @@ else bad "flags lost between wrapper and cli.py:$t20_fail" fi +# -------------------------------------------------------------------------- +# T21 — a help flag on a plain-positional subcommand must print usage and +# change nothing (issue #269). `add-site --help` used to write a vhost for a +# site named "--help"; `setup-proxy --help` reran the proxy setup and reset +# the panel's certificate paths. Runs through the real executed-mode dispatch +# with the root check out of the way, so "it stopped early" can only mean the +# help guard and not a missing-root refusal. +t="$WORK/t21"; mkdir -p "$t/install/scripts" "$t/nginx/sites-available" "$t/nginx/sites-enabled" +cat > "$t/install/scripts/setup-nginx-proxy.sh" < "$t/proxy-setup-ran" +EOF +chmod +x "$t/install/scripts/setup-nginx-proxy.sh" +# The dispatch runs with the script's own functions, so the root check is +# neutralised by a wrapper that sources the CLI's functions and replays the +# dispatch block verbatim. +cat > "$t/run.sh" <&1 /dev/null | tr ' +' ' ')" +if [ -n "$written" ]; then + t21_fail="$t21_fail [a help flag wrote nginx config: $written]" +fi +[ ! -e "$t/proxy-setup-ran" ] || t21_fail="$t21_fail [setup-proxy --help ran the proxy setup]" +if [ -z "$t21_fail" ]; then + ok "--help on a plain subcommand prints its usage and touches nothing" +else + bad "--help had side effects or no usage:$t21_fail" +fi + +# T21b — the guard must not swallow the real command: the same wrapper still +# writes the vhost and runs the proxy setup when no help flag is present. +out="$(run_plain add-site t21.example.com 3210)" +run_plain setup-proxy >/dev/null +if [ -f "$t/nginx/sites-available/t21.example.com.conf" ] \ + && grep -q 'proxy_pass http://127.0.0.1:3210;' "$t/nginx/sites-available/t21.example.com.conf" \ + && [ -e "$t/proxy-setup-ran" ]; then + ok "add-site and setup-proxy still do their work without a help flag" +else + bad "the help guard broke the real commands: [$out]" +fi + +# T21c — a site name that is not a hostname (a stray flag, a path) is refused +# before anything is written or removed. +t21c_fail="" +for name in "--frobnicate" "../etc/passwd" "a b" ".hidden"; do + out="$(run_plain add-site "$name")"; rc=$? + [ "$rc" -ne 0 ] || t21c_fail="$t21c_fail [add-site '$name' exited 0]" + out="$(run_plain remove-site "$name")"; rc=$? + [ "$rc" -ne 0 ] || t21c_fail="$t21c_fail [remove-site '$name' exited 0]" +done +out="$(run_plain add-site t21c.example.com notaport)"; rc=$? +[ "$rc" -ne 0 ] || t21c_fail="$t21c_fail [add-site with a non-numeric port exited 0]" +if [ "$(ls "$t/nginx/sites-available" | tr '\n' ' ')" != "t21.example.com.conf " ]; then + t21c_fail="$t21c_fail [unexpected vhosts: $(ls "$t/nginx/sites-available" | tr '\n' ' ')]" +fi +if [ -z "$t21c_fail" ]; then + ok "add-site/remove-site refuse a name that is not a hostname" +else + bad "invalid site names got through:$t21c_fail" +fi + # -------------------------------------------------------------------------- printf '\n%d passed, %d failed, %d skipped\n\n' "$PASS" "$FAIL" "$SKIP" [ "$FAIL" -eq 0 ] diff --git a/serverkit b/serverkit index ade58df7..723768e8 100644 --- a/serverkit +++ b/serverkit @@ -1084,6 +1084,13 @@ reload_nginx_or_warn() { print_warning "Could not reload nginx — apply the change manually: systemctl reload nginx (or nginx -s reload)" } +# A site name becomes a file under the nginx dir and a server_name, so it has +# to look like a hostname. Anything else — a stray flag above all — is +# refused before a single file is written or removed. +valid_site_domain() { + [[ "$1" =~ ^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$ ]] +} + cmd_add_site() { check_root @@ -1099,6 +1106,18 @@ cmd_add_site() { exit 1 fi + if ! valid_site_domain "$DOMAIN"; then + print_error "Not a valid domain: $DOMAIN" + echo "Usage: serverkit add-site [port]" + exit 1 + fi + + if ! [[ "$PORT" =~ ^[0-9]+$ ]]; then + print_error "Not a valid port: $PORT" + echo "Usage: serverkit add-site [port]" + exit 1 + fi + resolve_site_paths "$DOMAIN" if [ -f "$SITE_FILE" ]; then @@ -1554,6 +1573,12 @@ cmd_remove_site() { exit 1 fi + if ! valid_site_domain "$DOMAIN"; then + print_error "Not a valid domain: $DOMAIN" + echo "Usage: serverkit remove-site " + exit 1 + fi + resolve_site_paths "$DOMAIN" if [ ! -f "$SITE_FILE" ]; then @@ -1575,6 +1600,40 @@ cmd_remove_site() { fi } +# Subcommands that take plain positional arguments (or none) and parse no +# flags of their own. A help flag used to fall through to them as a +# positional: `add-site --help` wrote a vhost for a site named "--help", and +# `setup-proxy --help` reran the proxy setup, resetting the panel's +# certificate paths. For these, --help/-h anywhere prints usage and stops +# before any command code runs. Commands missing from this list parse their +# own flags (update, uninstall, cleanup-apps) or hand them to cli.py. +PLAIN_COMMANDS="start stop restart status logs branch check-update setup-code init-db migrate-db factory-reset backup-db restore-db generate-keys config setup-proxy create-app start-app stop-app app-logs add-site list-sites remove-site doctor completion" + +wants_help() { + local arg + for arg in "$@"; do + case "$arg" in + --help|-h) return 0 ;; + esac + done + return 1 +} + +command_usage() { + local cmd="$1" args="" + case "$cmd" in + logs) args=" [backend|frontend|nginx|all]" ;; + restore-db) args=" " ;; + start-app|stop-app|app-logs) args=" " ;; + add-site) args=" [port]" ;; + remove-site) args=" " ;; + doctor) args=" [--fix]" ;; + esac + echo "Usage: serverkit ${cmd}${args}" + # The command's one-line description from the main help, when it has one. + cmd_help 2>/dev/null | grep -m1 -E "^ ${cmd}( |\$)" | sed -E "s/^ ${cmd} +/ /" || true +} + # Main # # Sourcing this file (e.g. from scripts/test/test_cli.sh) exposes every @@ -1582,6 +1641,11 @@ cmd_remove_site() { # pattern as scripts/update.sh. Only direct execution runs the dispatch below. [ "${BASH_SOURCE[0]}" = "${0}" ] || return 0 +if [ $# -gt 1 ] && [[ " $PLAIN_COMMANDS " == *" $1 "* ]] && wants_help "${@:2}"; then + command_usage "$1" + exit 0 +fi + case "${1:-help}" in help|--help|-h) cmd_help From 4ba435243f464c3b5f402a05f939e5ce28905a8e Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sun, 22 Nov 2026 02:02:44 -0500 Subject: [PATCH 04/13] Adopt sites already running on the host A site set up by hand or by a migration serves traffic but has no application, domain or WordPress row, so the panel cannot see it. Every existing entry point creates something (a vhost, a copy of the files), which is wrong for a site that is live. Discovery reads the live nginx config, the PHP-FPM pools, the certificate and wp-config.php. Adopting writes rows only, as a dry run unless asked otherwise. The app is managed_by 'host', and the vhost writer, drift repair, lifecycle and delete paths leave its running config alone. The doctor reports sites nginx serves that no application accounts for. Part of #269. --- backend/app/api/apps.py | 15 +- backend/app/api/site_adoption.py | 61 ++ backend/app/core_blueprints.py | 1 + backend/app/models/application.py | 14 +- .../services/application_lifecycle_service.py | 14 + backend/app/services/application_restore.py | 18 +- backend/app/services/doctor_service.py | 32 ++ backend/app/services/drift_service.py | 4 +- backend/app/services/previews/plan.py | 4 +- backend/app/services/site_adoption_service.py | 541 ++++++++++++++++++ backend/app/services/site_domain_service.py | 8 + backend/tests/test_site_adoption.py | 377 ++++++++++++ 12 files changed, 1077 insertions(+), 12 deletions(-) create mode 100644 backend/app/api/site_adoption.py create mode 100644 backend/app/services/site_adoption_service.py create mode 100644 backend/tests/test_site_adoption.py diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py index 369a9adb..d8dc6c81 100644 --- a/backend/app/api/apps.py +++ b/backend/app/api/apps.py @@ -85,6 +85,13 @@ def _sync_manual_app_status(app): elif app.managed_by == 'docker_compose' and app.root_path: status = ProcessService.get_compose_project_status(app.root_path, compose_file=app.compose_file) actual = status.get('status', 'stopped') + elif app.is_host_managed: + # Served by host nginx: the site is up when nginx is. A probe that + # cannot answer leaves the recorded status alone rather than guess. + status = ProcessService.get_systemd_unit_status('nginx') + if not status.get('success') or status.get('status') == 'unknown': + return + actual = 'running' if status.get('active') else 'stopped' else: return @@ -1029,8 +1036,12 @@ def create_manual_app(): else: managed_by = 'docker_compose' - if managed_by not in ('docker_compose', 'systemd'): - return jsonify({'error': "managed_by must be 'docker_compose' or 'systemd'"}), 400 + if managed_by not in ('docker_compose', 'systemd', Application.MANAGED_BY_HOST): + return jsonify({'error': "managed_by must be 'docker_compose', 'systemd' or 'host'"}), 400 + + if managed_by == Application.MANAGED_BY_HOST and app_type not in ('php', 'static', 'wordpress'): + return jsonify({'error': "managed_by 'host' is for php, static and wordpress sites " + 'served by host nginx'}), 400 if managed_by == 'docker_compose' and not compose_file: if not os.path.exists(os.path.join(root_path, 'docker-compose.yml')): diff --git a/backend/app/api/site_adoption.py b/backend/app/api/site_adoption.py new file mode 100644 index 00000000..446f4a9e --- /dev/null +++ b/backend/app/api/site_adoption.py @@ -0,0 +1,61 @@ +"""Site adoption API — register sites that already run on this host. + +Mounted at /api/v1/site-adoption (see app/core_blueprints.py). Admin-only: +discovery reads the host's nginx, PHP-FPM and site configuration, and adopting +creates an application any admin could then operate. + +Nothing here writes to the host. See app/services/site_adoption_service.py. +""" +from flask import Blueprint, jsonify, request + +from app.api._request import json_object +from app.middleware.rbac import admin_required, get_current_user +from app.services import site_adoption_service +from app.services.site_adoption_service import SiteAdoptionError + +site_adoption_bp = Blueprint('site_adoption', __name__) + + +@site_adoption_bp.route('/sites', methods=['GET']) +@admin_required +def list_sites(): + """Every site host nginx serves, and whether an application accounts for + it. ``unmanaged`` is the drift count: live sites the panel cannot see.""" + sites = site_adoption_service.discover() + return jsonify({ + 'sites': sites, + 'unmanaged': sum(1 for site in sites if site['linked_app'] is None), + 'adoptable': sum(1 for site in sites if site['adoptable']), + }), 200 + + +@site_adoption_bp.route('/adopt', methods=['POST']) +@admin_required +def adopt_site(): + """Adopt one site. A dry run unless the body says ``"dry_run": false`` — + the default answer is the plan, never the change.""" + data = json_object() + identifier = (data.get('site') or '').strip() + if not identifier: + return jsonify({'error': 'site is required'}), 400 + name = (data.get('name') or '').strip() or None + + if data.get('dry_run', True) is not False: + site = site_adoption_service.find(identifier) + if site is None: + return jsonify({'error': f'No site served by host nginx matches "{identifier}".'}), 404 + return jsonify({'dry_run': True, 'adoptable': site['adoptable'], + 'reason': site['reason'], + 'plan': site_adoption_service.plan(site, name)}), 200 + + user = get_current_user() + from app.services.workspace_service import WorkspaceService + workspace_id = WorkspaceService.resolve_workspace_id( + user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id')) + try: + application, plan = site_adoption_service.adopt( + identifier, user, name=name, workspace_id=workspace_id) + except SiteAdoptionError as exc: + return jsonify({'error': str(exc)}), exc.status + return jsonify({'message': 'Site adopted', 'dry_run': False, 'plan': plan, + 'app': application.to_dict()}), 201 diff --git a/backend/app/core_blueprints.py b/backend/app/core_blueprints.py index 4743fbdc..68c2b669 100644 --- a/backend/app/core_blueprints.py +++ b/backend/app/core_blueprints.py @@ -271,6 +271,7 @@ CORE_BLUEPRINTS: tuple[BlueprintSpec, ...] = ( BlueprintSpec('app.api.ai', 'ai_bp', '/api/v1/ai'), BlueprintSpec('app.api.speed_test', 'speedtest_bp', '/api/v1/speedtest'), BlueprintSpec('app.api.site_imports', 'site_imports_bp', '/api/v1/imports'), + BlueprintSpec('app.api.site_adoption', 'site_adoption_bp', '/api/v1/site-adoption'), BlueprintSpec('app.api.doctor', 'doctor_bp', '/api/v1/doctor'), BlueprintSpec( 'app.api.fleet_doctor', diff --git a/backend/app/models/application.py b/backend/app/models/application.py index 479e7649..59ae2efb 100644 --- a/backend/app/models/application.py +++ b/backend/app/models/application.py @@ -88,7 +88,7 @@ class Application(JsonColumnMixin, TimestampMixin, SoftDeleteMixin, db.Model): # Manual / local service configuration compose_file = db.Column(db.String(200), nullable=True) systemd_unit = db.Column(db.String(100), nullable=True) - managed_by = db.Column(db.String(20), nullable=True) # 'docker_compose', 'systemd' + managed_by = db.Column(db.String(20), nullable=True) # 'docker_compose', 'systemd', 'host' # Ingress plane: which reverse proxy is expected to serve this app — # 'nginx' (host Nginx, the default) or 'proxy_stack' (Dockerized @@ -186,6 +186,18 @@ class Application(JsonColumnMixin, TimestampMixin, SoftDeleteMixin, db.Model): from app.utils.slug import app_name_clash_error return app_name_clash_error(cls.query.filter_by(name=name).first(), name, suffix) + # A site that was already running on the host when the panel adopted it + # (nginx + PHP-FPM, or static files): its vhost, pool and certificate + # were written by someone else and stay theirs. + MANAGED_BY_HOST = 'host' + + @property + def is_host_managed(self): + """True for an adopted host site. The panel records and observes it + but must never write, rewrite or remove its running config — every + path that touches nginx or the runtime for an app checks this.""" + return self.managed_by == self.MANAGED_BY_HOST + @property def live_domains(self): """The domains this app actually serves — tombstones excluded. diff --git a/backend/app/services/application_lifecycle_service.py b/backend/app/services/application_lifecycle_service.py index 58009d66..b5ec4510 100644 --- a/backend/app/services/application_lifecycle_service.py +++ b/backend/app/services/application_lifecycle_service.py @@ -140,8 +140,20 @@ def _ensure_local_image_compose(app): db.session.commit() +def _refuse_host_managed(app, action): + """An adopted host site is served by the host's own nginx and PHP-FPM, + shared with every other site on the box. There is no per-site runtime to + start or stop, and flipping the status column would only make the panel + lie about a site that is still serving.""" + if app.is_host_managed: + raise ApplicationLifecycleError( + f'Cannot {action} a host-managed site: it is served by this server\'s ' + 'nginx and PHP-FPM, which ServerKit does not control per site.') + + def start_application(app, *, user_id=None): """Start the configured runtime, materializing local image apps if needed.""" + _refuse_host_managed(app, 'start') # A local BYO-image docker app (image set, no source yet) has no compose to # launch — materialize one on first start so it can actually run. if app.app_type == 'docker' and not app.root_path and app.docker_image and not app.server_id: @@ -197,6 +209,7 @@ def start_application(app, *, user_id=None): def stop_application(app, *, user_id=None): """Stop the configured runtime; a vanished single container is stopped.""" + _refuse_host_managed(app, 'stop') # Handle Docker apps if app.app_type == 'docker' and app.root_path: if app.server_id: @@ -234,6 +247,7 @@ def stop_application(app, *, user_id=None): def restart_application(app, *, user_id=None): """Restart the configured runtime, requiring a deployed single container.""" + _refuse_host_managed(app, 'restart') # Handle Docker apps if app.app_type == 'docker' and app.root_path: if app.server_id: diff --git a/backend/app/services/application_restore.py b/backend/app/services/application_restore.py index 4252780d..f39bcbe2 100644 --- a/backend/app/services/application_restore.py +++ b/backend/app/services/application_restore.py @@ -206,12 +206,18 @@ def suspend_application(app, user_id=None): except Exception as exc: # noqa: BLE001 results['docker'] = {'error': str(exc)} - try: - NginxService.disable_site(app.name) - NginxService.delete_site(app.name) - results['nginx'] = {'success': True} - except Exception as exc: # noqa: BLE001 - results['nginx'] = {'error': str(exc)} + if app.is_host_managed: + # Deleting an adopted site forgets it; it does not take it offline. + # The vhost was never ours, and a site named like its vhost file + # would otherwise lose its live config here. + results['nginx'] = {'success': True, 'skipped': 'host-managed'} + else: + try: + NginxService.disable_site(app.name) + NginxService.delete_site(app.name) + results['nginx'] = {'success': True} + except Exception as exc: # noqa: BLE001 + results['nginx'] = {'error': str(exc)} try: results['cron'] = {'suspended': CronService.suspend_for_application(app.id)} diff --git a/backend/app/services/doctor_service.py b/backend/app/services/doctor_service.py index a34ccba6..bbd1548b 100644 --- a/backend/app/services/doctor_service.py +++ b/backend/app/services/doctor_service.py @@ -705,6 +705,37 @@ class DoctorService: return [_check('extensions.checks', 'Extension checks', 'warn', f'Could not collect extension checks: {e}')] + @classmethod + def _unmanaged_site_checks(cls): + """Sites host nginx is serving that no application accounts for. + + Such a site is live but invisible to the panel: no monitoring, + backups, SSL status or logs, while its database may well be listed + under Databases. One warning per site; a host with none adds nothing. + Not repairable — adopting is the operator's call, and it is one + command (or one click) away in the detail.""" + try: + from app.services import site_adoption_service + sites = site_adoption_service.unmanaged() + except Exception as e: # noqa: BLE001 + logger.warning('unmanaged-site doctor section failed: %s', e) + return [_check('sites.unmanaged', 'Unmanaged sites', 'warn', + f'Could not read the host nginx config: {e}')] + checks = [] + for site in sites: + if site['kind'] == site_adoption_service.KIND_REDIRECT: + continue # a redirect-only vhost has no site behind it + if site['adoptable']: + detail = (f"Served by host nginx ({site['vhost_file']}) but not registered " + f"in ServerKit. Adopt it from Services, or run: " + f"serverkit adopt-site {site['primary_domain']} --apply") + else: + detail = (f"Served by host nginx ({site['vhost_file']}) but not registered " + f"in ServerKit. {site['reason']}") + checks.append(_check(f"sites.unmanaged.{site['id']}", + f"Unmanaged site: {site['primary_domain']}", 'warn', detail)) + return checks + # ------------------------------------------------------------------ # # Sweep # ------------------------------------------------------------------ # @@ -718,6 +749,7 @@ class DoctorService: checks = [] checks += cls._drift_checks() checks += cls._service_checks() + checks += cls._unmanaged_site_checks() checks += cls._dns_checks() checks += cls._backup_proof_checks() checks.append(cls._cert_check()) diff --git a/backend/app/services/drift_service.py b/backend/app/services/drift_service.py index fdfdea8a..e051e0b8 100644 --- a/backend/app/services/drift_service.py +++ b/backend/app/services/drift_service.py @@ -342,7 +342,9 @@ def _nginx_list_resources(): .filter(Domain.deleted_at.is_(None)) .distinct() .all()) - return [(app.id, app.name) for app in rows] + # An adopted host site's vhost was not written by the panel, so there is + # no expected config to compare it with and nothing here may repair it. + return [(app.id, app.name) for app in rows if not app.is_host_managed] def _nginx_render_expected(app_id): diff --git a/backend/app/services/previews/plan.py b/backend/app/services/previews/plan.py index 83dd3835..caebc9fa 100644 --- a/backend/app/services/previews/plan.py +++ b/backend/app/services/previews/plan.py @@ -12,8 +12,8 @@ class PreviewError(ValueError): def validate(app, preview, settings, git_config): if app.server_id or settings.target_server_id: raise PreviewError('Generic previews currently require a local server.') - if app.compose_file or app.managed_by in ('docker_compose', 'systemd'): - raise PreviewError('Compose and systemd previews are not supported by this provisioner.') + if app.compose_file or app.managed_by in ('docker_compose', 'systemd', 'host'): + raise PreviewError('Compose, systemd and host-managed previews are not supported by this provisioner.') if app.ingress_plane not in (None, '', 'nginx'): raise PreviewError('Generic previews currently require nginx ingress.') if not app.port or not 1 <= app.port <= 65535: diff --git a/backend/app/services/site_adoption_service.py b/backend/app/services/site_adoption_service.py new file mode 100644 index 00000000..30eb997a --- /dev/null +++ b/backend/app/services/site_adoption_service.py @@ -0,0 +1,541 @@ +"""Adopt sites that already run on this host (issue #269). + +A site that was set up by hand, by a script or by a migration serves traffic +through host nginx but has no row in ``applications`` / ``domains`` / +``wordpress_sites``, so the panel cannot see it: no monitoring, backups, SSL +status or logs. The other entry points all *create* something — a vhost, a +copy of the files — which is the wrong thing to do to a site that is already +live. + +This module only ever READS the host: the live nginx config, the PHP-FPM +pools, the certificate files and ``wp-config.php``. Adopting writes database +rows and nothing else. The resulting application carries +``managed_by='host'``, which the vhost writer, the lifecycle and the delete +path all honour by leaving the running config alone +(``Application.is_host_managed``). + +``discover()`` doubles as the drift report: every site it returns without a +``linked_app`` is one serving traffic that the panel does not know about. +""" +import glob +import logging +import os +import re +from datetime import datetime + +from app import db +from app.models.application import Application +from app.models.domain import Domain +from app.services.nginx_service import NginxService +from app.utils.slug import app_name_clash_error, slugify + +logger = logging.getLogger(__name__) + +HOST_MANAGED = Application.MANAGED_BY_HOST + +# Where the distro keeps PHP-FPM pools: /etc/php//fpm/pool.d/*.conf. +# Globbed rather than iterated over a list of known versions, so a 7.4 or 8.4 +# pool is found too. +PHP_ETC_DIR = os.environ.get('PHP_ETC_DIR', '/etc/php') + +# Kinds of site a vhost can describe, and what each one adopts as. +KIND_PHP = 'php' +KIND_STATIC = 'static' +KIND_PROXY = 'proxy' +KIND_REDIRECT = 'redirect' +_ADOPTABLE_KINDS = (KIND_PHP, KIND_STATIC) + + +class SiteAdoptionError(Exception): + """Adoption refused. ``status`` is the HTTP status the API answers with.""" + + def __init__(self, message, status=400): + super().__init__(message) + self.status = status + + +# -------------------------------------------------------------------------- +# Reading nginx +# -------------------------------------------------------------------------- + +def _live_vhost_files(): + """Config files nginx is actually loading: ``sites-enabled/*`` (Debian + layout) and ``conf.d/*.conf`` (RHEL layout, and extras on Debian).""" + files = [] + enabled = NginxService.SITES_ENABLED + if os.path.isdir(enabled): + files.extend(sorted(glob.glob(os.path.join(enabled, '*')))) + conf_d = os.path.join(NginxService.NGINX_CONF_DIR, 'conf.d') + if os.path.isdir(conf_d): + files.extend(sorted(glob.glob(os.path.join(conf_d, '*.conf')))) + return [f for f in files if os.path.isfile(f)] + + +def _strip_comments(text): + return re.sub(r'(?m)#.*$', '', text) + + +def _server_blocks(text): + """The body of every ``server { ... }`` block, by brace matching.""" + blocks = [] + for match in re.finditer(r'(?:^|[\s;{}])server\s*\{', text): + depth, start = 1, match.end() + pos = start + while pos < len(text) and depth: + char = text[pos] + if char == '{': + depth += 1 + elif char == '}': + depth -= 1 + pos += 1 + if depth == 0: + blocks.append(text[start:pos - 1]) + return blocks + + +def _directive(body, name): + """Every value of directive ``name`` in ``body``, in order.""" + pattern = r'(?:^|[;{}])\s*' + re.escape(name) + r'\s+([^;{}]+);' + return [value.strip() for value in re.findall(pattern, body)] + + +def _first(values): + return values[0] if values else None + + +def _unquote(value): + return value.strip().strip('"\'') if value else value + + +def _parse_block(body): + names = [] + for value in _directive(body, 'server_name'): + for name in value.split(): + # `_` is the catch-all and `~...` a regex: neither is a domain. + if name != '_' and not name.startswith('~') and name not in names: + names.append(name) + listens = _directive(body, 'listen') + return { + 'domains': names, + 'root': _unquote(_first(_directive(body, 'root'))), + 'fastcgi_pass': _first(_directive(body, 'fastcgi_pass')), + 'proxy_pass': _first(_directive(body, 'proxy_pass')), + 'certificate': _unquote(_first(_directive(body, 'ssl_certificate'))), + 'certificate_key': _unquote(_first(_directive(body, 'ssl_certificate_key'))), + 'ssl': any('ssl' in value.split() or value.split()[0].endswith('443') + for value in listens if value.split()), + } + + +def _has_content(block): + return bool(block['root'] or block['fastcgi_pass'] or block['proxy_pass']) + + +def _related(domain_a, domain_b): + """`www.example.com` and `example.com` are the same site.""" + return domain_a == 'www.' + domain_b or domain_b == 'www.' + domain_a + + +def _merge(target, block): + for name in block['domains']: + if name not in target['domains']: + target['domains'].append(name) + for key in ('root', 'fastcgi_pass', 'proxy_pass', 'certificate', 'certificate_key'): + target[key] = target[key] or block[key] + target['ssl'] = target['ssl'] or block['ssl'] + + +def _group_blocks(blocks): + """One group per site. A port-80 redirect and its 443 twin share names and + merge; a content-less `www.` redirect folds into the site it points at.""" + groups = [] + for block in blocks: + if not block['domains']: + continue + home = next((g for g in groups if set(g['domains']) & set(block['domains'])), None) + if home is None: + groups.append(dict(block, domains=list(block['domains']))) + else: + _merge(home, block) + + sites = [g for g in groups if _has_content(g)] + for group in groups: + if _has_content(group): + continue + home = next((s for s in sites + if any(_related(a, b) for a in s['domains'] for b in group['domains'])), + None) + if home is not None: + _merge(home, group) + else: + sites.append(group) + return sites + + +# -------------------------------------------------------------------------- +# Reading PHP-FPM, certificates, WordPress +# -------------------------------------------------------------------------- + +def _fpm_pools(): + """Every PHP-FPM pool on the box: ``{version, pool, listen, file}``.""" + pools = [] + pattern = os.path.join(PHP_ETC_DIR, '*', 'fpm', 'pool.d', '*.conf') + for path in sorted(glob.glob(pattern)): + version = os.path.basename(os.path.dirname(os.path.dirname(os.path.dirname(path)))) + try: + with open(path, encoding='utf-8', errors='replace') as handle: + text = re.sub(r'(?m)^\s*[;#].*$', '', handle.read()) + except OSError: + continue + section = re.search(r'(?m)^\s*\[([^\]]+)\]', text) + listen = re.search(r'(?m)^\s*listen\s*=\s*(\S+)', text) + if listen: + pools.append({'version': version, + 'pool': section.group(1) if section else None, + 'listen': listen.group(1), 'file': path}) + return pools + + +def _php_for(fastcgi_pass, pools): + """Which PHP serves a ``fastcgi_pass`` target: matched against the pools' + ``listen``, falling back to the version in a conventional socket name.""" + target = fastcgi_pass.strip() + target = target[len('unix:'):] if target.startswith('unix:') else target + for pool in pools: + if pool['listen'] == target: + return {'version': pool['version'], 'pool': pool['pool'], + 'listen': pool['listen'], 'pool_file': pool['file']} + named = re.search(r'php-?(\d+\.\d+)', target) + return {'version': named.group(1) if named else None, 'pool': None, + 'listen': target, 'pool_file': None} + + +def _certificate_expiry(path): + try: + from cryptography import x509 + with open(path, 'rb') as handle: + cert = x509.load_pem_x509_certificate(handle.read()) + expires = getattr(cert, 'not_valid_after_utc', None) or cert.not_valid_after + return expires.replace(tzinfo=None) + except Exception: # unreadable, missing or not a PEM certificate + return None + + +_WP_DEFINE = r'''define\(\s*['"]{key}['"]\s*,\s*['"]([^'"]*)['"]''' + + +def _wordpress(root): + """What ``wp-config.php`` says about the site. The password is never read: + nothing here needs it, and a secret we do not hold cannot leak.""" + config = next((path for path in (os.path.join(root, 'wp-config.php'), + os.path.join(os.path.dirname(root.rstrip('/\\')), + 'wp-config.php')) + if os.path.isfile(path)), None) + if config is None: + return None + try: + with open(config, encoding='utf-8', errors='replace') as handle: + text = handle.read() + except OSError: + return {'config_file': config, 'readable': False} + + def define(key): + match = re.search(_WP_DEFINE.format(key=key), text) + return match.group(1) if match else None + + prefix = re.search(r'''\$table_prefix\s*=\s*['"]([^'"]+)['"]''', text) + version = None + try: + with open(os.path.join(root, 'wp-includes', 'version.php'), + encoding='utf-8', errors='replace') as handle: + found = re.search(r'''\$wp_version\s*=\s*['"]([^'"]+)['"]''', handle.read()) + version = found.group(1) if found else None + except OSError: + pass + return { + 'config_file': config, 'readable': True, 'version': version, + 'db_name': define('DB_NAME'), 'db_user': define('DB_USER'), + 'db_host': define('DB_HOST') or 'localhost', + 'table_prefix': prefix.group(1) if prefix else 'wp_', + 'multisite': bool(re.search(r'''define\(\s*['"]MULTISITE['"]\s*,\s*true''', text, re.I)), + } + + +# -------------------------------------------------------------------------- +# Discovery +# -------------------------------------------------------------------------- + +def _is_panel_vhost(path): + """ServerKit's own vhost and snippets are not sites to adopt.""" + return os.path.basename(path).lower().startswith('serverkit') + + +def _link_index(): + """Lookup tables for "is this site already an application?".""" + apps = Application.query_active().all() + by_id = {app.id: app for app in apps} + by_domain = {} + for domain in Domain.query_active().all(): + if domain.application_id in by_id: + by_domain[domain.name.lower()] = by_id[domain.application_id] + by_root = {os.path.normpath(app.root_path): app for app in apps + if app.root_path and not app.server_id} + by_name = {app.name: app for app in apps if not app.server_id} + return by_domain, by_root, by_name + + +def _linked_app(site, vhost_file, index): + by_domain, by_root, by_name = index + for domain in site['domains']: + if domain.lower() in by_domain: + return by_domain[domain.lower()] + if site['root'] and os.path.normpath(site['root']) in by_root: + return by_root[os.path.normpath(site['root'])] + # A vhost the panel wrote is named after its application. + stem = os.path.basename(vhost_file) + return by_name.get(stem) or by_name.get(stem[:-len('.conf')] if stem.endswith('.conf') else stem) + + +def _describe(site, vhost_file, pools, index, single): + primary = site['domains'][0] + stem = os.path.basename(vhost_file) + root = site['root'] + root_exists = bool(root and os.path.isdir(root)) + + if site['fastcgi_pass']: + kind = KIND_PHP + elif site['proxy_pass']: + kind = KIND_PROXY + elif root: + kind = KIND_STATIC + else: + kind = KIND_REDIRECT + + php = _php_for(site['fastcgi_pass'], pools) if kind == KIND_PHP else None + wordpress = _wordpress(root) if kind == KIND_PHP and root_exists else None + app_type = {KIND_PHP: 'wordpress' if wordpress else 'php', + KIND_STATIC: 'static'}.get(kind) + + port = None + if site['proxy_pass']: + found = re.search(r':(\d+)', site['proxy_pass'].split('//', 1)[-1]) + port = int(found.group(1)) if found else None + + certificate = site['certificate'] + expires = _certificate_expiry(certificate) if certificate else None + linked = _linked_app(site, vhost_file, index) + + reason = None + if linked is not None: + reason = f'Already managed as "{linked.name}".' + elif kind == KIND_PROXY: + reason = ('This vhost proxies to a running process. Register that process as a ' + 'service (Docker Compose or systemd) instead of adopting the vhost.') + elif kind == KIND_REDIRECT: + reason = 'This vhost only redirects; there is no site behind it to adopt.' + elif not root_exists: + reason = f'Document root does not exist: {root}' + + return { + 'id': stem if single else f'{stem}#{primary}', + 'vhost_file': os.path.realpath(vhost_file), + 'domains': list(site['domains']), + 'primary_domain': primary, + 'kind': kind, + 'app_type': app_type, + 'root': root, + 'root_exists': root_exists, + 'php': php, + 'upstream': site['proxy_pass'], + 'port': port, + 'ssl': { + 'enabled': bool(site['ssl'] and certificate), + 'certificate': certificate, + 'certificate_key': site['certificate_key'], + 'letsencrypt': bool(certificate and '/letsencrypt/' in certificate.replace('\\', '/')), + 'expires_at': expires.isoformat() if expires else None, + }, + 'wordpress': wordpress, + 'database': ({'engine': 'mysql', 'name': wordpress['db_name'], + 'user': wordpress.get('db_user'), 'host': wordpress.get('db_host')} + if wordpress and wordpress.get('db_name') else None), + 'linked_app': {'id': linked.id, 'name': linked.name} if linked is not None else None, + 'adoptable': reason is None and kind in _ADOPTABLE_KINDS, + 'reason': reason, + 'suggested_name': slugify(primary) or 'site', + } + + +def discover(): + """Every site host nginx is serving, with what backs it and whether the + panel already manages it. Read-only; an unreadable file is skipped.""" + pools = _fpm_pools() + index = _link_index() + sites = [] + for path in _live_vhost_files(): + if _is_panel_vhost(path): + continue + try: + with open(path, encoding='utf-8', errors='replace') as handle: + text = _strip_comments(handle.read()) + except OSError as exc: + logger.warning('site adoption: cannot read %s: %s', path, exc) + continue + groups = _group_blocks([_parse_block(body) for body in _server_blocks(text)]) + for group in groups: + sites.append(_describe(group, path, pools, index, single=len(groups) == 1)) + return sites + + +def unmanaged(): + """The drift list: sites serving traffic that no application accounts for.""" + return [site for site in discover() if site['linked_app'] is None] + + +def find(identifier): + """A discovered site by its id, vhost file name or any of its domains.""" + wanted = (identifier or '').strip().lower() + if not wanted: + return None + for site in discover(): + candidates = {site['id'].lower(), os.path.basename(site['vhost_file']).lower()} + candidates.update(domain.lower() for domain in site['domains']) + if wanted in candidates: + return site + return None + + +# -------------------------------------------------------------------------- +# Adopting +# -------------------------------------------------------------------------- + +def plan(site, name=None): + """What adopting ``site`` would record, and what it would leave alone. + Pure: this is the dry run, and `adopt` builds its rows from the same dict.""" + name = (name or site['suggested_name']).strip() + php = site['php'] or {} + wordpress = site['wordpress'] + return { + 'site': site['id'], + 'application': { + 'name': name, + 'app_type': site['app_type'], + 'managed_by': HOST_MANAGED, + 'source': 'manual', + 'root_path': site['root'], + 'php_version': php.get('version'), + }, + 'domains': [{ + 'name': domain, + 'is_primary': position == 0, + 'ssl_enabled': site['ssl']['enabled'], + 'ssl_certificate_path': site['ssl']['certificate'], + 'ssl_key_path': site['ssl']['certificate_key'], + 'ssl_expires_at': site['ssl']['expires_at'], + } for position, domain in enumerate(site['domains'])], + 'wordpress_site': ({ + 'wp_version': wordpress.get('version'), + 'multisite': bool(wordpress.get('multisite')), + 'db_name': wordpress.get('db_name'), + 'db_user': wordpress.get('db_user'), + 'db_host': wordpress.get('db_host'), + 'db_prefix': wordpress.get('table_prefix'), + } if wordpress and wordpress.get('readable') else None), + 'database': site['database'], + # Named so the operator can see exactly what stays as it is. + 'untouched': [path for path in (site['vhost_file'], php.get('pool_file'), + site['ssl']['certificate'], + (wordpress or {}).get('config_file')) if path], + } + + +def adopt(identifier, user, name=None, workspace_id=None): + """Register a running site as an application. Writes rows, never config. + + Returns ``(application, plan)``. Raises :class:`SiteAdoptionError` when the + site is unknown, already managed, or not something this flow adopts. + """ + site = find(identifier) + if site is None: + raise SiteAdoptionError( + f'No site served by host nginx matches "{identifier}".', status=404) + if not site['adoptable']: + raise SiteAdoptionError(site['reason'] or 'This site cannot be adopted.', status=409) + + todo = plan(site, name) + app_name = todo['application']['name'] + if not app_name or len(app_name) < 2: + raise SiteAdoptionError('Service name must be at least 2 characters.') + # Not query_active: a tombstone keeps its name reserved so a restore from + # the Recycle Bin can never collide with an app adopted in the meantime. + clash = app_name_clash_error(Application.query.filter_by(name=app_name).first(), app_name) + if clash: + raise SiteAdoptionError(clash, status=409) + + if workspace_id is None: + from app.services.workspace_service import WorkspaceService + workspace_id = WorkspaceService.ensure_default_workspace().id + + application = Application( + name=app_name, + app_type=todo['application']['app_type'], + # It is serving traffic right now; that is the whole premise. + status='running', + source='manual', + managed_by=HOST_MANAGED, + root_path=todo['application']['root_path'], + php_version=todo['application']['php_version'], + user_id=user.id, + workspace_id=workspace_id, + ) + db.session.add(application) + db.session.flush() + + for row in todo['domains']: + expires = row['ssl_expires_at'] + db.session.add(Domain( + name=row['name'], + is_primary=row['is_primary'], + ssl_enabled=row['ssl_enabled'], + ssl_certificate_path=row['ssl_certificate_path'], + ssl_key_path=row['ssl_key_path'], + ssl_expires_at=datetime.fromisoformat(expires) if expires else None, + application_id=application.id, + )) + + if todo['wordpress_site'] is not None: + from app.models.wordpress_site import WordPressSite + db.session.add(WordPressSite(application_id=application.id, **todo['wordpress_site'])) + + db.session.commit() + + if todo['database'] is not None: + _link_database(todo['database'], application) + + try: + from app.services.audit_service import AuditService + AuditService.log(action='app.adopt', user_id=user.id, target_type='application', + target_id=application.id, + details={'site': site['id'], 'domains': site['domains'], + 'vhost_file': site['vhost_file']}) + except Exception: # audit is best-effort and never blocks the adoption + logger.debug('site adoption: audit log failed', exc_info=True) + + return application, todo + + +def _link_database(database, application): + """Point the site's database at the application, so Databases stops + showing it as belonging to nothing. Best-effort: the site is adopted + either way.""" + try: + from app.services.managed_database_service import ManagedDatabaseService + host, _, port = (database.get('host') or 'localhost').partition(':') + ManagedDatabaseService.adopt( + database['engine'], host or 'localhost', database['name'], + port=int(port) if port.isdigit() else None, + owner_application_id=application.id, + workspace_id=application.workspace_id) + except Exception as exc: + logger.warning('site adoption: could not link database %s to %s: %s', + database.get('name'), application.name, exc) diff --git a/backend/app/services/site_domain_service.py b/backend/app/services/site_domain_service.py index a5d61abc..76281e64 100644 --- a/backend/app/services/site_domain_service.py +++ b/backend/app/services/site_domain_service.py @@ -538,6 +538,14 @@ class SiteDomainService: """ from app.models.domain import Domain + # An adopted host site already has a vhost someone else wrote, under a + # file name that is not the app's. Rendering one here would publish a + # second server block for the same names — or, through drift repair, + # replace the one that is serving traffic. + if app.is_host_managed: + return None, ('This site is host-managed: ServerKit records its domains ' + 'but does not rewrite its nginx config.') + # query_active, not query: Domain is soft-deleted now, so a plain query # returns tombstones and this renderer would write a deleted domain # straight back into server_name — the vhost would keep serving a domain diff --git a/backend/tests/test_site_adoption.py b/backend/tests/test_site_adoption.py new file mode 100644 index 00000000..f37d4c99 --- /dev/null +++ b/backend/tests/test_site_adoption.py @@ -0,0 +1,377 @@ +"""Adopting a site that already runs on the host (issue #269). + +The contract under test: discovery reads the live nginx / PHP-FPM / WordPress +config and describes each site; adopting writes database rows and NOTHING on +the host; and once adopted, no panel path rewrites or removes the config that +is serving the site. +""" +import hashlib +from unittest.mock import patch + +import pytest + +from factories import headers_for, make_user + +WP_CONFIG = """= 400 + assert 'host-managed' in resp.get_data(as_text=True) + assert adopted.status == 'running' + + +def test_deleting_an_adopted_site_forgets_it_but_keeps_it_serving(client, admin, adopted, host): + from app.models.application import Application + before = _snapshot(host['root']) + # Mocks, not raising stubs: the delete path catches exceptions per step, + # so a raise would be swallowed and this would pass with the guard removed. + with patch('app.services.nginx_service.NginxService.disable_site') as disable_site, \ + patch('app.services.nginx_service.NginxService.delete_site') as delete_site: + resp = client.delete(f'/api/v1/apps/{adopted.id}', headers=headers_for(admin)) + assert resp.status_code == 200, resp.get_json() + disable_site.assert_not_called() + delete_site.assert_not_called() + assert Application.query_active().filter_by(id=adopted.id).first() is None + assert _snapshot(host['root']) == before + + +def test_status_follows_nginx_and_never_guesses(app, adopted): + from app import db + from app.api.apps import _sync_manual_app_status + probe = 'app.services.process_service.ProcessService.get_systemd_unit_status' + with patch(probe, return_value={'success': True, 'status': 'inactive', 'active': False}): + _sync_manual_app_status(adopted) + assert adopted.status == 'stopped' + with patch(probe, return_value={'success': True, 'status': 'active', 'active': True}): + _sync_manual_app_status(adopted) + assert adopted.status == 'running' + # No systemd to ask (a dev box): keep what we knew. + with patch(probe, return_value={'success': True, 'status': 'unknown', 'active': False}): + _sync_manual_app_status(adopted) + assert adopted.status == 'running' + db.session.rollback() + + +def test_manual_route_accepts_host_for_sites_only(client, admin, host): + ok = client.post('/api/v1/apps/manual', headers=headers_for(admin), json={ + 'name': 'docs-manual', 'app_type': 'static', 'root_path': host['docs_root'], + 'managed_by': 'host'}) + assert ok.status_code == 201, ok.get_json() + assert ok.get_json()['app']['managed_by'] == 'host' + bad = client.post('/api/v1/apps/manual', headers=headers_for(admin), json={ + 'name': 'api-manual', 'app_type': 'docker', 'root_path': host['docs_root'], + 'managed_by': 'host'}) + assert bad.status_code == 400 + + +# ------------------------------------------------------------- drift report + +def test_doctor_reports_unmanaged_sites_until_they_are_adopted(client, host, admin): + from app.services.doctor_service import DoctorService + + def unmanaged(): + return {check['key']: check for check in DoctorService._unmanaged_site_checks()} + + checks = unmanaged() + assert set(checks) == {'sites.unmanaged.shop.example.com.conf', + 'sites.unmanaged.docs.example.com.conf', + 'sites.unmanaged.api.example.com.conf'} + shop = checks['sites.unmanaged.shop.example.com.conf'] + assert shop['status'] == 'warn' and not shop['repairable'] + assert 'serverkit adopt-site shop.example.com --apply' in shop['detail'] + # A proxied process is still reported, with why it is not adopted here. + assert 'Docker Compose or systemd' in checks['sites.unmanaged.api.example.com.conf']['detail'] + + client.post('/api/v1/site-adoption/adopt', + json={'site': 'shop.example.com', 'dry_run': False}, headers=headers_for(admin)) + assert 'sites.unmanaged.shop.example.com.conf' not in unmanaged() + + +def test_doctor_stays_quiet_on_a_host_with_no_stray_sites(app, tmp_path, monkeypatch): + from app.services.doctor_service import DoctorService + from app.services.nginx_service import NginxService + monkeypatch.setattr(NginxService, 'NGINX_CONF_DIR', str(tmp_path / 'absent')) + monkeypatch.setattr(NginxService, 'SITES_ENABLED', str(tmp_path / 'absent' / 'sites-enabled')) + assert DoctorService._unmanaged_site_checks() == [] From 933216e911a694e442832b4abcc0f977aed0b138 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sun, 22 Nov 2026 02:02:48 -0500 Subject: [PATCH 05/13] Add serverkit adopt-site Lists the sites host nginx serves, shows what adopting one would record, and registers it with --apply. list-sites now names a PHP-FPM site instead of calling it "port static". Part of #269. --- backend/cli.py | 116 +++++++++++++++++++++++++++ backend/tests/test_cli_adopt_site.py | 73 +++++++++++++++++ scripts/test/test_cli.sh | 18 ++++- serverkit | 18 +++-- 4 files changed, 217 insertions(+), 8 deletions(-) create mode 100644 backend/tests/test_cli_adopt_site.py diff --git a/backend/cli.py b/backend/cli.py index 99530a00..d0268db4 100644 --- a/backend/cli.py +++ b/backend/cli.py @@ -854,6 +854,122 @@ def _api_client(with_token=True): return ApiClient(token=token) +@cli.command('adopt-site') +@click.argument('site', required=False) +@click.option('--apply', 'apply_', is_flag=True, + help='Register the site. Without it, only show what would be recorded.') +@click.option('--name', default=None, help='Service name (default: derived from the domain)') +@click.option('--json', 'as_json', is_flag=True, help='Output machine-readable JSON') +def adopt_site(site, apply_, name, as_json): + """Register a site that already runs on this server. + + With no SITE, lists every site host nginx serves and whether ServerKit + manages it. With a SITE (a domain or a vhost file name), shows what + adopting it would record: a dry run. Add --apply to register it. + + Nothing on the server is rewritten either way: adopting records the + running nginx vhost, PHP-FPM pool, database and certificate as they are. + """ + from app.services import site_adoption_service + from app.services.site_adoption_service import SiteAdoptionError + + app = create_app() + with app.app_context(): + if not site: + if apply_: + _fail('--apply needs a site: serverkit adopt-site --apply') + sites = site_adoption_service.discover() + if as_json: + _echo_json({'sites': sites}) + return + if not sites: + click.echo('\n Host nginx is not serving any sites.\n') + return + click.echo(f"\n{'Domain':<34} {'Type':<10} {'PHP':<6} {'SSL':<4} {'State'}") + click.echo('-' * 90) + for found in sites: + if found['linked_app']: + state = f"managed as {found['linked_app']['name']}" + elif found['adoptable']: + state = 'not managed (adoptable)' + else: + state = f"not managed: {found['reason']}" + click.echo( + f"{found['primary_domain']:<34} " + f"{(found['app_type'] or found['kind']):<10} " + f"{((found['php'] or {}).get('version') or '-'):<6} " + f"{('yes' if found['ssl']['enabled'] else 'no'):<4} " + f"{state}" + ) + adoptable = sum(1 for found in sites if found['adoptable']) + click.echo(f"\n{adoptable} site(s) can be adopted: serverkit adopt-site \n") + return + + found = site_adoption_service.find(site) + if found is None: + _fail(f'No site served by host nginx matches "{site}". ' + "Run 'serverkit adopt-site' to list them.") + plan = site_adoption_service.plan(found, name) + + if not apply_: + if as_json: + _echo_json({'dry_run': True, 'adoptable': found['adoptable'], + 'reason': found['reason'], 'plan': plan}) + return + _print_adoption_plan(found, plan) + if found['adoptable']: + click.echo(f"\nDry run. Nothing was changed. To register it:\n" + f" serverkit adopt-site {site} --apply\n") + else: + click.echo(click.style(f"\nCannot adopt: {found['reason']}\n", fg='yellow')) + return + + owner = User.query.filter_by(role='admin', is_active=True).order_by(User.id).first() + if owner is None: + _fail("No active admin user to own the service. Run 'serverkit create-admin' first.") + try: + application, plan = site_adoption_service.adopt(site, owner, name=name) + except SiteAdoptionError as exc: + _fail(str(exc)) + if as_json: + _echo_json({'dry_run': False, 'plan': plan, 'app': application.to_dict()}) + return + _print_adoption_plan(found, plan) + click.echo(click.style( + f"\nAdopted as \"{application.name}\" (id {application.id}). " + 'No file on the server was changed.\n', fg='green')) + + +def _print_adoption_plan(site, plan): + php = site['php'] or {} + click.echo(f"\nSite: {site['primary_domain']}") + click.echo(f" vhost {site['vhost_file']}") + click.echo(f" domains {', '.join(site['domains'])}") + click.echo(f" root {site['root'] or '-'}") + if php: + pool = f" (pool {php['pool']})" if php.get('pool') else '' + click.echo(f" PHP-FPM {php.get('version') or 'unknown version'}{pool} at {php['listen']}") + if site['ssl']['enabled']: + expires = site['ssl']['expires_at'] or 'expiry unknown' + click.echo(f" certificate {site['ssl']['certificate']} ({expires})") + else: + click.echo(' certificate none') + if site['database']: + click.echo(f" database {site['database']['name']} on {site['database']['host']}") + click.echo('\nWould record:' if site['adoptable'] else '\nWould have recorded:') + application = plan['application'] + click.echo(f" service {application['name']} ({application['app_type']}, " + f"managed by {application['managed_by']})") + click.echo(f" domains {len(plan['domains'])}") + if plan['wordpress_site'] is not None: + click.echo(f" WordPress version {plan['wordpress_site']['wp_version'] or 'unknown'}") + if plan['database'] is not None: + click.echo(f" database linked to the service") + click.echo('\nLeft exactly as it is:') + for path in plan['untouched']: + click.echo(f" {path}") + + def _fail(message): click.echo(click.style(f'Error: {message}', fg='red'), err=True) sys.exit(1) diff --git a/backend/tests/test_cli_adopt_site.py b/backend/tests/test_cli_adopt_site.py new file mode 100644 index 00000000..c71d2cd6 --- /dev/null +++ b/backend/tests/test_cli_adopt_site.py @@ -0,0 +1,73 @@ +"""`serverkit adopt-site` — the CLI face of site adoption (issue #269). + +Dry run by default: naming a site prints what would be recorded and changes +nothing; only `--apply` registers it. The host fixture and the "nothing on +the host changed" snapshot come from test_site_adoption.py. +""" +import json + +import pytest +from click.testing import CliRunner + +from factories import make_user +from test_site_adoption import _snapshot, host # noqa: F401 (fixture) + + +@pytest.fixture +def run(app, monkeypatch): + """Invoke the Click command against the test app instead of a fresh one.""" + import cli + monkeypatch.setattr(cli, 'create_app', lambda *args, **kwargs: app) + + def invoke(*args): + return CliRunner().invoke(cli.cli, ['adopt-site', *args], catch_exceptions=False) + return invoke + + +def test_no_argument_lists_sites_with_their_state(run, host): # noqa: F811 + result = run() + assert result.exit_code == 0, result.output + assert 'shop.example.com' in result.output and 'wordpress' in result.output + assert 'not managed (adoptable)' in result.output + assert '2 site(s) can be adopted' in result.output + listed = json.loads(run('--json').output)['sites'] + assert {site['primary_domain'] for site in listed} == { + 'shop.example.com', 'docs.example.com', 'api.example.com'} + + +def test_naming_a_site_is_a_dry_run(run, host): # noqa: F811 + from app.models.application import Application + before = _snapshot(host['root']) + result = run('shop.example.com') + assert result.exit_code == 0, result.output + assert 'Dry run. Nothing was changed.' in result.output + assert 'serverkit adopt-site shop.example.com --apply' in result.output + assert 'Left exactly as it is:' in result.output + assert Application.query.filter_by(name='shop-example-com').first() is None + assert _snapshot(host['root']) == before + + +def test_apply_registers_the_site_and_leaves_the_host_alone(run, host, app): # noqa: F811 + from app import db + from app.models.application import Application + make_user(db, 'cli_adopt_admin', 'admin') + before = _snapshot(host['root']) + result = run('docs.example.com', '--apply', '--name', 'docs-site') + assert result.exit_code == 0, result.output + assert 'Adopted as "docs-site"' in result.output + row = Application.query_active().filter_by(name='docs-site').one() + assert (row.managed_by, row.app_type, row.status) == ('host', 'static', 'running') + assert _snapshot(host['root']) == before + + +def test_refusals_exit_non_zero_and_register_nothing(run, host, app): # noqa: F811 + from app import db + from app.models.application import Application + make_user(db, 'cli_adopt_admin2', 'admin') + count = Application.query.count() + assert run('nope.example.com').exit_code == 1 + # A proxied process is described, but --apply refuses it. + assert run('api.example.com').exit_code == 0 + assert run('api.example.com', '--apply').exit_code == 1 + assert run('--apply').exit_code == 1 + assert Application.query.count() == count diff --git a/scripts/test/test_cli.sh b/scripts/test/test_cli.sh index 80d999c3..78145af8 100644 --- a/scripts/test/test_cli.sh +++ b/scripts/test/test_cli.sh @@ -600,6 +600,15 @@ server { root /var/www/static; } EOF +cat > "$t/nginx/sites-enabled/php-site.conf" <<'EOF' +server { + server_name php.example.com; + root /var/www/php-site; + location ~ \.php$ { + fastcgi_pass unix:/run/php/php8.3-fpm.sock; + } +} +EOF cat > "$t/rhel/conf.d/confd.conf" <<'EOF' server { server_name confd.example.com; @@ -614,9 +623,11 @@ out2="$( set -Eeuo pipefail; NGINX_DIR="$t/rhel"; cmd_list_sites 2>&1 )" rc2=$? if [ "$rc" -eq 0 ] && [ "$rc2" -eq 0 ] \ && printf '%s' "$out" | grep 'proxied.example.com' | grep -q 'port 4100' \ - && printf '%s' "$out" | grep 'static.example.com' | grep -q 'port static' \ + && printf '%s' "$out" | grep 'static.example.com' | grep -q 'static files' \ + && printf '%s' "$out" | grep 'php.example.com' | grep -q 'php-fpm 8.3' \ + && ! printf '%s' "$out" | grep -q 'port static' \ && printf '%s' "$out2" | grep 'confd.example.com' | grep -q 'port 4200'; then - ok "list-sites extracts ports portably and lists conf.d layouts" + ok "list-sites extracts ports portably, names PHP-FPM sites, and lists conf.d layouts" else bad "list-sites broken: rc=$rc/$rc2 out=[$out] out2=[$out2]" fi @@ -725,7 +736,7 @@ fi t="$WORK/t18"; mkdir -p "$t/install" unknown="" for c in manifest services apps repair login-url support-bundle \ - db-migrate db-status db-history panel-status panel-doctor; do + db-migrate db-status db-history panel-status panel-doctor adopt-site; do out="$(SERVERKIT_DIR="$t/install" bash "$CLI" "$c" 2>&1)" || true if printf '%s' "$out" | grep -q 'Unknown command'; then unknown="$unknown $c" @@ -829,6 +840,7 @@ check_args 'services list --json' services list --json check_args 'status --json' panel-status --json check_args 'doctor --repair --yes' panel-doctor --repair --yes check_args 'connect status --json' connect status --json +check_args 'adopt-site example.com --apply --json' adopt-site example.com --apply --json if [ -z "$t20_fail" ]; then ok "executed-mode flag passthrough: wrapper commands reach cli.py verbatim" else diff --git a/serverkit b/serverkit index 723768e8..d81132e9 100644 --- a/serverkit +++ b/serverkit @@ -326,6 +326,7 @@ cmd_help() { echo "Site Management:" echo " setup-proxy Setup host nginx as reverse proxy (run once)" echo " add-site Add a new site/domain" + echo " adopt-site Register a site already running here (adopt-site [domain] [--apply])" echo " list-sites List all configured sites" echo " remove-site Remove a site" echo "" @@ -372,7 +373,7 @@ cmd_completion() { _serverkit() { local cur commands cur="${COMP_WORDS[COMP_CWORD]}" - commands="help start stop restart status logs update branch version check-update uninstall create-admin reset-password setup-code unlock-user list-users make-admin deactivate-user activate-user init-db migrate-db db-migrate db-status db-history backup-db restore-db disk cleanup-apps factory-reset generate-keys config setup-proxy create-app deploy-template list-servers deployment-status list-apps start-app stop-app app-logs add-site list-sites remove-site doctor manifest services apps repair login-url support-bundle connect panel-status panel-doctor completion" + commands="help start stop restart status logs update branch version check-update uninstall create-admin reset-password setup-code unlock-user list-users make-admin deactivate-user activate-user init-db migrate-db db-migrate db-status db-history backup-db restore-db disk cleanup-apps factory-reset generate-keys config setup-proxy create-app deploy-template list-servers deployment-status list-apps start-app stop-app app-logs add-site adopt-site list-sites remove-site doctor manifest services apps repair login-url support-bundle connect panel-status panel-doctor completion" if [ "$COMP_CWORD" -eq 1 ]; then COMPREPLY=( $(compgen -W "$commands" -- "$cur") ) @@ -392,6 +393,7 @@ _serverkit() { disk) COMPREPLY=( $(compgen -W "--safe --all --only --days --keep --older-than --dry-run --allow-restart --yes --json" -- "$cur") ) ;; cleanup-apps) COMPREPLY=( $(compgen -W "--delete-volumes --keep-db" -- "$cur") ) ;; list-apps) COMPREPLY=( $(compgen -W "--all --json" -- "$cur") ) ;; + adopt-site) COMPREPLY=( $(compgen -W "--apply --name --json" -- "$cur") ) ;; deployment-status) COMPREPLY=( $(compgen -W "--logs --json" -- "$cur") ) ;; db-migrate|migrate-db) COMPREPLY=( $(compgen -W "--no-backup" -- "$cur") ) ;; login-url) COMPREPLY=( $(compgen -W "--ttl --ip --user" -- "$cur") ) ;; @@ -1205,11 +1207,17 @@ cmd_list_sites() { DOMAIN=$(grep -m1 "server_name" "$site" | awk '{print $2}' | tr -d ';' || true) # Portable port extraction (GNU-only `grep -oP` broke busybox) PORT=$(grep -m1 "proxy_pass" "$site" | sed -n 's/.*:\([0-9][0-9]*\).*/\1/p' || true) - if [ -z "$PORT" ]; then - PORT="static" + if [ -n "$PORT" ]; then + TARGET="port $PORT" + elif grep -q "fastcgi_pass" "$site" 2>/dev/null; then + # A host PHP-FPM site has no port: name what serves it. + PHP_VER=$(grep -m1 "fastcgi_pass" "$site" | sed -n 's/.*php-\{0,1\}\([0-9][0-9]*\.[0-9][0-9]*\).*/\1/p' || true) + TARGET="php-fpm${PHP_VER:+ $PHP_VER}" + else + TARGET="static files" fi ENABLED="✓" - printf " %s %-35s → port %s\n" "$ENABLED" "$DOMAIN" "$PORT" + printf " %s %-35s → %s\n" "$ENABLED" "$DOMAIN" "$TARGET" fi done else @@ -1719,7 +1727,7 @@ case "${1:-help}" in migrate-db) cmd_migrate_db ;; - manifest|services|apps|repair|login-url|support-bundle|connect|db-migrate|db-status|db-history) + manifest|services|apps|repair|login-url|support-bundle|connect|db-migrate|db-status|db-history|adopt-site) cmd_panel_cli "$@" ;; panel-status) From 7bc25e54c3b1e6dd4846b0d1ca6c83662b39be78 Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sun, 22 Nov 2026 02:10:36 -0500 Subject: [PATCH 06/13] Offer unmanaged host sites on Services When this server's nginx serves sites no service accounts for, Services shows an Adopt button with the count; the dialog lists each site with what was detected and adopts it in one click. The button is absent on a host with nothing to adopt, so the top bar stays quiet. Host-managed rows drop the start/stop controls and the detail page names how they are run. Part of #269. --- .../src/components/apps/AdoptSitesDialog.jsx | 131 ++++++++++++++++++ frontend/src/i18n/locales/en.json | 25 ++++ frontend/src/pages/ServiceDetail.jsx | 10 +- frontend/src/pages/Services.jsx | 50 ++++++- frontend/src/services/api/index.js | 2 + frontend/src/services/api/siteAdoption.js | 15 ++ frontend/src/styles/pages/_services.scss | 63 +++++++++ 7 files changed, 292 insertions(+), 4 deletions(-) create mode 100644 frontend/src/components/apps/AdoptSitesDialog.jsx create mode 100644 frontend/src/services/api/siteAdoption.js diff --git a/frontend/src/components/apps/AdoptSitesDialog.jsx b/frontend/src/components/apps/AdoptSitesDialog.jsx new file mode 100644 index 00000000..717f7ed0 --- /dev/null +++ b/frontend/src/components/apps/AdoptSitesDialog.jsx @@ -0,0 +1,131 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import api from '@/services/api'; +import Modal from '@/components/Modal'; +import { Button } from '@/components/ui/button'; +import { Pill } from '@/components/ds'; +import { useToast } from '@/contexts/useToast.js'; +import { toastError } from '@/utils/errorMessage'; + +// Sites host nginx is serving that no service accounts for. Each row shows +// what discovery found; adopting records the site as it is. Nothing on the +// server is rewritten, which the dialog says in so many words because that is +// the question anyone with a live site asks first. +export default function AdoptSitesDialog({ open, onClose, sites, onAdopted }) { + const { t } = useTranslation(); + const toast = useToast(); + const [adopting, setAdopting] = useState(null); + + const kindLabel = (site) => ({ + wordpress: t('app.services.adopt.kindWordpress', 'WordPress'), + php: t('app.services.adopt.kindPhp', 'PHP'), + static: t('app.services.adopt.kindStatic', 'Static'), + }[site.app_type] || (site.kind === 'proxy' + ? t('app.services.adopt.kindProxy', 'Proxied app') + : t('app.services.adopt.kindRedirect', 'Redirect'))); + + async function handleAdopt(site) { + setAdopting(site.id); + try { + const result = await api.adoptHostSite(site.id, { apply: true }); + toast.success(t('app.services.adopt.adopted', { + name: result?.app?.name || site.primary_domain, + defaultValue: '{{name}} is now managed. Nothing on the server was changed.', + })); + await onAdopted?.(result?.app); + } catch (err) { + toastError(toast, t('app.services.adopt.failed', "Couldn't adopt this site."), err); + } finally { + setAdopting(null); + } + } + + return ( + + {t('common.actions.close', 'Close')} + + )} + > +

+ {t('app.services.adopt.intro', 'These sites are served by this server but are not managed here yet, so they have no monitoring, backups or SSL status. Adopting one records it as it is: the nginx config, PHP-FPM pool, database and certificate are left exactly as they are.')} +

+ +
    + {sites.map((site) => ( +
  • +
    +
    + {site.primary_domain} + {kindLabel(site)} +
    +
    + {site.domains.length > 1 && ( + <> +
    {t('app.services.adopt.alsoServes', 'Also serves')}
    +
    {site.domains.slice(1).join(', ')}
    + + )} + {site.root && ( + <> +
    {t('app.services.adopt.root', 'Document root')}
    +
    {site.root}
    + + )} + {site.php && ( + <> +
    {t('app.services.adopt.php', 'PHP-FPM')}
    +
    + {site.php.version || t('app.services.adopt.unknownVersion', 'Unknown version')} + {site.php.pool ? ` · ${site.php.pool}` : ''} +
    + + )} + {site.upstream && ( + <> +
    {t('app.services.adopt.upstream', 'Proxies to')}
    +
    {site.upstream}
    + + )} + {site.database && ( + <> +
    {t('app.services.adopt.database', 'Database')}
    +
    {site.database.name}
    + + )} +
    {t('app.services.adopt.certificate', 'Certificate')}
    +
    + {site.ssl.enabled + ? site.ssl.certificate + : t('app.services.adopt.noCertificate', 'None')} +
    +
    {t('app.services.adopt.vhost', 'nginx config')}
    +
    {site.vhost_file}
    +
    + {!site.adoptable && site.reason && ( +

    {site.reason}

    + )} +
    + {site.adoptable && ( + + )} +
  • + ))} +
+
+ ); +} diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json index d085560d..7d5e3e2b 100644 --- a/frontend/src/i18n/locales/en.json +++ b/frontend/src/i18n/locales/en.json @@ -6005,6 +6005,7 @@ "failedToLoadVersions": "Couldn't load versions.", "failedToRollback": "Couldn't roll back.", "failedToUploadNewVersion": "Couldn't upload the new version.", + "hostManaged": "Host nginx", "loadingService": "Loading service", "loadingVersions": "Loading versions…", "localService": "Local service", @@ -6051,6 +6052,30 @@ "wordpress": "WordPress" }, "services": { + "adopt": { + "action": "Adopt", + "adopted": "{{name}} is now managed. Nothing on the server was changed.", + "adopting": "Adopting…", + "alsoServes": "Also serves", + "button": "Adopt ({{count}})", + "buttonTitle": "Sites running on this server that are not managed here yet", + "certificate": "Certificate", + "database": "Database", + "failed": "Couldn't adopt this site.", + "intro": "These sites are served by this server but are not managed here yet, so they have no monitoring, backups or SSL status. Adopting one records it as it is: the nginx config, PHP-FPM pool, database and certificate are left exactly as they are.", + "kindPhp": "PHP", + "kindProxy": "Proxied app", + "kindRedirect": "Redirect", + "kindStatic": "Static", + "kindWordpress": "WordPress", + "noCertificate": "None", + "php": "PHP-FPM", + "root": "Document root", + "title": "Adopt existing sites", + "unknownVersion": "Unknown version", + "upstream": "Proxies to", + "vhost": "nginx config" + }, "assignSelected_one": "Assign 1 selected service to a project and environment, or leave it unassigned.", "assignSelected_other": "Assign {{count}} selected services to a project and environment, or leave them unassigned.", "bulkRestartSent_one": "Restart sent to 1 service", diff --git a/frontend/src/pages/ServiceDetail.jsx b/frontend/src/pages/ServiceDetail.jsx index 2d5954d8..21b6cd90 100644 --- a/frontend/src/pages/ServiceDetail.jsx +++ b/frontend/src/pages/ServiceDetail.jsx @@ -476,7 +476,7 @@ const ServiceDetail = () => { {service.managed_by && ( <> → - {service.managed_by === 'docker_compose' ? t('app.serviceDetail.dockerCompose', 'Docker Compose') : 'systemd'} + {managedByLabel(service.managed_by, t)} )} @@ -585,6 +585,14 @@ const ServiceDetail = () => { ); }; +// How a locally registered service is run. `host` is a site that was already +// being served by this server's nginx when it was adopted. +function managedByLabel(managedBy, t) { + if (managedBy === 'docker_compose') return t('app.serviceDetail.dockerCompose', 'Docker Compose'); + if (managedBy === 'host') return t('app.serviceDetail.hostManaged', 'Host nginx'); + return 'systemd'; +} + function extractRepoDisplay(url) { if (!url) return ''; try { diff --git a/frontend/src/pages/Services.jsx b/frontend/src/pages/Services.jsx index 03a185c4..ce4c7e29 100644 --- a/frontend/src/pages/Services.jsx +++ b/frontend/src/pages/Services.jsx @@ -1,6 +1,6 @@ import { useCallback, useState, useEffect, useMemo } from 'react'; import { useNavigate, Link } from 'react-router-dom'; -import { Layers, Plus, Square, Play, RotateCw, GitBranch, FolderOpen, FileArchive, FolderKanban, ArrowDownToLine } from 'lucide-react'; +import { Layers, Plus, Square, Play, RotateCw, GitBranch, FolderOpen, FileArchive, FolderKanban, ArrowDownToLine, ScanSearch } from 'lucide-react'; import { SiGithub as Github } from 'react-icons/si'; import api from '../services/api'; import { useToast } from '../contexts/useToast.js'; @@ -23,6 +23,8 @@ import { } from '@/components/ui/select'; import Modal from '@/components/Modal'; import RequiresDocker from '../components/RequiresDocker'; +import AdoptSitesDialog from '@/components/apps/AdoptSitesDialog'; +import { useAuth } from '@/contexts/useAuth.js'; import { useTranslation } from 'react-i18next'; import { toastError } from '@/utils/errorMessage'; import { translateLabel } from '@/i18n/labels'; @@ -120,6 +122,22 @@ const Services = () => { const [bulkLoading, setBulkLoading] = useState(false); const [showMoveDialog, setShowMoveDialog] = useState(false); const [bandwidth, setBandwidth] = useState({}); + const { isAdmin } = useAuth(); + // Sites this server's nginx is serving that no service accounts for. + const [unmanagedSites, setUnmanagedSites] = useState([]); + const [showAdoptDialog, setShowAdoptDialog] = useState(false); + + // Best-effort and admin-only (the endpoint reads host config): a failure + // just means the Adopt button does not appear. + const loadUnmanagedSites = useCallback(async () => { + if (!isAdmin) return; + try { + const data = await api.getHostSites(); + setUnmanagedSites((data?.sites || []).filter((site) => !site.linked_app && site.kind !== 'redirect')); + } catch { + setUnmanagedSites([]); + } + }, [isAdmin]); const loadApps = useCallback(async () => { try { @@ -141,6 +159,10 @@ const Services = () => { .catch(() => {}); }, [loadApps]); + useEffect(() => { + loadUnmanagedSites(); + }, [loadUnmanagedSites]); + async function handleAction(e, appId, action) { e.stopPropagation(); @@ -203,6 +225,17 @@ const Services = () => { useTopbarActions(() => <> + {unmanagedSites.length > 0 && ( + + )}