Merge pull request #270 from jhd3197/claude/serverkit-work-tree-issues-33a9d1

Adopt existing host sites and close four authz gaps
This commit is contained in:
Juan Denis authored and GitHub committed 2026-11-26 02:30:59 -05:00
commit 1e733d0bf8
51 files changed
+2593 -106

No files matched your search

+12
View File
@@ -614,6 +614,18 @@ Spin up and manage cloud servers directly from the panel.
Current focus areas on the `dev` branch. Core work centers on the deploy experience and
platform infrastructure; new capability areas ship as Marketplace extensions.
## Adopting Existing Sites (implemented)
Issue #269 — a site already running on the host was invisible to the panel.
- [x] Discover the sites host nginx serves: vhost, document root, PHP-FPM pool and version, WordPress database, certificate.
- [x] Adopt a site in place (`serverkit adopt-site`, the Services page, `POST /apps/host-sites/adopt`), dry run by default, writing rows and never config.
- [x] `managed_by = host`: the vhost writer, drift repair, lifecycle and delete paths leave a host-managed site's running config alone.
- [x] Report unmanaged sites in the doctor and on Services.
- [x] Document the hand-migration path that ends in adoption (`docs/COEXISTENCE.md`).
- [ ] Adopt a proxied process together with its vhost.
- [ ] Report PHP-FPM pools and databases that no service uses.
## AI Assistant: Prompture Provider Connections (implemented)
Community request: D3M4L, September 1, 2026 — connect the assistant to OmniRoute.
+27 -3
View File
@@ -11,6 +11,7 @@ from sqlalchemy.orm import joinedload
from app import db
from app.api._query import apply_query, QueryParseError
from app.models import Application, User
from app.models.application import is_host_managed
from app.utils.slug import app_name_clash_error, slugify
from app.services.build_service import BuildService
from app.services.docker_service import DockerService
@@ -85,6 +86,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 is_host_managed(app):
# 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
@@ -923,6 +931,11 @@ _HOST_BINDING_FIELDS = ('root_path', 'compose_file', 'systemd_unit', 'managed_by
@jwt_required()
def create_app():
user = get_current_user()
# Creating a service is a write. A read-only (viewer) account owning an
# app would hold write access to it — and to everything an owner can
# configure (GHSA-vrwv-j8w5-p94q).
if not user.is_developer:
raise PermissionDeniedError('Your role is read-only and cannot create services')
current_user_id = user.id
data = json_object()
@@ -1029,8 +1042,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'):
raise ValidationError("managed_by 'host' is for php, static and wordpress sites "
'served by host nginx')
if managed_by == 'docker_compose' and not compose_file:
if not os.path.exists(os.path.join(root_path, 'docker-compose.yml')):
@@ -2218,7 +2235,10 @@ def update_app_backup_policy(app_id):
app = require_app(app_id, write=True)
policy = BackupPolicyService.get_or_create_policy('application', app_id)
try:
BackupPolicyService.update_policy(policy, json_object())
# Write access to the app is not host access: only an admin may set
# the hooks, which run as shell commands on the panel host.
BackupPolicyService.update_policy(
policy, json_object(), allow_host_commands=get_current_user().is_admin)
except BackupPolicyError as e:
return jsonify({'error': str(e)}), 400
return jsonify(BackupPolicyService.serialize_policy_view(policy))
@@ -2396,3 +2416,7 @@ def delete_app_db_snapshot(app_id, snapshot_id):
db.session.delete(snapshot)
db.session.commit()
return jsonify({'success': True, 'message': 'Snapshot deleted'}), 200
# Area modules register their routes on apps_bp when imported.
from app.api import apps_adoption # noqa: E402,F401
+58
View File
@@ -0,0 +1,58 @@
"""Site adoption routes — register sites that already run on this host.
An area module of the apps blueprint: importing it registers the routes on
``apps_bp`` (see the bottom of app/api/apps.py), so they live under
/api/v1/apps/host-sites. 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 jsonify, request
from app.api._request import json_object
from app.api.apps import apps_bp
from app.exceptions import field_required
from app.middleware.rbac import admin_required, get_current_user
from app.services import site_adoption_service
@apps_bp.route('/host-sites', methods=['GET'])
@admin_required
def list_host_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
@apps_bp.route('/host-sites/adopt', methods=['POST'])
@admin_required
def adopt_host_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:
raise field_required('site')
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:
raise site_adoption_service.unknown_site(identifier)
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'))
application, plan = site_adoption_service.adopt(
identifier, user, name=name, workspace_id=workspace_id)
return jsonify({'message': 'Site adopted', 'dry_run': False, 'plan': plan,
'app': application.to_dict()}), 201
+2 -1
View File
@@ -205,7 +205,8 @@ def update_target_policy(target_type, target_id):
try:
BackupPolicyService.validate_target_type(target_type)
policy = BackupPolicyService.get_or_create_policy(target_type, target_id, subtype, meta)
BackupPolicyService.update_policy(policy, data)
# Admin-only route: an admin may set the policy's backup hooks.
BackupPolicyService.update_policy(policy, data, allow_host_commands=True)
except BackupPolicyError as e:
return jsonify({'error': str(e)}), 400
return jsonify(BackupPolicyService.serialize_policy_view(policy)), 200
+3 -1
View File
@@ -879,7 +879,9 @@ def protect_managed_database(managed_id):
if not managed:
raise not_found('database')
data = json_object()
policy = ManagedDatabaseService.protect(managed, fields=data.get('policy'))
# Admin-only route: an admin may set the policy's backup hooks.
policy = ManagedDatabaseService.protect(managed, fields=data.get('policy'),
allow_host_commands=True)
return jsonify({'policy': policy.to_dict()}), 201
+16 -8
View File
@@ -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/<alert_id>/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 ====================
+8 -5
View File
@@ -4,9 +4,14 @@ 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__)
# How many servers the offline cache carries.
OFFLINE_CACHE_SERVERS = 50
@mobile_bp.route('/push/register', methods=['POST'])
@jwt_required()
@@ -97,10 +102,10 @@ def get_mobile_summary():
except Exception:
metrics = {}
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 = len(WorkspaceService.accessible_servers(get_current_user()))
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
@@ -120,9 +125,7 @@ def get_mobile_summary():
@jwt_required()
def get_offline_data():
"""Get data for offline caching."""
from app.models.server import Server
servers = Server.query.limit(50).all()
servers = WorkspaceService.accessible_servers(get_current_user())[:OFFLINE_CACHE_SERVERS]
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(),
+11 -3
View File
@@ -24,23 +24,31 @@ def _require_server(server_id):
"""Return (server, None) or (None, error_response_tuple)."""
from app.middleware.rbac import get_current_user
from app.services.workspace_service import WorkspaceService
server = WorkspaceService.get_accessible_server(get_current_user(), server_id)
user = get_current_user()
server = WorkspaceService.get_accessible_server(user, server_id)
if not server:
return None, (jsonify({'error': 'Server not found'}), 404)
# Same rule as servers._get_operable_server: a workspace `viewer` member
# reads the proxy state but may not change it.
if (request.method not in ('GET', 'HEAD', 'OPTIONS') and server.workspace_id
and not WorkspaceService.can_write_in_workspace(user, server.workspace_id)):
from app.exceptions import PermissionDeniedError
raise PermissionDeniedError('You have read-only access to this workspace')
return server, None
@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 ``<server_id>``
converter on ``/<server_id>/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('/<server_id>/proxy', methods=['GET'])
+34 -6
View File
@@ -90,16 +90,43 @@ def _agent_failure_status(result):
return {'AGENT_OFFLINE': 503, 'PERMISSION_DENIED': 403}.get(result.get('code'), 500)
_READ_METHODS = ('GET', 'HEAD', 'OPTIONS')
def _get_operable_server(server_id):
"""The server, if the current user may operate it; 404 otherwise, so a
non-member can't tell a foreign workspace's server from a missing one."""
non-member can't tell a foreign workspace's server from a missing one.
On a mutating request the caller must also be able to WRITE in the
server's workspace: a member whose workspace role is `viewer` reads its
servers but may not change them, whatever their global role
(GHSA-m72h-hc66-5jwx). Checked here, at the one door every server route
goes through, so a new mutating route cannot forget it."""
from app.services.workspace_service import WorkspaceService
server = WorkspaceService.get_accessible_server(get_current_user(), server_id)
user = get_current_user()
server = WorkspaceService.get_accessible_server(user, server_id)
if server is None:
raise not_found('server')
if (request.method not in _READ_METHODS and server.workspace_id
and not WorkspaceService.can_write_in_workspace(user, server.workspace_id)):
raise PermissionDeniedError('You have read-only access to this workspace')
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 +244,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 +281,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/<group_id>', methods=['PUT'])
@@ -1300,7 +1328,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)
+64
View File
@@ -168,6 +168,64 @@ def _check_resource_write(resource_type, resource_id):
return _bad('access denied', 403)
def _check_resource_read(resource_type, resource_id):
"""Authorize reading the variables resolved FOR a target resource.
The read-side twin of ``_check_resource_write``, and it fails closed the
same way: the resolved set is the target's effective configuration, so the
caller must be able to read the target itself. Returns None when allowed,
else a ``(response, status)`` tuple.
"""
user = get_current_user()
if user is None:
return _bad('authentication required', 401)
if user.is_admin:
return None
if resource_type in ('application', 'wordpress'):
application = _resolve_app(resource_type, resource_id)
if application is None:
return _bad('resource not found', 404)
if not ResourceGrantService.can_access_app(user, application):
return _bad('access denied', 403)
return None
if resource_type == 'database':
from app.services.managed_database_service import ManagedDatabaseService
try:
row = ManagedDatabaseService.get(int(resource_id))
except (TypeError, ValueError):
row = None
if row is None:
return _bad('resource not found', 404)
if row.workspace_id is None:
return _bad('access denied', 403)
return require_workspace_access(row.workspace_id, user)
if resource_type == 'server':
from app.services.workspace_service import WorkspaceService
if WorkspaceService.get_accessible_server(user, str(resource_id)) is None:
return _bad('resource not found', 404)
return None
return _bad('access denied', 403)
def _check_scope_context(context):
"""Authorize every scope a hierarchical resolve was asked to layer in.
The scope ids arrive as query parameters, so without this any caller could
name another workspace's id and read its variable groups
(GHSA-893r-j92f-5q9x).
"""
for scope_type, key in ((SharedVariableGroup.SCOPE_WORKSPACE, 'workspace_id'),
(SharedVariableGroup.SCOPE_PROJECT, 'project_id'),
(SharedVariableGroup.SCOPE_ENVIRONMENT, 'environment_id')):
scope_id = context.get(key)
if scope_id in (None, ''):
continue
denied = _check_scope(scope_type, scope_id)
if denied:
return denied
return None
# ---------------------------------------------------------------- metadata
@shared_resources_bp.route('/resource-types', methods=['GET'])
@@ -439,6 +497,9 @@ def resolved():
resource_id = request.args.get('resource_id')
if not resource_type or resource_id in (None, ''):
return _bad('resource_type and resource_id are required')
denied = _check_resource_read(resource_type, resource_id)
if denied:
return denied
variables = SharedResourceService.resolve_variables(
resource_type, resource_id, mask_secrets=True
@@ -477,6 +538,9 @@ def resolved_hierarchical():
'project_id': request.args.get('project_id'),
'environment_id': request.args.get('environment_id'),
}
denied = _check_resource_read(resource_type, resource_id) or _check_scope_context(context)
if denied:
return denied
variables = SharedResourceService.resolve_hierarchical(
resource_type, resource_id, context=context, mask_secrets=True
)
+25 -1
View File
@@ -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,19 @@ 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 (through
:func:`is_host_managed`, which also accepts a stand-in object)."""
return is_host_managed(self)
@property
def live_domains(self):
"""The domains this app actually serves — tombstones excluded.
@@ -350,3 +363,14 @@ def _clear_cron_association(mapper, connection, target):
CronService.clear_application(target.id)
except Exception: # noqa: BLE001 - cleanup must not block app deletion
pass
def is_host_managed(app):
"""Whether ``app`` is an adopted host site (``managed_by == 'host'``).
A function rather than only the property so the services that guard on
it can be handed any app-shaped object: a plain attribute comparison
answers False for one that has no ``managed_by``, where reading a
property off a stand-in would raise or, on a mock, read as true.
"""
return getattr(app, 'managed_by', None) == Application.MANAGED_BY_HOST
@@ -140,8 +140,21 @@ 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."""
from app.models.application import is_host_managed
if is_host_managed(app):
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 +210,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 +248,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:
+13 -6
View File
@@ -28,6 +28,7 @@ import shutil
from app import db
from app.models import Application
from app.models.application import is_host_managed
from app.services.cron_service import CronService
logger = logging.getLogger(__name__)
@@ -206,12 +207,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 is_host_managed(app):
# 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)}
+19 -2
View File
@@ -132,10 +132,27 @@ class BackupPolicyService:
'pre_backup_hook', 'post_backup_hook',
)
# A hook is a shell command the panel runs as its own user on every backup:
# setting one is host command execution, whatever the target belongs to.
_HOST_COMMAND_FIELDS = ('pre_backup_hook', 'post_backup_hook')
@classmethod
def update_policy(cls, policy, fields):
"""Apply a partial update, persist, and re-sync the ScheduledJob."""
def update_policy(cls, policy, fields, *, allow_host_commands=False):
"""Apply a partial update, persist, and re-sync the ScheduledJob.
Changing a hook is refused unless the caller says the actor is an admin
(``allow_host_commands``) — default-deny, so a new caller that forwards
request data cannot hand shell access to whoever may edit the target
(GHSA-vrwv-j8w5-p94q). Sending a hook back unchanged is not a change,
so a policy read by a non-admin still round-trips.
"""
clean = {k: v for k, v in (fields or {}).items() if k in cls._MUTABLE}
if not allow_host_commands:
changed = [key for key in cls._HOST_COMMAND_FIELDS
if key in clean and (clean[key] or None) != (getattr(policy, key) or None)]
if changed:
from app.exceptions import PermissionDeniedError
raise PermissionDeniedError('Only an admin can set backup hooks')
cls.validate_fields(clean)
for key, value in clean.items():
if key in ('retention_count', 'retention_days', 'full_every_n_days') and value is not None:
+32
View File
@@ -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())
+4 -1
View File
@@ -342,7 +342,10 @@ def _nginx_list_resources():
.filter(Domain.deleted_at.is_(None))
.distinct()
.all())
return [(app.id, app.name) for app in rows]
from app.models.application import is_host_managed
# 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 is_host_managed(app)]
def _nginx_render_expected(app_id):
+62 -21
View File
@@ -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
@@ -170,7 +170,7 @@ class ManagedDatabaseService:
}
@classmethod
def protect(cls, managed, fields=None):
def protect(cls, managed, fields=None, allow_host_commands=False):
"""Create/refresh a BackupPolicy for this managed DB with a **real FK**
(``target_id = managed.id``) plus a ``managed`` marker so the executor
resolves the descriptor from the row (not a free-floating JSON blob)."""
@@ -184,7 +184,8 @@ class ManagedDatabaseService:
'host': managed.host},
)
if fields:
policy = BackupPolicyService.update_policy(policy, fields)
policy = BackupPolicyService.update_policy(
policy, fields, allow_host_commands=allow_host_commands)
return policy
@staticmethod
+2 -2
View File
@@ -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:
+6 -4
View File
@@ -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 []
+21 -11
View File
@@ -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()
@@ -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.exceptions import ConflictError, NotFoundError, ValidationError
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/<version>/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 = '/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)
# --------------------------------------------------------------------------
# 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 unknown_site(identifier):
"""The error for a site name that matches nothing nginx serves."""
return NotFoundError(f'No site served by host nginx matches "{identifier}".',
code='not_found.host_site')
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 a typed application error when the
site is unknown (404), already managed or not something this flow adopts
(409), or the name is unusable (400).
"""
site = find(identifier)
if site is None:
raise unknown_site(identifier)
if not site['adoptable']:
raise ConflictError(site['reason'] or 'This site cannot be adopted.',
code='host_site.not_adoptable')
todo = plan(site, name)
app_name = todo['application']['name']
if not app_name or len(app_name) < 2:
raise ValidationError('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 ConflictError(clash, code='host_site.name_taken')
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)
@@ -536,8 +536,17 @@ class SiteDomainService:
domains (nothing to publish), ``(None, reason)`` when it can't be
published via host nginx.
"""
from app.models.application import is_host_managed
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 is_host_managed(app):
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
+116
View File
@@ -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.exceptions import ApplicationError
from app.services import site_adoption_service
app = create_app()
with app.app_context():
if not site:
if apply_:
_fail('--apply needs a site: serverkit adopt-site <domain> --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 <domain>\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 ApplicationError 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)
@@ -3,7 +3,7 @@
"policy": "Exact reviewed inventory of direct persistence, subprocess, and filesystem mutation calls in Flask API controllers. New calls are forbidden; remove entries as controllers delegate to services.",
"counts": {
"filesystem": 8,
"persistence": 445
"persistence": 443
},
"owners": {
"api/admin.py": {
@@ -501,8 +501,6 @@
"api/manifests.py::reset_bootstrap::persistence::db.session.commit()::1",
"api/manifests.py::scaffold_manifest::persistence::Application.query_active().filter_by(id=app_id).first()::1",
"api/mobile.py::get_mobile_summary::persistence::SecurityAlert.query.filter_by(resolved=False).count()::1",
"api/mobile.py::get_mobile_summary::persistence::Server.query.count()::1",
"api/mobile.py::get_offline_data::persistence::Server.query.limit(50).all()::1",
"api/mobile.py::register_push::persistence::User.query.get(user_id)::1",
"api/mobile.py::register_push::persistence::db.session.commit()::1",
"api/notifications.py::get_user_preferences::persistence::User.query.get(current_user_id)::1",
+70
View File
@@ -0,0 +1,70 @@
"""GHSA-vrwv-j8w5-p94q: a viewer created an app, then set a backup hook the
panel runs as a shell command on its own host.
Each refusal has its control: the fix must not lock out the people who are
supposed to be able to do the thing.
"""
import pytest
from factories import headers_for, make_user
def _create(client, user, name):
return client.post('/api/v1/apps', json={'name': name, 'app_type': 'static'},
headers=headers_for(user))
def test_viewer_cannot_create_a_service(client, app):
from app import db
from app.models.application import Application
viewer = make_user(db, 'vrwv_viewer', 'viewer')
assert _create(client, viewer, 'vrwv-viewer-app').status_code == 403
assert Application.query.filter_by(name='vrwv-viewer-app').first() is None
developer = make_user(db, 'vrwv_dev', 'developer')
assert _create(client, developer, 'vrwv-dev-app').status_code == 201
def test_only_an_admin_can_set_a_backup_hook(client, app):
from app import db
from app.models.backup_policy import BackupPolicy
developer = make_user(db, 'vrwv_owner', 'developer')
admin = make_user(db, 'vrwv_admin', 'admin')
app_id = _create(client, developer, 'vrwv-owned').get_json()['app']['id']
url = f'/api/v1/apps/{app_id}/backup-policy'
def policy():
return BackupPolicy.query.filter_by(target_type='application', target_id=app_id).one()
for field in ('pre_backup_hook', 'post_backup_hook'):
resp = client.put(url, json={field: 'id > /tmp/pwned'}, headers=headers_for(developer))
assert resp.status_code == 403, field
assert getattr(policy(), field) in (None, '')
# The owner still manages the rest of the policy...
resp = client.put(url, json={'retention_count': 9}, headers=headers_for(developer))
assert resp.status_code == 200 and policy().retention_count == 9
# ...an admin sets the hook...
resp = client.put(url, json={'pre_backup_hook': 'echo ok'}, headers=headers_for(admin))
assert resp.status_code == 200 and policy().pre_backup_hook == 'echo ok'
# ...and the owner can send the policy back unchanged (a round trip of what
# GET returned) without that counting as setting a hook, but not alter it.
resp = client.put(url, json={'pre_backup_hook': 'echo ok', 'retention_count': 4},
headers=headers_for(developer))
assert resp.status_code == 200 and policy().retention_count == 4
resp = client.put(url, json={'pre_backup_hook': 'echo changed'},
headers=headers_for(developer))
assert resp.status_code == 403 and policy().pre_backup_hook == 'echo ok'
resp = client.put(url, json={'pre_backup_hook': ''}, headers=headers_for(developer))
assert resp.status_code == 403 and policy().pre_backup_hook == 'echo ok'
def test_hook_changes_are_denied_by_default_in_the_service(app):
"""A new caller that forwards request data gets the refusal, not a shell."""
from app.exceptions import PermissionDeniedError
from app.services.backup_policy_service import BackupPolicyService
policy = BackupPolicyService.get_or_create_policy('application', 987654)
with pytest.raises(PermissionDeniedError):
BackupPolicyService.update_policy(policy, {'post_backup_hook': 'id'})
assert policy.post_backup_hook in (None, '')
+73
View File
@@ -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
+4 -2
View File
@@ -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'
+12 -5
View File
@@ -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'
@@ -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 `<server_id>` 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. `<server_id>` 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('<group_id>', 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)
+4 -1
View File
@@ -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
@@ -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/<token>``, 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<modifier>\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
@@ -0,0 +1,77 @@
"""GHSA-m72h-hc66-5jwx: a member capped to `viewer` in a workspace could still
mutate that workspace's servers (re-pair the agent, rename, edit the IP
allow-list), whatever the cap said.
Each refusal has its control: the viewer still reads, a member still writes.
"""
import re
from unittest.mock import patch
import pytest
from factories import headers_for, make_server, make_user
@pytest.fixture
def capped(app):
from app import db
from app.services.workspace_service import WorkspaceService
admin = make_user(db, 'm72_admin', 'admin')
read_only = make_user(db, 'm72_ro', 'developer')
member = make_user(db, 'm72_member', 'developer')
ws = WorkspaceService.create_workspace({'name': 'M72'}, admin.id)
WorkspaceService.add_member(ws.id, read_only.id, role='viewer')
WorkspaceService.add_member(ws.id, member.id)
server = make_server(db, name='m72-box', workspace_id=ws.id)
return {'server': server.id, 'read_only': read_only.id, 'member': member.id}
def test_workspace_viewer_cannot_mutate_a_server(client, capped):
from app.models.server import Server
sid = capped['server']
before = Server.query.get(sid)
token_hash, status = before.registration_token_hash, before.status
headers = headers_for(capped['read_only'])
calls = [
client.post(f'/api/v1/servers/{sid}/regenerate-token', json={}, headers=headers),
client.put(f'/api/v1/servers/{sid}', json={'name': 'renamed'}, headers=headers),
client.put(f'/api/v1/servers/{sid}/allowed-ips', json={'allowed_ips': ['10.0.0.1']},
headers=headers),
]
assert [resp.status_code for resp in calls] == [403, 403, 403]
after = Server.query.get(sid)
assert (after.name, after.registration_token_hash, after.status) == (
'm72-box', token_hash, status)
assert not after.allowed_ips
def test_workspace_viewer_still_reads_and_a_member_still_writes(client, capped):
from app.models.server import Server
sid = capped['server']
assert client.get(f'/api/v1/servers/{sid}',
headers=headers_for(capped['read_only'])).status_code == 200
resp = client.put(f'/api/v1/servers/{sid}', json={'name': 'm72-renamed'},
headers=headers_for(capped['member']))
assert resp.status_code == 200 and Server.query.get(sid).name == 'm72-renamed'
def test_no_mutating_server_route_lets_a_workspace_viewer_through(app, client, capped):
"""Sweep: every mutating `<server_id>` route, present or future, refuses a
member whose workspace role is viewer. Anything other than a refusal means
the route acted (or validated input) before asking whether it may."""
sid = capped['server']
leaks = []
with patch('app.services.remote_command_dispatcher.dispatch_agent_command',
side_effect=AssertionError('agent reached')):
for rule in app.url_map.iter_rules():
if '<server_id>' not in rule.rule or not rule.rule.startswith('/api/v1/'):
continue
url = rule.rule.replace('<server_id>', sid)
url = re.sub(r'<int:[^>]+>', '1', url)
url = re.sub(r'<[^>]+>', 'x', url)
for method in sorted(rule.methods - {'GET', 'HEAD', 'OPTIONS'}):
resp = getattr(client, method.lower())(
url, json={}, headers=headers_for(capped['read_only']))
if resp.status_code not in (401, 403):
leaks.append(f'{method} {rule.rule} -> {resp.status_code}')
assert not leaks, '\n'.join(leaks)
@@ -0,0 +1,84 @@
"""GHSA-893r-j92f-5q9x: the resolved-variables routes took a resource id and
scope ids from the query string and checked neither, so any account could
read another workspace's variable groups.
Each refusal has its control: members still resolve their own.
"""
import pytest
from factories import headers_for, make_application, make_user
@pytest.fixture
def variables(app):
from app import db
from app.services.shared_resource_service import SharedResourceService
from app.services.workspace_service import WorkspaceService
admin = make_user(db, 'v893_admin', 'admin')
member = make_user(db, 'v893_member', 'developer')
outsider = make_user(db, 'v893_outsider', 'developer')
ws_a = WorkspaceService.create_workspace({'name': 'V893-A'}, admin.id)
WorkspaceService.add_member(ws_a.id, member.id)
ws_b = WorkspaceService.create_workspace({'name': 'V893-B'}, outsider.id)
group = SharedResourceService.create_group('workspace', ws_a.id, 'tenant-a')
SharedResourceService.set_variable(group.id, 'TENANT_A_PLAIN', 'visible-value-a')
SharedResourceService.set_variable(group.id, 'TENANT_A_KEY', 'secret-a', is_secret=True)
app_a = make_application(db, name='v893-a', user_id=member.id, workspace_id=ws_a.id)
SharedResourceService.attach_group(group.id, 'application', app_a.id)
app_b = make_application(db, name='v893-b', user_id=outsider.id, workspace_id=ws_b.id)
return {'member': member.id, 'outsider': outsider.id, 'admin': admin.id,
'ws_a': ws_a.id, 'ws_b': ws_b.id, 'app_a': app_a.id, 'app_b': app_b.id}
def _resolved(client, user, path, **query):
qs = '&'.join(f'{key}={value}' for key, value in query.items())
return client.get(f'/api/v1/shared/{path}?{qs}', headers=headers_for(user))
_NEEDLES = ('TENANT_A_PLAIN', 'TENANT_A_KEY', 'visible-value-a', 'secret-a', 'tenant-a')
def test_outsider_cannot_layer_in_a_foreign_workspace(client, variables):
"""The reported call: the caller's OWN app, another workspace's id."""
resp = _resolved(client, variables['outsider'], 'resolved/hierarchical',
resource_type='application', resource_id=variables['app_b'],
workspace_id=variables['ws_a'])
assert resp.status_code in (403, 404)
assert not [n for n in _NEEDLES if n in resp.get_data(as_text=True)]
@pytest.mark.parametrize('path', ['resolved', 'resolved/hierarchical'])
def test_outsider_cannot_resolve_a_foreign_resource(client, variables, path):
resp = _resolved(client, variables['outsider'], path,
resource_type='application', resource_id=variables['app_a'])
assert resp.status_code in (403, 404)
assert not [n for n in _NEEDLES if n in resp.get_data(as_text=True)]
@pytest.mark.parametrize('path', ['resolved', 'resolved/hierarchical'])
def test_unknown_resource_types_fail_closed(client, variables, path):
resp = _resolved(client, variables['outsider'], path,
resource_type='nonsense', resource_id=1, workspace_id=variables['ws_b'])
assert resp.status_code == 403
@pytest.mark.parametrize('who', ['member', 'admin'])
def test_members_still_resolve_their_own(client, variables, who):
resp = _resolved(client, variables[who], 'resolved/hierarchical',
resource_type='application', resource_id=variables['app_a'],
workspace_id=variables['ws_a'])
assert resp.status_code == 200
keys = {row['key'] for row in resp.get_json()['variables']}
assert {'TENANT_A_PLAIN', 'TENANT_A_KEY'} <= keys
assert 'secret-a' not in resp.get_data(as_text=True) # still masked
flat = _resolved(client, variables[who], 'resolved',
resource_type='application', resource_id=variables['app_a'])
assert flat.status_code == 200
assert 'TENANT_A_PLAIN' in flat.get_data(as_text=True)
def test_outsider_still_resolves_inside_their_own_workspace(client, variables):
resp = _resolved(client, variables['outsider'], 'resolved/hierarchical',
resource_type='application', resource_id=variables['app_b'],
workspace_id=variables['ws_b'])
assert resp.status_code == 200
+377
View File
@@ -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 = """<?php
define( 'DB_NAME', 'shop_wp' );
define( 'DB_USER', 'shop_user' );
define( 'DB_PASSWORD', 'never-read-this' );
define( 'DB_HOST', 'localhost' );
$table_prefix = 'shp_';
"""
@pytest.fixture
def host(tmp_path, monkeypatch):
"""A fake host: one WordPress site on PHP-FPM, one static site, one proxied
app, a www redirect, the panel's own vhost and the distro default."""
from app.services import site_adoption_service
from app.services.nginx_service import NginxService
nginx = tmp_path / 'nginx'
available, enabled = nginx / 'sites-available', nginx / 'sites-enabled'
for directory in (available, enabled, nginx / 'conf.d'):
directory.mkdir(parents=True)
php = tmp_path / 'php'
pool_dir = php / '8.4' / 'fpm' / 'pool.d'
pool_dir.mkdir(parents=True)
(pool_dir / 'shop.conf').write_text(
'; pool for the shop\n[shop]\nuser = shop\nlisten = /run/php/shop.sock\n',
encoding='utf-8')
shop_root = tmp_path / 'www' / 'shop' / 'public'
(shop_root / 'wp-includes').mkdir(parents=True)
(shop_root / 'wp-config.php').write_text(WP_CONFIG, encoding='utf-8')
(shop_root / 'wp-includes' / 'version.php').write_text(
"<?php\n$wp_version = '6.8.1';\n", encoding='utf-8')
docs_root = tmp_path / 'www' / 'docs'
docs_root.mkdir(parents=True)
files = {
'shop.example.com.conf': f"""
# Site: shop
server {{
listen 80;
server_name shop.example.com www.shop.example.com;
return 301 https://shop.example.com$request_uri;
}}
server {{
listen 443 ssl http2;
server_name shop.example.com;
root {shop_root.as_posix()};
ssl_certificate /etc/letsencrypt/live/shop.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/shop.example.com/privkey.pem;
location ~ \\.php$ {{
fastcgi_pass unix:/run/php/shop.sock;
}}
}}
""",
'docs.example.com.conf': f"""
server {{
listen 80;
server_name docs.example.com;
root "{docs_root.as_posix()}";
}}
""",
'api.example.com.conf': """
server {
listen 80;
server_name api.example.com;
location / { proxy_pass http://127.0.0.1:3210; }
}
""",
'serverkit.conf': """
server { listen 80 default_server; server_name _; root /opt/serverkit; }
""",
'default': """
server { listen 80; server_name _; root /var/www/html; }
""",
}
for name, body in files.items():
(available / name).write_text(body, encoding='utf-8')
# A copy, not a symlink: Windows dev boxes cannot create symlinks.
(enabled / name).write_text(body, encoding='utf-8')
monkeypatch.setattr(NginxService, 'NGINX_CONF_DIR', str(nginx))
monkeypatch.setattr(NginxService, 'SITES_AVAILABLE', str(available))
monkeypatch.setattr(NginxService, 'SITES_ENABLED', str(enabled))
monkeypatch.setattr(site_adoption_service, 'PHP_ETC_DIR', str(php))
return {'root': tmp_path, 'shop_root': shop_root.as_posix(),
'docs_root': docs_root.as_posix()}
def _snapshot(root):
"""Content hash of every file under the fake host."""
return {path.relative_to(root).as_posix(): hashlib.sha256(path.read_bytes()).hexdigest()
for path in sorted(root.rglob('*')) if path.is_file()}
@pytest.fixture
def admin(app):
from app import db
return make_user(db, 'adopt_admin', 'admin')
def _by_domain(sites):
return {site['primary_domain']: site for site in sites}
# --------------------------------------------------------------- discovery
def test_discovery_describes_each_site_and_skips_the_panel(app, host):
from app.services import site_adoption_service
sites = _by_domain(site_adoption_service.discover())
# The panel's own vhost and the catch-all default are not sites.
assert set(sites) == {'shop.example.com', 'docs.example.com', 'api.example.com'}
shop = sites['shop.example.com']
assert shop['kind'] == 'php' and shop['app_type'] == 'wordpress'
assert shop['root'] == host['shop_root']
# The :80 redirect block and its www name fold into the one site.
assert shop['domains'] == ['shop.example.com', 'www.shop.example.com']
# 8.4 is outside PHPService.SUPPORTED_VERSIONS — found by the pool's socket.
assert shop['php'] == {'version': '8.4', 'pool': 'shop', 'listen': '/run/php/shop.sock',
'pool_file': shop['php']['pool_file']}
assert shop['ssl']['enabled'] and shop['ssl']['letsencrypt']
assert shop['ssl']['certificate'].endswith('shop.example.com/fullchain.pem')
assert shop['wordpress']['version'] == '6.8.1'
assert shop['database'] == {'engine': 'mysql', 'name': 'shop_wp',
'user': 'shop_user', 'host': 'localhost'}
assert shop['adoptable'] and shop['linked_app'] is None
docs = sites['docs.example.com']
assert (docs['kind'], docs['app_type'], docs['adoptable']) == ('static', 'static', True)
assert docs['root'] == host['docs_root'] and docs['php'] is None
api = sites['api.example.com']
assert (api['kind'], api['port'], api['adoptable']) == ('proxy', 3210, False)
assert 'Docker Compose or systemd' in api['reason']
def test_discovery_never_exposes_the_database_password(app, host):
from app.services import site_adoption_service
assert 'never-read-this' not in repr(site_adoption_service.discover())
def test_php_version_falls_back_to_the_socket_name(app, host):
from app.services import site_adoption_service
assert site_adoption_service._php_for('unix:/run/php/php8.2-fpm.sock', [])['version'] == '8.2'
assert site_adoption_service._php_for('127.0.0.1:9000', [])['version'] is None
# ----------------------------------------------------------------- adopting
def test_dry_run_is_the_default_and_changes_nothing(client, host, admin):
from app.models.application import Application
before = _snapshot(host['root'])
resp = client.post('/api/v1/apps/host-sites/adopt', json={'site': 'shop.example.com'},
headers=headers_for(admin))
assert resp.status_code == 200
body = resp.get_json()
assert body['dry_run'] is True and body['adoptable'] is True
assert body['plan']['application'] == {
'name': 'shop-example-com', 'app_type': 'wordpress', 'managed_by': 'host',
'source': 'manual', 'root_path': host['shop_root'], 'php_version': '8.4'}
assert [d['name'] for d in body['plan']['domains']] == [
'shop.example.com', 'www.shop.example.com']
assert any(path.endswith('shop.example.com.conf') for path in body['plan']['untouched'])
assert Application.query.filter_by(name='shop-example-com').first() is None
assert _snapshot(host['root']) == before
def test_adopt_records_the_site_and_writes_nothing_to_the_host(client, host, admin):
from app.models.application import Application
from app.models.domain import Domain
from app.models.managed_database import ManagedDatabase
from app.models.wordpress_site import WordPressSite
before = _snapshot(host['root'])
with patch('app.services.nginx_service.NginxService.create_site',
side_effect=AssertionError('adoption wrote a vhost')), \
patch('app.services.nginx_service.NginxService.write_vhost',
side_effect=AssertionError('adoption wrote a vhost')):
resp = client.post('/api/v1/apps/host-sites/adopt',
json={'site': 'shop.example.com', 'dry_run': False},
headers=headers_for(admin))
assert resp.status_code == 201, resp.get_json()
assert _snapshot(host['root']) == before
app_row = Application.query_active().filter_by(name='shop-example-com').one()
assert (app_row.app_type, app_row.managed_by, app_row.source) == ('wordpress', 'host', 'manual')
assert (app_row.status, app_row.php_version, app_row.root_path) == (
'running', '8.4', host['shop_root'])
assert app_row.is_host_managed and app_row.workspace_id is not None
domains = Domain.query_active().filter_by(application_id=app_row.id).order_by(Domain.id).all()
assert [(d.name, d.is_primary, d.ssl_enabled) for d in domains] == [
('shop.example.com', True, True), ('www.shop.example.com', False, True)]
assert domains[0].ssl_certificate_path.endswith('shop.example.com/fullchain.pem')
wp = WordPressSite.query.filter_by(application_id=app_row.id).one()
assert (wp.db_name, wp.db_user, wp.db_prefix, wp.wp_version) == (
'shop_wp', 'shop_user', 'shp_', '6.8.1')
# Not a compose site: nothing invented for the container fields.
assert wp.compose_project_name is None and wp.container_prefix is None
database = ManagedDatabase.query_active().filter_by(name='shop_wp').one()
assert database.owner_application_id == app_row.id and database.origin == 'adopted'
def test_an_adopted_site_is_no_longer_reported_or_adoptable(client, host, admin):
listing = client.get('/api/v1/apps/host-sites', headers=headers_for(admin)).get_json()
assert (listing['unmanaged'], listing['adoptable']) == (3, 2)
client.post('/api/v1/apps/host-sites/adopt',
json={'site': 'docs.example.com', 'dry_run': False, 'name': 'docs'},
headers=headers_for(admin))
listing = client.get('/api/v1/apps/host-sites', headers=headers_for(admin)).get_json()
assert (listing['unmanaged'], listing['adoptable']) == (2, 1)
docs = _by_domain(listing['sites'])['docs.example.com']
assert docs['linked_app']['name'] == 'docs' and not docs['adoptable']
again = client.post('/api/v1/apps/host-sites/adopt',
json={'site': 'docs.example.com', 'dry_run': False},
headers=headers_for(admin))
assert again.status_code == 409 and 'Already managed' in again.get_json()['error']
@pytest.mark.parametrize('site,status', [
('api.example.com', 409), # a proxied process, not a host site
('nope.example.com', 404), # nothing nginx serves
('serverkit.conf', 404), # the panel itself is never offered
])
def test_adopt_refuses_what_it_should_not_register(client, host, admin, site, status):
resp = client.post('/api/v1/apps/host-sites/adopt', json={'site': site, 'dry_run': False},
headers=headers_for(admin))
assert resp.status_code == status
def test_adoption_is_admin_only(client, host, app):
from app import db
developer = make_user(db, 'adopt_dev', 'developer')
assert client.get('/api/v1/apps/host-sites',
headers=headers_for(developer)).status_code == 403
assert client.post('/api/v1/apps/host-sites/adopt', json={'site': 'docs.example.com'},
headers=headers_for(developer)).status_code == 403
assert client.get('/api/v1/apps/host-sites').status_code == 401
# ------------------------------------- the panel leaves the running config alone
@pytest.fixture
def adopted(client, host, admin):
from app.models.application import Application
client.post('/api/v1/apps/host-sites/adopt',
json={'site': 'shop.example.com', 'dry_run': False}, headers=headers_for(admin))
return Application.query_active().filter_by(name='shop-example-com').one()
def test_vhost_writer_and_drift_skip_a_host_managed_site(app, adopted):
from app.services import drift_service
from app.services.site_domain_service import SiteDomainService
with patch('app.services.nginx_service.NginxService.create_site',
side_effect=AssertionError('rewrote a host-managed vhost')):
result = SiteDomainService.write_app_vhost(adopted)
assert result['nginx'] is None and 'host-managed' in result['warning']
assert adopted.id not in {app_id for app_id, _ in drift_service._nginx_list_resources()}
assert drift_service._nginx_render_expected(adopted.id) == {}
def test_adding_a_domain_records_it_without_touching_nginx(client, admin, host):
# The static site, not the WordPress one: a static app has everything the
# vhost writer needs (a root), so only the host-managed guard stops it.
from app.models.application import Application
client.post('/api/v1/apps/host-sites/adopt',
json={'site': 'docs.example.com', 'dry_run': False}, headers=headers_for(admin))
adopted = Application.query_active().filter_by(name='docs-example-com').one()
before = _snapshot(host['root'])
# A mock, not a raising stub: the vhost writer swallows exceptions by design.
with patch('app.services.nginx_service.NginxService.create_site') as create_site:
resp = client.post('/api/v1/domains',
json={'name': 'store.example.com', 'application_id': adopted.id},
headers=headers_for(admin))
assert resp.status_code in (200, 201), resp.get_json()
create_site.assert_not_called()
assert _snapshot(host['root']) == before
@pytest.mark.parametrize('action', ['start', 'stop', 'restart'])
def test_lifecycle_refuses_instead_of_lying(client, admin, adopted, action):
resp = client.post(f'/api/v1/apps/{adopted.id}/{action}', headers=headers_for(admin))
assert resp.status_code >= 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/apps/host-sites/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() == []
+4
View File
@@ -159,6 +159,7 @@ Regenerate (backend/):
- `GET /api-keys/{key_id}`
- `GET /apps`
- `GET /apps/attachments/services`
- `GET /apps/host-sites`
- `GET /apps/p/{slug}`
- `GET /apps/{app_id}`
- `GET /apps/{app_id}/attachments`
@@ -599,6 +600,7 @@ Regenerate (backend/):
- `GET /servers/{server_id}/system/metrics`
- `GET /servers/{server_id}/timeline`
- `GET /services`
- `GET /services/host-sites`
- `GET /services/{app_id}`
- `GET /services/{app_id}/backup-policy`
- `GET /services/{app_id}/backups`
@@ -770,6 +772,7 @@ Regenerate (backend/):
- `POST /api-keys/{key_id}/rotate`
- `POST /apps`
- `POST /apps/from-repository`
- `POST /apps/host-sites/adopt`
- `POST /apps/htaccess-convert`
- `POST /apps/manual`
- `POST /apps/move-to-project`
@@ -1186,6 +1189,7 @@ Regenerate (backend/):
- `POST /servers/{server_id}/terminal`
- `POST /services`
- `POST /services/from-repository`
- `POST /services/host-sites/adopt`
- `POST /services/manual`
- `POST /services/move-to-project`
- `POST /services/sweep-idle`
+59
View File
@@ -87,6 +87,65 @@ When you're ready to move a site onto ServerKit:
checklist: what to stop on the old box, what to keep until TTLs expire, and
when it's safe to wipe.
## Adopt in place — a site that already runs on this server
Sometimes the site is already here: set up by hand, by a script, or by a
migration that wrote its own nginx and PHP-FPM config. It serves traffic, but
ServerKit has no record of it, so it gets no monitoring, backups, SSL status or
logs — while its database may well be listed under Databases.
Adopting registers such a site **as it is**. ServerKit reads the live nginx
config, the PHP-FPM pools, the certificate and (for WordPress) `wp-config.php`,
then records a service, its domains and its database link. **It writes nothing
to the server**: the vhost, the pool, the certificate and the files stay
exactly as they are. The database password is never read.
```bash
serverkit adopt-site # every site nginx serves, and its state
serverkit adopt-site example.com # dry run: what would be recorded
serverkit adopt-site example.com --apply # register it
```
In the panel, **Services** shows an **Adopt** button whenever this server is
serving sites that are not managed yet, and the doctor reports each one.
What adoption covers:
| Site | Adopted as |
|------|------------|
| nginx + PHP-FPM | a PHP service (any installed PHP version, any pool) |
| nginx + PHP-FPM + `wp-config.php` | a WordPress service, with its database linked |
| nginx serving files | a static service |
| nginx proxying to a port | not adopted here — register the process behind it as a Docker Compose or systemd service |
An adopted service is **host-managed**. ServerKit observes and records it but
never rewrites or removes its config:
- Adding or removing a domain updates the record only. Edit the vhost yourself.
- Start, stop and restart are refused: the site is served by the server's
shared nginx and PHP-FPM, and there is no per-site runtime to control.
- Deleting the service forgets it. The site keeps serving.
### Migrating a site onto this server by hand
If you move a site yourself instead of using the import wizard, finish by
adopting it so the migration does not bypass ServerKit:
1. **Copy the files** to their document root and set ownership to the PHP-FPM
pool user.
2. **Copy the database**: create the database and user, import the dump, and
point the site's config at it.
3. **Write the nginx vhost and PHP-FPM pool**, then `nginx -t` and reload. Keep
the ACME location ahead of any dotfile deny:
`location ^~ /.well-known/acme-challenge/ { root /var/www/certbot; }`.
4. **Check it on a preview hostname** (or a hosts-file entry) before touching
public DNS.
5. **Issue the certificate** once the name resolves here, or use a DNS
challenge to issue it ahead of the cutover.
6. **Cut DNS over**: lower the TTL a step ahead, switch the record, verify, and
keep the old server up until the old TTL has expired.
7. **Adopt the site**: `serverkit adopt-site <domain> --apply`.
## 3. Manage — full takeover on a clean box
Today's normal mode: ServerKit owns the box and manages the web stack end to
+2 -2
View File
@@ -18,8 +18,8 @@ debt. Regenerate with `python scripts/generate-migration-inventory.py`.
| API crashes swallowed without recording | app.error_reporting | 0 | 0 | INVARIANT at 0 |
| Hand-shaped {'error': ...} bodies in app/api | typed errors + the global handler | 849 | 850 | migrate when touched; new endpoints raise |
| Raw subprocess calls outside the runners | app/utils/system.py runners | 23 | 23 | migrate when touched |
| Controller-boundary violations (routes doing service work) | service layer extraction | 453 | 453 | migrate when touched (first-wave ratchet) |
| raw api.* calls in pages/ | E1: useServerQuery/useServerMutation | 363 | 371 | migrate when touched |
| Controller-boundary violations (routes doing service work) | service layer extraction | 451 | 451 | migrate when touched (first-wave ratchet) |
| raw api.* calls in pages/ | E1: useServerQuery/useServerMutation | 364 | 371 | migrate when touched |
| per-page toast.error extractions in pages/ | E1: query-layer error presentation | 185 | 206 | migrate when touched |
| hand-rolled form-group blocks | F2: FormField/useForm | 206 | 206 | migrate when touched |
| unencoded ?k=${v} query interpolations in services/api | C4: buildQuery/encoding template | 0 | 0 | INVARIANT at 0 |
@@ -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 (
<Modal
open={open}
onClose={onClose}
size="lg"
title={t('app.services.adopt.title', 'Adopt existing sites')}
footer={(
<Button type="button" variant="outline" onClick={onClose}>
{t('common.actions.close', 'Close')}
</Button>
)}
>
<p className="sk-modal__subtitle">
{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.')}
</p>
<ul className="adopt-sites">
{sites.map((site) => (
<li key={site.id} className="adopt-sites__row">
<div className="adopt-sites__main">
<div className="adopt-sites__head">
<span className="adopt-sites__domain">{site.primary_domain}</span>
<Pill kind={site.adoptable ? 'cyan' : 'gray'} dot={false}>{kindLabel(site)}</Pill>
</div>
<dl className="adopt-sites__facts">
{site.domains.length > 1 && (
<>
<dt>{t('app.services.adopt.alsoServes', 'Also serves')}</dt>
<dd>{site.domains.slice(1).join(', ')}</dd>
</>
)}
{site.root && (
<>
<dt>{t('app.services.adopt.root', 'Document root')}</dt>
<dd>{site.root}</dd>
</>
)}
{site.php && (
<>
<dt>{t('app.services.adopt.php', 'PHP-FPM')}</dt>
<dd>
{site.php.version || t('app.services.adopt.unknownVersion', 'Unknown version')}
{site.php.pool ? ` · ${site.php.pool}` : ''}
</dd>
</>
)}
{site.upstream && (
<>
<dt>{t('app.services.adopt.upstream', 'Proxies to')}</dt>
<dd>{site.upstream}</dd>
</>
)}
{site.database && (
<>
<dt>{t('app.services.adopt.database', 'Database')}</dt>
<dd>{site.database.name}</dd>
</>
)}
<dt>{t('app.services.adopt.certificate', 'Certificate')}</dt>
<dd>
{site.ssl.enabled
? site.ssl.certificate
: t('app.services.adopt.noCertificate', 'None')}
</dd>
<dt>{t('app.services.adopt.vhost', 'nginx config')}</dt>
<dd>{site.vhost_file}</dd>
</dl>
{!site.adoptable && site.reason && (
<p className="adopt-sites__reason">{site.reason}</p>
)}
</div>
{site.adoptable && (
<Button
type="button"
size="sm"
onClick={() => handleAdopt(site)}
disabled={adopting !== null}
>
{adopting === site.id
? t('app.services.adopt.adopting', 'Adopting…')
: t('app.services.adopt.action', 'Adopt')}
</Button>
)}
</li>
))}
</ul>
</Modal>
);
}
+25
View File
@@ -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",
+9 -1
View File
@@ -476,7 +476,7 @@ const ServiceDetail = () => {
{service.managed_by && (
<>
<span className="svc-detail__repo-arrow">&rarr;</span>
<span className="svc-detail__repo-branch">{service.managed_by === 'docker_compose' ? t('app.serviceDetail.dockerCompose', 'Docker Compose') : 'systemd'}</span>
<span className="svc-detail__repo-branch">{managedByLabel(service.managed_by, t)}</span>
</>
)}
</span>
@@ -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 {
+47 -3
View File
@@ -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 && (
<Button
variant="outline"
size="sm"
onClick={() => setShowAdoptDialog(true)}
title={t('app.services.adopt.buttonTitle', 'Sites running on this server that are not managed here yet')}
>
<ScanSearch size={16} />
{t('app.services.adopt.button', { count: unmanagedSites.length, defaultValue: 'Adopt ({{count}})' })}
</Button>
)}
<Button variant="outline" size="sm" asChild title={t('app.services.importASite', 'Import a site')}>
<Link to="/imports" aria-label={t('app.services.importASite', 'Import a site')}>
<ArrowDownToLine size={16} />
@@ -221,7 +254,7 @@ const Services = () => {
placeholder={t('app.services.searchServices', 'Search services…')}
/>
</>,
[searchTerm]
[searchTerm, unmanagedSites.length]
);
const toggleOne = (id, checked) => {
@@ -374,6 +407,9 @@ const Services = () => {
sortable: false,
hideable: false,
render: (app) => {
// A host-managed site is served by the server's own nginx and
// PHP-FPM: there is nothing per-site to start or stop.
if (app.managed_by === 'host') return null;
const isRunning = app.status === 'running';
return (
<div className="services-page__actions" onClick={(e) => e.stopPropagation()}>
@@ -414,7 +450,7 @@ const Services = () => {
items={filteredApps}
columns={columns}
keyField="id"
onRowClick={(app) => navigate(app.app_type === 'wordpress' ? `/wordpress/${app.id}` : `/services/${app.id}`)}
onRowClick={(app) => navigate(app.app_type === 'wordpress' && app.managed_by !== 'host' ? `/wordpress/${app.id}` : `/services/${app.id}`)}
selectable
selectedIds={selectedIds}
onToggleSelect={toggleOne}
@@ -447,6 +483,14 @@ const Services = () => {
filteredEmptyTitle={t('app.services.noServicesFound', 'No services found')}
filteredEmptyDescription={t('app.services.tryAdjustingFilter', 'Try adjusting your search or filter')}
>
<AdoptSitesDialog
open={showAdoptDialog && unmanagedSites.length > 0}
onClose={() => setShowAdoptDialog(false)}
sites={unmanagedSites}
onAdopted={async () => {
await Promise.all([loadApps(), loadUnmanagedSites()]);
}}
/>
<MoveToProjectDialog
open={showMoveDialog}
onOpenChange={setShowMoveDialog}
+2
View File
@@ -36,6 +36,7 @@ import * as speedTestMethods from './speedtest.js';
import * as dbProcessMethods from './dbProcesses.js';
import * as dbTunerMethods from './dbTuner.js';
import * as importMethods from './imports.js';
import * as siteAdoptionMethods from './siteAdoption.js';
import * as doctorMethods from './doctor.js';
import * as bandwidthMethods from './bandwidth.js';
import * as htaccessToolMethods from './htaccessTools.js';
@@ -97,6 +98,7 @@ class ApiService extends ApiClient {
dbProcessMethods,
dbTunerMethods,
importMethods,
siteAdoptionMethods,
doctorMethods,
bandwidthMethods,
htaccessToolMethods,
+15
View File
@@ -0,0 +1,15 @@
// Site adoption (/api/v1/apps/host-sites) — register sites that already run on
// this host. Discovery is read-only; adopting records rows and never rewrites
// the running nginx / PHP-FPM config. Admin-only on the server.
export async function getHostSites() {
return this.request('/apps/host-sites');
}
// A dry run unless `apply` is true: the server's default answer is the plan.
export async function adoptHostSite(site, { name, apply = false } = {}) {
return this.request('/apps/host-sites/adopt', {
method: 'POST',
body: { site, name: name || undefined, dry_run: !apply },
});
}
+63
View File
@@ -92,6 +92,69 @@
}
}
// "Adopt existing sites" dialog: one row per site nginx serves that no
// service accounts for, with what discovery found about it.
.adopt-sites {
display: flex;
flex-direction: column;
gap: $space-3;
margin: 0;
padding: 0;
list-style: none;
&__row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: $space-4;
padding: $space-3;
border: 1px solid var(--border-soft);
border-radius: $radius-card;
background: var(--surface-2);
}
&__main {
min-width: 0;
flex: 1;
}
&__head {
display: flex;
align-items: center;
gap: $space-2;
flex-wrap: wrap;
}
&__domain {
font-size: $text-sm;
font-weight: $font-weight-medium;
color: $text-primary;
overflow-wrap: anywhere;
}
&__facts {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
gap: $space-1 $space-3;
margin: $space-2 0 0;
font-size: $text-xs;
dt { color: $text-secondary; }
dd {
margin: 0;
color: $text-primary;
overflow-wrap: anywhere;
}
}
&__reason {
margin: $space-2 0 0;
font-size: $text-xs;
color: $text-secondary;
}
}
@keyframes pulse-dot {
0%, 100% { opacity: 1; }
50% { opacity: 0.4; }
+1 -1
View File
@@ -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;
}
+1 -1
View File
@@ -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;
}
@@ -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;
}
+1 -1
View File
@@ -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;
}
+95 -3
View File
@@ -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,12 +840,93 @@ 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
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" <<EOF
#!/usr/bin/env bash
echo ran > "$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" <<EOF
#!/usr/bin/env bash
source "$CLI"
check_root() { :; }
eval "\$(sed -n '/^if \[ \$# -gt 1 \] && \[\[ " \$PLAIN_COMMANDS "/,\$p' "$CLI")"
EOF
run_plain() {
SERVERKIT_DIR="$t/install" SERVERKIT_NGINX_DIR="$t/nginx" bash "$t/run.sh" "$@" 2>&1 </dev/null
}
t21_fail=""
for args in "add-site --help" "add-site -h" "add-site example.com --help" \
"remove-site --help" "setup-proxy --help" "setup-proxy -h" \
"doctor --help" "restore-db --help" "factory-reset --help"; do
# shellcheck disable=SC2086
out="$(run_plain $args)"; rc=$?
cmd="${args%% *}"
if [ "$rc" -ne 0 ] || ! printf '%s' "$out" | grep -q "^Usage: serverkit $cmd"; then
t21_fail="$t21_fail [$args → rc=$rc: $(printf '%s' "$out" | head -n 2 | tr '\n' ' ')]"
fi
done
written="$(find "$t/nginx" -mindepth 2 2>/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 ]
+77 -5
View File
@@ -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") ) ;;
@@ -1084,6 +1086,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 +1108,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 <domain> [port]"
exit 1
fi
if ! [[ "$PORT" =~ ^[0-9]+$ ]]; then
print_error "Not a valid port: $PORT"
echo "Usage: serverkit add-site <domain> [port]"
exit 1
fi
resolve_site_paths "$DOMAIN"
if [ -f "$SITE_FILE" ]; then
@@ -1186,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
@@ -1554,6 +1581,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 <domain>"
exit 1
fi
resolve_site_paths "$DOMAIN"
if [ ! -f "$SITE_FILE" ]; then
@@ -1575,6 +1608,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=" <backup-file>" ;;
start-app|stop-app|app-logs) args=" <name>" ;;
add-site) args=" <domain> [port]" ;;
remove-site) args=" <domain>" ;;
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 +1649,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
@@ -1655,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)