diff --git a/ROADMAP.md b/ROADMAP.md index bb346d1d..843d3236 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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. diff --git a/VERSION b/VERSION index e4f4cc00..174b3eb5 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.11.43 +1.11.45 diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py index 369a9adb..74ba1801 100644 --- a/backend/app/api/apps.py +++ b/backend/app/api/apps.py @@ -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 diff --git a/backend/app/api/apps_adoption.py b/backend/app/api/apps_adoption.py new file mode 100644 index 00000000..36ca43f1 --- /dev/null +++ b/backend/app/api/apps_adoption.py @@ -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 diff --git a/backend/app/api/backups.py b/backend/app/api/backups.py index 9578f935..dc62d0e6 100644 --- a/backend/app/api/backups.py +++ b/backend/app/api/backups.py @@ -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 diff --git a/backend/app/api/databases.py b/backend/app/api/databases.py index e34c351e..e4be2f80 100644 --- a/backend/app/api/databases.py +++ b/backend/app/api/databases.py @@ -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 diff --git a/backend/app/api/fleet_monitor.py b/backend/app/api/fleet_monitor.py index 8802ba18..6e041b53 100644 --- a/backend/app/api/fleet_monitor.py +++ b/backend/app/api/fleet_monitor.py @@ -4,6 +4,10 @@ Fleet Monitor API Endpoints for fleet-wide monitoring: heatmaps, comparisons, alert thresholds, anomaly detection, capacity forecasting, fleet search, and metrics export. + +Every read passes the caller to the service, which answers only for servers +that caller can access — the workspace rule GET /servers applies. These routes +carry no server id in the path, so nothing else enforces it for them. """ from flask import Blueprint, request, jsonify, Response @@ -24,7 +28,7 @@ fleet_monitor_bp = Blueprint('fleet_monitor', __name__) def get_fleet_heatmap(): """Get latest metrics for all servers in heatmap format.""" group_id = request.args.get('group_id') - return jsonify(fleet_monitor_service.get_fleet_heatmap(group_id)) + return jsonify(fleet_monitor_service.get_fleet_heatmap(get_current_user(), group_id)) # ==================== Comparison ==================== @@ -41,7 +45,8 @@ def get_comparison(): if not server_ids: return jsonify({'error': 'ids parameter is required'}), 400 - return jsonify(fleet_monitor_service.get_comparison_timeseries(server_ids, metric, period)) + return jsonify(fleet_monitor_service.get_comparison_timeseries( + get_current_user(), server_ids, metric, period)) # ==================== Alerts ==================== @@ -55,7 +60,8 @@ def get_alerts(): server_id = request.args.get('server_id') limit = request.args.get('limit', 50, type=int) - return jsonify(fleet_monitor_service.get_alerts(status, severity, server_id, limit)) + return jsonify(fleet_monitor_service.get_alerts( + get_current_user(), status, severity, server_id, limit)) @fleet_monitor_bp.route('/alerts//acknowledge', methods=['POST']) @@ -89,7 +95,7 @@ def resolve_alert(alert_id): def get_thresholds(): """Get alert thresholds.""" server_id = request.args.get('server_id') - return jsonify(fleet_monitor_service.get_thresholds(server_id)) + return jsonify(fleet_monitor_service.get_thresholds(get_current_user(), server_id)) @fleet_monitor_bp.route('/thresholds', methods=['POST']) @@ -120,7 +126,7 @@ def delete_threshold(threshold_id): def get_anomalies(): """Get anomaly detection results.""" server_id = request.args.get('server_id') - return jsonify(fleet_monitor_service.detect_anomalies(server_id)) + return jsonify(fleet_monitor_service.detect_anomalies(get_current_user(), server_id)) # ==================== Capacity Forecast ==================== @@ -146,7 +152,7 @@ def search_fleet(): if not query or len(query) < 2: return jsonify({'error': 'Query must be at least 2 characters'}), 400 - return jsonify(fleet_monitor_service.search_fleet(query, search_type)) + return jsonify(fleet_monitor_service.search_fleet(get_current_user(), query, search_type)) # ==================== Export ==================== @@ -163,7 +169,8 @@ def export_csv(): if not server_ids: return jsonify({'error': 'ids parameter is required'}), 400 - csv_data = fleet_monitor_service.export_metrics_csv(server_ids, metric, period) + csv_data = fleet_monitor_service.export_metrics_csv( + get_current_user(), server_ids, metric, period) return Response( csv_data, mimetype='text/csv', @@ -183,7 +190,8 @@ def export_json(): if not server_ids: return jsonify({'error': 'ids parameter is required'}), 400 - return jsonify(fleet_monitor_service.get_comparison_timeseries(server_ids, metric, period)) + return jsonify(fleet_monitor_service.get_comparison_timeseries( + get_current_user(), server_ids, metric, period)) # ==================== Prometheus ==================== diff --git a/backend/app/api/mobile.py b/backend/app/api/mobile.py index 5b2a6e78..a3d9d5f1 100644 --- a/backend/app/api/mobile.py +++ b/backend/app/api/mobile.py @@ -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(), diff --git a/backend/app/api/proxy.py b/backend/app/api/proxy.py index 1fe8e648..ae3fda10 100644 --- a/backend/app/api/proxy.py +++ b/backend/app/api/proxy.py @@ -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 ```` converter on ``//proxy``, and Werkzeug prefers static rules over dynamic ones, so the two never collide. Best-effort; always returns JSON. """ - return jsonify({'servers': ProxyStackService.fleet_overview()}) + from app.middleware.rbac import get_current_user + return jsonify({'servers': ProxyStackService.fleet_overview(get_current_user())}) @proxy_bp.route('//proxy', methods=['GET']) diff --git a/backend/app/api/servers.py b/backend/app/api/servers.py index ff51cb0c..4f0c7cd6 100644 --- a/backend/app/api/servers.py +++ b/backend/app/api/servers.py @@ -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/', 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) diff --git a/backend/app/api/shared_resources.py b/backend/app/api/shared_resources.py index bad1ec4e..b26558f6 100644 --- a/backend/app/api/shared_resources.py +++ b/backend/app/api/shared_resources.py @@ -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 ) diff --git a/backend/app/api/two_factor.py b/backend/app/api/two_factor.py index 5597ea2e..d231275b 100644 --- a/backend/app/api/two_factor.py +++ b/backend/app/api/two_factor.py @@ -67,7 +67,8 @@ def get_2fa_status(): @jwt_required() def initiate_2fa_setup(): """ - Initiate 2FA setup. Generates a new secret and returns QR code. + Initiate 2FA setup. Reuses the pending unconfirmed secret (or generates + one); JSON {"regenerate": true} forces a fresh secret. User must verify with a code to complete setup. """ current_user_id = get_jwt_identity() @@ -79,8 +80,11 @@ def initiate_2fa_setup(): if user.totp_enabled: return jsonify({'error': '2FA is already enabled'}), 400 + data = json_object(optional=True) + regenerate = data.get('regenerate') is True + setup = TwoFactorSetup(user) - setup_data = setup.initiate_setup() + setup_data = setup.initiate_setup(regenerate=regenerate) return jsonify({ 'message': '2FA setup initiated. Scan the QR code and enter a verification code.', diff --git a/backend/app/models/application.py b/backend/app/models/application.py index 479e7649..57221b0e 100644 --- a/backend/app/models/application.py +++ b/backend/app/models/application.py @@ -88,7 +88,7 @@ class Application(JsonColumnMixin, TimestampMixin, SoftDeleteMixin, db.Model): # Manual / local service configuration compose_file = db.Column(db.String(200), nullable=True) systemd_unit = db.Column(db.String(100), nullable=True) - managed_by = db.Column(db.String(20), nullable=True) # 'docker_compose', 'systemd' + managed_by = db.Column(db.String(20), nullable=True) # 'docker_compose', 'systemd', 'host' # Ingress plane: which reverse proxy is expected to serve this app — # 'nginx' (host Nginx, the default) or 'proxy_stack' (Dockerized @@ -186,6 +186,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 diff --git a/backend/app/services/application_lifecycle_service.py b/backend/app/services/application_lifecycle_service.py index 58009d66..70ff847b 100644 --- a/backend/app/services/application_lifecycle_service.py +++ b/backend/app/services/application_lifecycle_service.py @@ -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: diff --git a/backend/app/services/application_restore.py b/backend/app/services/application_restore.py index 4252780d..535a0331 100644 --- a/backend/app/services/application_restore.py +++ b/backend/app/services/application_restore.py @@ -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)} diff --git a/backend/app/services/backup_policy_service.py b/backend/app/services/backup_policy_service.py index 1dbace33..20350291 100644 --- a/backend/app/services/backup_policy_service.py +++ b/backend/app/services/backup_policy_service.py @@ -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: diff --git a/backend/app/services/doctor_service.py b/backend/app/services/doctor_service.py index a34ccba6..bbd1548b 100644 --- a/backend/app/services/doctor_service.py +++ b/backend/app/services/doctor_service.py @@ -705,6 +705,37 @@ class DoctorService: return [_check('extensions.checks', 'Extension checks', 'warn', f'Could not collect extension checks: {e}')] + @classmethod + def _unmanaged_site_checks(cls): + """Sites host nginx is serving that no application accounts for. + + Such a site is live but invisible to the panel: no monitoring, + backups, SSL status or logs, while its database may well be listed + under Databases. One warning per site; a host with none adds nothing. + Not repairable — adopting is the operator's call, and it is one + command (or one click) away in the detail.""" + try: + from app.services import site_adoption_service + sites = site_adoption_service.unmanaged() + except Exception as e: # noqa: BLE001 + logger.warning('unmanaged-site doctor section failed: %s', e) + return [_check('sites.unmanaged', 'Unmanaged sites', 'warn', + f'Could not read the host nginx config: {e}')] + checks = [] + for site in sites: + if site['kind'] == site_adoption_service.KIND_REDIRECT: + continue # a redirect-only vhost has no site behind it + if site['adoptable']: + detail = (f"Served by host nginx ({site['vhost_file']}) but not registered " + f"in ServerKit. Adopt it from Services, or run: " + f"serverkit adopt-site {site['primary_domain']} --apply") + else: + detail = (f"Served by host nginx ({site['vhost_file']}) but not registered " + f"in ServerKit. {site['reason']}") + checks.append(_check(f"sites.unmanaged.{site['id']}", + f"Unmanaged site: {site['primary_domain']}", 'warn', detail)) + return checks + # ------------------------------------------------------------------ # # Sweep # ------------------------------------------------------------------ # @@ -718,6 +749,7 @@ class DoctorService: checks = [] checks += cls._drift_checks() checks += cls._service_checks() + checks += cls._unmanaged_site_checks() checks += cls._dns_checks() checks += cls._backup_proof_checks() checks.append(cls._cert_check()) diff --git a/backend/app/services/drift_service.py b/backend/app/services/drift_service.py index fdfdea8a..8683beb5 100644 --- a/backend/app/services/drift_service.py +++ b/backend/app/services/drift_service.py @@ -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): diff --git a/backend/app/services/fleet_monitor_service.py b/backend/app/services/fleet_monitor_service.py index 8f2b8d74..9e5185e0 100644 --- a/backend/app/services/fleet_monitor_service.py +++ b/backend/app/services/fleet_monitor_service.py @@ -20,6 +20,7 @@ from app.models.server import Server, ServerMetrics, ServerGroup from app.models.metric_alert import ServerAlertThreshold, MetricAlert from app.services.agent_registry import agent_registry from app.services.server_metrics_service import latest_metrics_by_server +from app.services.workspace_service import WorkspaceService logger = logging.getLogger(__name__) @@ -32,15 +33,40 @@ METRIC_COLUMNS = { } +def _visible_servers(user, query=None): + """A Server query narrowed to what *user* may see — the same workspace + rule as GET /servers. Every read below goes through this or + `_visible_server`; the unscoped `Server.query` is for the system-level + passes only (threshold checks, the token-gated Prometheus scrape).""" + return WorkspaceService.filter_accessible_servers( + Server.query if query is None else query, user) + + +def _visible_server(user, server_id): + """The server if *user* may see it, else None — a foreign id reads + exactly like an unknown one.""" + return WorkspaceService.get_accessible_server(user, server_id) + + +def _visible_server_ids(user): + """Subquery of the server ids *user* may see, for filtering child rows.""" + return WorkspaceService.filter_accessible_servers( + db.session.query(Server.id), user) + + class FleetMonitorService: - """Service for fleet-wide monitoring and alerting.""" + """Service for fleet-wide monitoring and alerting. + + The read methods take the calling ``user`` and answer only for servers that + user can access (GHSA-qcjj-hf95-6rgw). + """ # ==================== Fleet Heatmap ==================== @staticmethod - def get_fleet_heatmap(group_id: str = None) -> List[Dict]: - """Get latest metrics for all servers, shaped for heatmap display.""" - query = Server.query + def get_fleet_heatmap(user, group_id: str = None) -> List[Dict]: + """Latest metrics for the servers *user* can access, shaped for heatmap display.""" + query = _visible_servers(user) if group_id: query = query.filter_by(group_id=group_id) @@ -70,9 +96,11 @@ class FleetMonitorService: @staticmethod def get_comparison_timeseries( - server_ids: List[str], metric: str = 'cpu', period: str = '24h' + user, server_ids: List[str], metric: str = 'cpu', period: str = '24h' ) -> Dict: - """Get time-series data for multiple servers for overlay charting.""" + """Get time-series data for multiple servers for overlay charting. + + Ids *user* cannot access are skipped, like ids that do not exist.""" hours_back = {'1h': 1, '6h': 6, '24h': 24, '7d': 168, '30d': 720}.get(period, 24) interval = {'1h': 1, '6h': 5, '24h': 15, '7d': 60, '30d': 360}.get(period, 15) cutoff = datetime.utcnow() - timedelta(hours=hours_back) @@ -80,7 +108,7 @@ class FleetMonitorService: series = [] for server_id in server_ids: - server = Server.query.get(server_id) + server = _visible_server(user, server_id) if not server: continue @@ -113,9 +141,17 @@ class FleetMonitorService: # ==================== Alert Thresholds ==================== @staticmethod - def get_thresholds(server_id: str = None) -> List[Dict]: - """Get alert thresholds, optionally filtered by server.""" + def get_thresholds(user, server_id: str = None) -> List[Dict]: + """Get alert thresholds, optionally filtered by server. + + Global defaults (no server) are fleet policy and visible to everyone; + per-server overrides only for servers *user* can access.""" query = ServerAlertThreshold.query + if not user.is_admin: + query = query.filter( + (ServerAlertThreshold.server_id == None) | # noqa: E711 + ServerAlertThreshold.server_id.in_(_visible_server_ids(user)) + ) if server_id: query = query.filter( (ServerAlertThreshold.server_id == server_id) | @@ -286,11 +322,13 @@ class FleetMonitorService: @staticmethod def get_alerts( - status: str = None, severity: str = None, + user, status: str = None, severity: str = None, server_id: str = None, limit: int = 50 ) -> List[Dict]: - """Get metric alerts with filters.""" + """Get metric alerts for the servers *user* can access, with filters.""" query = MetricAlert.query.order_by(MetricAlert.created_at.desc()) + if not user.is_admin: + query = query.filter(MetricAlert.server_id.in_(_visible_server_ids(user))) if status: query = query.filter_by(status=status) if severity: @@ -322,9 +360,12 @@ class FleetMonitorService: # ==================== Anomaly Detection ==================== @staticmethod - def detect_anomalies(server_id: str = None) -> List[Dict]: + def detect_anomalies(user, server_id: str = None) -> List[Dict]: """Simple z-score anomaly detection on 7-day hourly averages.""" - servers = [Server.query.get(server_id)] if server_id else Server.query.filter_by(status='online').all() + if server_id: + servers = [_visible_server(user, server_id)] + else: + servers = _visible_servers(user).filter_by(status='online').all() cutoff = datetime.utcnow() - timedelta(days=7) anomalies = [] @@ -484,14 +525,14 @@ class FleetMonitorService: # ==================== Fleet Search ==================== @staticmethod - def search_fleet(query: str, search_type: str = 'any') -> List[Dict]: - """Search across all servers for containers, services, or ports.""" + def search_fleet(user, query: str, search_type: str = 'any') -> List[Dict]: + """Search the servers *user* can access for containers, services, or ports.""" query_lower = query.lower() results = [] # Search server names and hostnames if search_type in ('any', 'server'): - servers = Server.query.filter( + servers = _visible_servers(user).filter( (Server.name.ilike(f'%{query}%')) | (Server.hostname.ilike(f'%{query}%')) | (Server.ip_address.ilike(f'%{query}%')) @@ -510,7 +551,7 @@ class FleetMonitorService: if search_type in ('any', 'container'): connected = agent_registry.get_connected_servers() for server_id in connected: - server = Server.query.get(server_id) + server = _visible_server(user, server_id) if not server: continue @@ -536,7 +577,7 @@ class FleetMonitorService: # Search tags if search_type in ('any', 'tag'): - all_servers = Server.query.all() + all_servers = _visible_servers(user).all() for s in all_servers: if s.tags: for tag in s.tags: @@ -608,8 +649,8 @@ class FleetMonitorService: # ==================== CSV Export ==================== @staticmethod - def export_metrics_csv(server_ids: List[str], metric: str = 'cpu', period: str = '24h') -> str: - """Export metrics as CSV string.""" + def export_metrics_csv(user, server_ids: List[str], metric: str = 'cpu', period: str = '24h') -> str: + """Export metrics as CSV string, for the ids *user* can access.""" hours_back = {'1h': 1, '6h': 6, '24h': 24, '7d': 168, '30d': 720}.get(period, 24) cutoff = datetime.utcnow() - timedelta(hours=hours_back) col_name = METRIC_COLUMNS.get(metric, 'cpu_percent') @@ -619,7 +660,7 @@ class FleetMonitorService: writer.writerow(['timestamp', 'server_id', 'server_name', metric]) for server_id in server_ids: - server = Server.query.get(server_id) + server = _visible_server(user, server_id) if not server: continue diff --git a/backend/app/services/managed_database_service.py b/backend/app/services/managed_database_service.py index b4f226dc..e9ca040d 100644 --- a/backend/app/services/managed_database_service.py +++ b/backend/app/services/managed_database_service.py @@ -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 diff --git a/backend/app/services/previews/plan.py b/backend/app/services/previews/plan.py index 83dd3835..caebc9fa 100644 --- a/backend/app/services/previews/plan.py +++ b/backend/app/services/previews/plan.py @@ -12,8 +12,8 @@ class PreviewError(ValueError): def validate(app, preview, settings, git_config): if app.server_id or settings.target_server_id: raise PreviewError('Generic previews currently require a local server.') - if app.compose_file or app.managed_by in ('docker_compose', 'systemd'): - raise PreviewError('Compose and systemd previews are not supported by this provisioner.') + if app.compose_file or app.managed_by in ('docker_compose', 'systemd', 'host'): + raise PreviewError('Compose, systemd and host-managed previews are not supported by this provisioner.') if app.ingress_plane not in (None, '', 'nginx'): raise PreviewError('Generic previews currently require nginx ingress.') if not app.port or not 1 <= app.port <= 65535: diff --git a/backend/app/services/proxy_stack_service.py b/backend/app/services/proxy_stack_service.py index 7056ae29..0abd502d 100644 --- a/backend/app/services/proxy_stack_service.py +++ b/backend/app/services/proxy_stack_service.py @@ -478,10 +478,10 @@ class ProxyStackService: return None @staticmethod - def fleet_overview(): - """Fleet-wide proxy posture: one row per server. + def fleet_overview(user): + """Fleet-wide proxy posture: one row per server *user* can access. - Best-effort and guarded — never raises. Joins every ``Server`` with its + Best-effort and guarded — never raises. Joins each such ``Server`` with its ``ProxyStack`` (if one exists). Servers that never opted into a managed stack report the host-nginx default (``proxy_type='nginx'``, ``status='host'``) rather than being omitted, so the dashboard shows the @@ -499,7 +499,9 @@ class ProxyStackService: return [] try: - servers = Server.query.order_by(Server.name).all() + from app.services.workspace_service import WorkspaceService + servers = WorkspaceService.filter_accessible_servers( + Server.query, user).order_by(Server.name).all() except Exception as e: # pragma: no cover - DB guard logger.warning(f"fleet_overview server query failed: {e}") return [] diff --git a/backend/app/services/server_metrics_service.py b/backend/app/services/server_metrics_service.py index 12356b7f..e9919e87 100644 --- a/backend/app/services/server_metrics_service.py +++ b/backend/app/services/server_metrics_service.py @@ -13,7 +13,7 @@ from typing import Dict, List, Optional, Any from sqlalchemy import func, and_ from app import db -from app.models.server import ServerMetrics +from app.models.server import Server, ServerMetrics logger = logging.getLogger(__name__) @@ -284,28 +284,38 @@ class ServerMetricsService: return deleted @classmethod - def get_retention_stats(cls) -> Dict[str, Any]: - """Get statistics about metrics retention. + def get_retention_stats(cls, user) -> Dict[str, Any]: + """Get statistics about metrics retention, over the servers *user* + can access (admins: all of them). Returns: Dict with record counts, date ranges, and storage info """ try: - # Total count - total_count = ServerMetrics.query.count() - - # Count per server - server_counts = db.session.query( + from app.services.workspace_service import WorkspaceService + metrics = ServerMetrics.query + counts = db.session.query( ServerMetrics.server_id, func.count().label('count') - ).group_by(ServerMetrics.server_id).all() + ) + if not user.is_admin: + visible = WorkspaceService.filter_accessible_servers( + db.session.query(Server.id), user) + metrics = metrics.filter(ServerMetrics.server_id.in_(visible)) + counts = counts.filter(ServerMetrics.server_id.in_(visible)) + + # Total count + total_count = metrics.count() + + # Count per server + server_counts = counts.group_by(ServerMetrics.server_id).all() # Date range - oldest = ServerMetrics.query.order_by( + oldest = metrics.order_by( ServerMetrics.timestamp.asc() ).first() - newest = ServerMetrics.query.order_by( + newest = metrics.order_by( ServerMetrics.timestamp.desc() ).first() diff --git a/backend/app/services/site_adoption_service.py b/backend/app/services/site_adoption_service.py new file mode 100644 index 00000000..d4adea40 --- /dev/null +++ b/backend/app/services/site_adoption_service.py @@ -0,0 +1,541 @@ +"""Adopt sites that already run on this host (issue #269). + +A site that was set up by hand, by a script or by a migration serves traffic +through host nginx but has no row in ``applications`` / ``domains`` / +``wordpress_sites``, so the panel cannot see it: no monitoring, backups, SSL +status or logs. The other entry points all *create* something — a vhost, a +copy of the files — which is the wrong thing to do to a site that is already +live. + +This module only ever READS the host: the live nginx config, the PHP-FPM +pools, the certificate files and ``wp-config.php``. Adopting writes database +rows and nothing else. The resulting application carries +``managed_by='host'``, which the vhost writer, the lifecycle and the delete +path all honour by leaving the running config alone +(``Application.is_host_managed``). + +``discover()`` doubles as the drift report: every site it returns without a +``linked_app`` is one serving traffic that the panel does not know about. +""" +import glob +import logging +import os +import re +from datetime import datetime + +from app import db +from app.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//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) diff --git a/backend/app/services/site_domain_service.py b/backend/app/services/site_domain_service.py index a5d61abc..b7cdf06a 100644 --- a/backend/app/services/site_domain_service.py +++ b/backend/app/services/site_domain_service.py @@ -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 diff --git a/backend/app/services/totp_service.py b/backend/app/services/totp_service.py index 28f9afbf..24a4f351 100644 --- a/backend/app/services/totp_service.py +++ b/backend/app/services/totp_service.py @@ -191,20 +191,32 @@ class TwoFactorSetup: def __init__(self, user): self.user = user - def initiate_setup(self): + def initiate_setup(self, regenerate=False): """ - Start 2FA setup by generating a new secret. + Start 2FA setup, reusing the pending unconfirmed secret if there is one. + + A new secret is minted only when none is pending or ``regenerate`` is + set, so repeated Enable clicks keep the secret the user already scanned. + A confirmed secret is never rotated here. Returns: dict: Setup data including secret and QR code """ from app import db - # Generate new secret (don't enable yet) - secret = TOTPService.generate_secret() - self.user.totp_secret = secret + # Serialize on the user row so concurrent /setup calls see one secret. + # (No-op on SQLite, where writes are already serialized.) + db.session.refresh(self.user, with_for_update=True) - # Don't enable until verified + if self.user.totp_enabled: + from app.exceptions import ConflictError + raise ConflictError('2FA is already enabled') + + secret = self.user.totp_secret + if regenerate or not secret: + secret = TOTPService.generate_secret() + self.user.totp_secret = secret + # Don't enable until verified; commit also releases the row lock. db.session.commit() # Generate QR code diff --git a/backend/cli.py b/backend/cli.py index 99530a00..7fa4d1d5 100644 --- a/backend/cli.py +++ b/backend/cli.py @@ -854,6 +854,122 @@ def _api_client(with_token=True): return ApiClient(token=token) +@cli.command('adopt-site') +@click.argument('site', required=False) +@click.option('--apply', 'apply_', is_flag=True, + help='Register the site. Without it, only show what would be recorded.') +@click.option('--name', default=None, help='Service name (default: derived from the domain)') +@click.option('--json', 'as_json', is_flag=True, help='Output machine-readable JSON') +def adopt_site(site, apply_, name, as_json): + """Register a site that already runs on this server. + + With no SITE, lists every site host nginx serves and whether ServerKit + manages it. With a SITE (a domain or a vhost file name), shows what + adopting it would record: a dry run. Add --apply to register it. + + Nothing on the server is rewritten either way: adopting records the + running nginx vhost, PHP-FPM pool, database and certificate as they are. + """ + from app.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 --apply') + sites = site_adoption_service.discover() + if as_json: + _echo_json({'sites': sites}) + return + if not sites: + click.echo('\n Host nginx is not serving any sites.\n') + return + click.echo(f"\n{'Domain':<34} {'Type':<10} {'PHP':<6} {'SSL':<4} {'State'}") + click.echo('-' * 90) + for found in sites: + if found['linked_app']: + state = f"managed as {found['linked_app']['name']}" + elif found['adoptable']: + state = 'not managed (adoptable)' + else: + state = f"not managed: {found['reason']}" + click.echo( + f"{found['primary_domain']:<34} " + f"{(found['app_type'] or found['kind']):<10} " + f"{((found['php'] or {}).get('version') or '-'):<6} " + f"{('yes' if found['ssl']['enabled'] else 'no'):<4} " + f"{state}" + ) + adoptable = sum(1 for found in sites if found['adoptable']) + click.echo(f"\n{adoptable} site(s) can be adopted: serverkit adopt-site \n") + return + + found = site_adoption_service.find(site) + if found is None: + _fail(f'No site served by host nginx matches "{site}". ' + "Run 'serverkit adopt-site' to list them.") + plan = site_adoption_service.plan(found, name) + + if not apply_: + if as_json: + _echo_json({'dry_run': True, 'adoptable': found['adoptable'], + 'reason': found['reason'], 'plan': plan}) + return + _print_adoption_plan(found, plan) + if found['adoptable']: + click.echo(f"\nDry run. Nothing was changed. To register it:\n" + f" serverkit adopt-site {site} --apply\n") + else: + click.echo(click.style(f"\nCannot adopt: {found['reason']}\n", fg='yellow')) + return + + owner = User.query.filter_by(role='admin', is_active=True).order_by(User.id).first() + if owner is None: + _fail("No active admin user to own the service. Run 'serverkit create-admin' first.") + try: + application, plan = site_adoption_service.adopt(site, owner, name=name) + except 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) diff --git a/backend/tests/api_controller_boundary_baseline.json b/backend/tests/api_controller_boundary_baseline.json index d651fe08..f1ce16e6 100644 --- a/backend/tests/api_controller_boundary_baseline.json +++ b/backend/tests/api_controller_boundary_baseline.json @@ -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", diff --git a/backend/tests/test_backup_hook_authz.py b/backend/tests/test_backup_hook_authz.py new file mode 100644 index 00000000..076c67d1 --- /dev/null +++ b/backend/tests/test_backup_hook_authz.py @@ -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, '') diff --git a/backend/tests/test_cli_adopt_site.py b/backend/tests/test_cli_adopt_site.py new file mode 100644 index 00000000..c71d2cd6 --- /dev/null +++ b/backend/tests/test_cli_adopt_site.py @@ -0,0 +1,73 @@ +"""`serverkit adopt-site` — the CLI face of site adoption (issue #269). + +Dry run by default: naming a site prints what would be recorded and changes +nothing; only `--apply` registers it. The host fixture and the "nothing on +the host changed" snapshot come from test_site_adoption.py. +""" +import json + +import pytest +from click.testing import CliRunner + +from factories import make_user +from test_site_adoption import _snapshot, host # noqa: F401 (fixture) + + +@pytest.fixture +def run(app, monkeypatch): + """Invoke the Click command against the test app instead of a fresh one.""" + import cli + monkeypatch.setattr(cli, 'create_app', lambda *args, **kwargs: app) + + def invoke(*args): + return CliRunner().invoke(cli.cli, ['adopt-site', *args], catch_exceptions=False) + return invoke + + +def test_no_argument_lists_sites_with_their_state(run, host): # noqa: F811 + result = run() + assert result.exit_code == 0, result.output + assert 'shop.example.com' in result.output and 'wordpress' in result.output + assert 'not managed (adoptable)' in result.output + assert '2 site(s) can be adopted' in result.output + listed = json.loads(run('--json').output)['sites'] + assert {site['primary_domain'] for site in listed} == { + 'shop.example.com', 'docs.example.com', 'api.example.com'} + + +def test_naming_a_site_is_a_dry_run(run, host): # noqa: F811 + from app.models.application import Application + before = _snapshot(host['root']) + result = run('shop.example.com') + assert result.exit_code == 0, result.output + assert 'Dry run. Nothing was changed.' in result.output + assert 'serverkit adopt-site shop.example.com --apply' in result.output + assert 'Left exactly as it is:' in result.output + assert Application.query.filter_by(name='shop-example-com').first() is None + assert _snapshot(host['root']) == before + + +def test_apply_registers_the_site_and_leaves_the_host_alone(run, host, app): # noqa: F811 + from app import db + from app.models.application import Application + make_user(db, 'cli_adopt_admin', 'admin') + before = _snapshot(host['root']) + result = run('docs.example.com', '--apply', '--name', 'docs-site') + assert result.exit_code == 0, result.output + assert 'Adopted as "docs-site"' in result.output + row = Application.query_active().filter_by(name='docs-site').one() + assert (row.managed_by, row.app_type, row.status) == ('host', 'static', 'running') + assert _snapshot(host['root']) == before + + +def test_refusals_exit_non_zero_and_register_nothing(run, host, app): # noqa: F811 + from app import db + from app.models.application import Application + make_user(db, 'cli_adopt_admin2', 'admin') + count = Application.query.count() + assert run('nope.example.com').exit_code == 1 + # A proxied process is described, but --apply refuses it. + assert run('api.example.com').exit_code == 0 + assert run('api.example.com', '--apply').exit_code == 1 + assert run('--apply').exit_code == 1 + assert Application.query.count() == count diff --git a/backend/tests/test_fleet_metrics_batching.py b/backend/tests/test_fleet_metrics_batching.py index 7d7b07d3..55b9e994 100644 --- a/backend/tests/test_fleet_metrics_batching.py +++ b/backend/tests/test_fleet_metrics_batching.py @@ -8,6 +8,7 @@ from sqlalchemy import event from app import db from app.models.server import Server, ServerMetrics +from factories import make_user from app.services.fleet_monitor_service import FleetMonitorService from app.services.server_metrics_service import latest_metrics_by_server @@ -79,10 +80,11 @@ def test_each_fleet_reader_uses_one_metrics_query( # Arrives later, but describes an older observation. seed_sample(server, now - timedelta(hours=1), 20) db.session.commit() + admin = make_user(db, role='admin') with metric_queries() as queries: if reader == 'heatmap': - result = FleetMonitorService.get_fleet_heatmap() + result = FleetMonitorService.get_fleet_heatmap(admin) assert len(result) == size assert all(row['cpu'] == 10 for row in result) elif reader == 'prometheus': @@ -115,7 +117,7 @@ def test_heatmap_keeps_group_scope_and_missing_metrics(app, db_session): included.group_id = group.id seed_server('excluded') db.session.commit() - result = FleetMonitorService.get_fleet_heatmap(group.id) + result = FleetMonitorService.get_fleet_heatmap(make_user(db, role='admin'), group.id) assert len(result) == 1 assert result[0]['id'] == included.id assert result[0]['group_name'] == 'selected' diff --git a/backend/tests/test_fleet_proxy.py b/backend/tests/test_fleet_proxy.py index 7e5fbe0a..b39450cb 100644 --- a/backend/tests/test_fleet_proxy.py +++ b/backend/tests/test_fleet_proxy.py @@ -13,6 +13,13 @@ from app.services.proxy_stack_service import ProxyStackService as PS from app.models.proxy_stack import ProxyStack # noqa: F401 +def _admin(): + """The overview is scoped to its caller; an admin sees the whole fleet.""" + from app import db + from factories import make_user + return make_user(db, role='admin') + + def _make_server(name, agent_id): from app import db from app.models.server import Server @@ -28,7 +35,7 @@ def _make_server(name, agent_id): def test_fleet_overview_empty_when_no_servers(app): with app.app_context(): - assert PS.fleet_overview() == [] + assert PS.fleet_overview(_admin()) == [] def test_fleet_overview_one_row_per_server(app): @@ -37,7 +44,7 @@ def test_fleet_overview_one_row_per_server(app): sid_b = _make_server('bravo', 'agent-fp-b') sid_c = _make_server('charlie', 'agent-fp-c') - overview = PS.fleet_overview() + overview = PS.fleet_overview(_admin()) # A row for every server, even ones that never opted into a stack. assert len(overview) == 3 ids = {row['server_id'] for row in overview} @@ -61,7 +68,7 @@ def test_fleet_overview_one_row_per_server(app): def test_fleet_overview_host_default_for_unconfigured(app): with app.app_context(): sid = _make_server('hostonly', 'agent-fp-host') - overview = PS.fleet_overview() + overview = PS.fleet_overview(_admin()) assert len(overview) == 1 row = overview[0] # No managed stack → host nginx, status 'host'. @@ -80,7 +87,7 @@ def test_fleet_overview_reflects_configured_stack(app): # Configure one server onto a managed Traefik stack. PS.configure(sid_traefik, proxy_type='traefik') - overview = PS.fleet_overview() + overview = PS.fleet_overview(_admin()) by_id = {row['server_id']: row for row in overview} # Configured server reflects its stack type; not the host default. @@ -120,7 +127,7 @@ def test_fleet_overview_recommendation_levels(app): # info: a stack server running with no apps yet. PS.switch(sid_idle_stack, 'caddy') - rows = {r['server_id']: r for r in PS.fleet_overview()} + rows = {r['server_id']: r for r in PS.fleet_overview(_admin())} warn = rows[sid_warn]['recommendation'] assert warn['level'] == 'warn' diff --git a/backend/tests/test_fleet_read_workspace_access.py b/backend/tests/test_fleet_read_workspace_access.py new file mode 100644 index 00000000..788a0d8a --- /dev/null +++ b/backend/tests/test_fleet_read_workspace_access.py @@ -0,0 +1,206 @@ +"""Fleet-wide READ routes obey the same workspace rule as /servers +(GHSA-qcjj-hf95-6rgw). + +`test_server_workspace_access.py` sweeps every `` route. The +routes here take no id in the path — they list, search or export across the +fleet, or take ids in the query string — so that sweep never reached them and +they answered from unfiltered `Server` / `ServerMetrics` queries. +""" +import re +from datetime import datetime, timedelta + +import pytest + +from factories import headers_for, make_server, make_user + +NAME = 'frw-tenantb-billing-db' +HOST = 'frw-billing.internal' +IP = '10.99.77.5' +CONTAINER = 'frw-ledger-postgres' +TAG = 'frw-pci-scope' + + +@pytest.fixture +def setup(app): + from app import db + from app.models.metric_alert import MetricAlert, ServerAlertThreshold + from app.models.server import ServerGroup, ServerMetrics + from app.services.workspace_service import WorkspaceService + + admin = make_user(db, 'frw_admin', 'admin') + member = make_user(db, 'frw_member', 'developer') + outsider = make_user(db, 'frw_outsider', 'developer') + viewer = make_user(db, 'frw_viewer', 'viewer') + ws = WorkspaceService.create_workspace({'name': 'FRW'}, admin.id) + WorkspaceService.add_member(ws.id, member.id) + WorkspaceService.create_workspace({'name': 'FRW-out'}, outsider.id) + + # Groups are fleet-wide labels, so a foreign server can sit in one. + group = ServerGroup(name='frw-group') + db.session.add(group) + db.session.commit() + server = make_server(db, name=NAME, hostname=HOST, ip_address=IP, + status='online', tags=[TAG], workspace_id=ws.id, + group_id=group.id) + # A flat week with a spike at the end: enough samples for the comparison + # and export routes, and an outlier for the anomaly detector. + now = datetime.utcnow() + for i in range(30): + last = i == 29 + db.session.add(ServerMetrics( + server_id=server.id, + timestamp=now - timedelta(minutes=(29 - i) * 20), + cpu_percent=99.0 if last else 10.0 + (i % 2), + memory_percent=88.2, disk_percent=91.4, + extra={'containers': [{'name': CONTAINER, 'image': 'postgres:16', + 'status': 'running'}]})) + db.session.add(MetricAlert(server_id=server.id, metric='cpu', + severity='critical', value=99.0, threshold=95.0)) + db.session.add(ServerAlertThreshold(server_id=server.id, metric='cpu')) + db.session.add(ServerAlertThreshold(server_id=None, metric='disk')) + db.session.commit() + return {'server': server.id, 'group': group.id, 'admin': admin.id, + 'member': member.id, 'outsider': outsider.id, 'viewer': viewer.id} + + +def _leaks(setup, text): + return [needle for needle in (setup['server'], NAME, HOST, IP, CONTAINER, TAG) + if needle in text] + + +def _fleet_reads(sid, gid): + return [ + f'/api/v1/servers/groups/{gid}', + '/api/v1/servers/proxy/overview', + '/api/v1/fleet-monitor/heatmap', + f'/api/v1/fleet-monitor/comparison?ids={sid}&metric=cpu&period=24h', + '/api/v1/fleet-monitor/alerts', + f'/api/v1/fleet-monitor/alerts?server_id={sid}', + '/api/v1/fleet-monitor/thresholds', + f'/api/v1/fleet-monitor/thresholds?server_id={sid}', + '/api/v1/fleet-monitor/anomalies', + f'/api/v1/fleet-monitor/anomalies?server_id={sid}', + '/api/v1/fleet-monitor/search?q=frw-', + '/api/v1/fleet-monitor/search?q=10.99', + '/api/v1/fleet-monitor/search?q=frw-ledger&type=container', + '/api/v1/fleet-monitor/search?q=frw-pci&type=tag', + f'/api/v1/fleet-monitor/export/csv?ids={sid}&metric=memory', + f'/api/v1/fleet-monitor/export/json?ids={sid}&metric=cpu', + '/api/v1/mobile/offline-cache', + ] + + +# Developer-only reads: a viewer is refused outright, before any scoping. +_DEVELOPER_READS = ['/api/v1/servers/metrics/retention'] + + +@pytest.mark.parametrize('who', ['outsider', 'viewer']) +def test_non_member_reads_nothing_about_a_foreign_server(client, setup, who): + leaked = {} + with _connected(setup['server']): + for url in _fleet_reads(setup['server'], setup['group']) + _DEVELOPER_READS: + resp = client.get(url, headers=headers_for(setup[who])) + if who == 'viewer' and url in _DEVELOPER_READS: + assert resp.status_code == 403, (url, resp.status_code) + else: + assert resp.status_code == 200, (url, resp.status_code) + found = _leaks(setup, resp.get_data(as_text=True)) + if found: + leaked[url] = found + assert not leaked, leaked + + +@pytest.mark.parametrize('who', ['member', 'admin']) +def test_member_and_admin_still_read_their_server(client, setup, who): + """The fix narrows, it must not blank the page for people who belong.""" + missing = [] + with _connected(setup['server']): + for url in _fleet_reads(setup['server'], setup['group']) + _DEVELOPER_READS: + resp = client.get(url, headers=headers_for(setup[who])) + assert resp.status_code == 200, (url, resp.status_code) + if not _leaks(setup, resp.get_data(as_text=True)): + missing.append(url) + assert not missing, missing + + +def test_global_thresholds_stay_visible_to_everyone(client, setup): + """A threshold with no server is fleet policy, not a tenant's data.""" + rows = client.get('/api/v1/fleet-monitor/thresholds', + headers=headers_for(setup['outsider'])).get_json() + assert [r['metric'] for r in rows] == ['disk'] + assert rows[0]['server_id'] is None + + +def test_mobile_summary_counts_only_accessible_servers(client, setup): + def count(who): + return client.get('/api/v1/mobile/summary', + headers=headers_for(setup[who])).get_json()['servers'] + assert count('member') == count('outsider') + 1 + assert count('admin') == count('member') + + +def test_comparison_keeps_accessible_ids_and_drops_foreign_ones(client, setup, app): + """A mixed id list answers for the caller's own servers only — the foreign + id is dropped silently, exactly as an unknown id already was.""" + from app import db + from app.models.server import ServerMetrics + own = make_server(db, name='frw-shared-box') + db.session.add(ServerMetrics(server_id=own.id, cpu_percent=5.0)) + db.session.commit() + body = client.get( + f"/api/v1/fleet-monitor/comparison?ids={setup['server']},{own.id}", + headers=headers_for(setup['outsider'])).get_json() + assert [s['server_id'] for s in body['series']] == [own.id] + + +def _connected(server_id): + from unittest.mock import patch + return patch('app.services.agent_registry.agent_registry.get_connected_servers', + return_value=[server_id]) + + +def test_group_member_count_stops_at_accessible_servers(client, setup): + def count(who): + rows = client.get('/api/v1/servers/groups', + headers=headers_for(setup[who])).get_json() + return next(r['server_count'] for r in rows if r['id'] == setup['group']) + assert (count('outsider'), count('member'), count('admin')) == (0, 1, 1) + + +def _fleet_get_rules(app, setup): + """Every GET route with no path parameter, plus the ones keyed by a server + group. `` routes have their own sweep in + test_server_workspace_access.py.""" + for rule in app.url_map.iter_rules(): + if not rule.rule.startswith('/api/v1/') or 'GET' not in rule.methods: + continue + url = rule.rule.replace('', setup['group']) + if '<' in url: + continue + yield url + + +def test_no_fleet_read_route_leaks_a_foreign_server(app, client, setup): + """Sweep: whatever list/search/export/summary route exists — including one + added after this test — a developer outside the workspace never gets the + foreign server's id, name, hostname, IP, tag or container back. The + member test above proves those needles are reachable through the same + routes, so an empty answer here is the filter and not a blank fixture.""" + sid = setup['server'] + # Ask for the foreign server every way a route might accept: an id-taking + # route answers for it, a search route matches it, the rest ignore it. + query = f'?ids={sid}&server_id={sid}&q=frw-&query=frw-&search=frw-' + leaks = [] + with _connected(sid): + for rule in sorted(set(_fleet_get_rules(app, setup))): + url = rule + query + try: + resp = client.get(url, headers=headers_for(setup['outsider'])) + except Exception as exc: # a route that crashes is not a leak + if re.search('frw-', str(exc)): + leaks.append(f'GET {url} raised with the server in it') + continue + found = _leaks(setup, resp.get_data(as_text=True)) + if found: + leaks.append(f'GET {url} -> {resp.status_code} {found}') + assert not leaks, '\n'.join(leaks) diff --git a/backend/tests/test_ingress_plane.py b/backend/tests/test_ingress_plane.py index bb0e529d..c830dce1 100644 --- a/backend/tests/test_ingress_plane.py +++ b/backend/tests/test_ingress_plane.py @@ -104,7 +104,10 @@ def test_fleet_overview_reports_mismatch_counts(app): s = _make_server(app, 'fleet-srv') ProxyStackService.switch(s.id, 'caddy') _make_app(s.id, 'php', name='php-site') # nginx plane on a caddy server -> mismatch - rows = {r['server_id']: r for r in ProxyStackService.fleet_overview()} + from app import db + from factories import make_user + admin = make_user(db, role='admin') + rows = {r['server_id']: r for r in ProxyStackService.fleet_overview(admin)} row = rows[s.id] assert row['proxy_type'] == 'caddy' assert row['app_count'] == 1 diff --git a/backend/tests/test_nginx_acme_challenge_location.py b/backend/tests/test_nginx_acme_challenge_location.py new file mode 100644 index 00000000..912b97a9 --- /dev/null +++ b/backend/tests/test_nginx_acme_challenge_location.py @@ -0,0 +1,49 @@ +"""The shipped nginx configs must let Let's Encrypt HTTP-01 through (issue #269). + +Each vhost denies dotfiles with the regex location ``location ~ /\\.``. That +regex also matches ``/.well-known/acme-challenge/``, and nginx prefers +a matching regex location over a plain prefix location — so a plain +``location /.well-known/acme-challenge/`` in the same server block loses and +the challenge answers 403. Issuance and renewal then fail, and a hand fix was +undone by the next ``serverkit update`` re-copying the shipped file. + +``^~`` on the prefix location tells nginx to stop there and skip the regex +pass, which is the only form that wins. +""" +import re +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] + +CONFIGS = [ + ROOT / 'nginx' / 'nginx.conf', + ROOT / 'nginx' / 'sites-available' / 'serverkit.conf', + ROOT / 'nginx' / 'sites-available' / 'serverkit-insecure.conf', + ROOT / 'nginx' / 'sites-available' / 'example.conf.template', +] + +_ACME = re.compile(r'^\s*location\s+(?P\S+\s+)?/\.well-known/acme-challenge/\s*\{', + re.MULTILINE) +_DOTFILE_DENY = re.compile(r'^\s*location\s+~\*?\s+/\\\.\s*\{', re.MULTILINE) + + +@pytest.mark.parametrize('config', CONFIGS, ids=lambda p: p.name) +def test_acme_challenge_location_beats_the_dotfile_deny(config): + text = config.read_text(encoding='utf-8') + locations = list(_ACME.finditer(text)) + assert locations, f'{config.name}: no ACME challenge location to serve HTTP-01' + for match in locations: + assert (match.group('modifier') or '').strip() == '^~', ( + f'{config.name}: the ACME challenge location must be ' + f'`location ^~ /.well-known/acme-challenge/` or the dotfile deny wins') + + +def test_the_collision_this_guards_is_real(): + """At least one shipped server block carries both locations — the plain + HTTP vhost — so the modifier is load-bearing, not decoration.""" + text = (ROOT / 'nginx' / 'sites-available' / 'serverkit-insecure.conf').read_text( + encoding='utf-8') + assert _ACME.search(text) and _DOTFILE_DENY.search(text) + assert text.count('server {') == 1 diff --git a/backend/tests/test_server_workspace_write_cap.py b/backend/tests/test_server_workspace_write_cap.py new file mode 100644 index 00000000..73c7e71c --- /dev/null +++ b/backend/tests/test_server_workspace_write_cap.py @@ -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 `` 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 '' not in rule.rule or not rule.rule.startswith('/api/v1/'): + continue + url = rule.rule.replace('', sid) + url = re.sub(r']+>', '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) diff --git a/backend/tests/test_shared_variables_read_authz.py b/backend/tests/test_shared_variables_read_authz.py new file mode 100644 index 00000000..b891aaf0 --- /dev/null +++ b/backend/tests/test_shared_variables_read_authz.py @@ -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 diff --git a/backend/tests/test_site_adoption.py b/backend/tests/test_site_adoption.py new file mode 100644 index 00000000..ec02f87b --- /dev/null +++ b/backend/tests/test_site_adoption.py @@ -0,0 +1,377 @@ +"""Adopting a site that already runs on the host (issue #269). + +The contract under test: discovery reads the live nginx / PHP-FPM / WordPress +config and describes each site; adopting writes database rows and NOTHING on +the host; and once adopted, no panel path rewrites or removes the config that +is serving the site. +""" +import hashlib +from unittest.mock import patch + +import pytest + +from factories import headers_for, make_user + +WP_CONFIG = """= 400 + assert 'host-managed' in resp.get_data(as_text=True) + assert adopted.status == 'running' + + +def test_deleting_an_adopted_site_forgets_it_but_keeps_it_serving(client, admin, adopted, host): + from app.models.application import Application + before = _snapshot(host['root']) + # Mocks, not raising stubs: the delete path catches exceptions per step, + # so a raise would be swallowed and this would pass with the guard removed. + with patch('app.services.nginx_service.NginxService.disable_site') as disable_site, \ + patch('app.services.nginx_service.NginxService.delete_site') as delete_site: + resp = client.delete(f'/api/v1/apps/{adopted.id}', headers=headers_for(admin)) + assert resp.status_code == 200, resp.get_json() + disable_site.assert_not_called() + delete_site.assert_not_called() + assert Application.query_active().filter_by(id=adopted.id).first() is None + assert _snapshot(host['root']) == before + + +def test_status_follows_nginx_and_never_guesses(app, adopted): + from app import db + from app.api.apps import _sync_manual_app_status + probe = 'app.services.process_service.ProcessService.get_systemd_unit_status' + with patch(probe, return_value={'success': True, 'status': 'inactive', 'active': False}): + _sync_manual_app_status(adopted) + assert adopted.status == 'stopped' + with patch(probe, return_value={'success': True, 'status': 'active', 'active': True}): + _sync_manual_app_status(adopted) + assert adopted.status == 'running' + # No systemd to ask (a dev box): keep what we knew. + with patch(probe, return_value={'success': True, 'status': 'unknown', 'active': False}): + _sync_manual_app_status(adopted) + assert adopted.status == 'running' + db.session.rollback() + + +def test_manual_route_accepts_host_for_sites_only(client, admin, host): + ok = client.post('/api/v1/apps/manual', headers=headers_for(admin), json={ + 'name': 'docs-manual', 'app_type': 'static', 'root_path': host['docs_root'], + 'managed_by': 'host'}) + assert ok.status_code == 201, ok.get_json() + assert ok.get_json()['app']['managed_by'] == 'host' + bad = client.post('/api/v1/apps/manual', headers=headers_for(admin), json={ + 'name': 'api-manual', 'app_type': 'docker', 'root_path': host['docs_root'], + 'managed_by': 'host'}) + assert bad.status_code == 400 + + +# ------------------------------------------------------------- drift report + +def test_doctor_reports_unmanaged_sites_until_they_are_adopted(client, host, admin): + from app.services.doctor_service import DoctorService + + def unmanaged(): + return {check['key']: check for check in DoctorService._unmanaged_site_checks()} + + checks = unmanaged() + assert set(checks) == {'sites.unmanaged.shop.example.com.conf', + 'sites.unmanaged.docs.example.com.conf', + 'sites.unmanaged.api.example.com.conf'} + shop = checks['sites.unmanaged.shop.example.com.conf'] + assert shop['status'] == 'warn' and not shop['repairable'] + assert 'serverkit adopt-site shop.example.com --apply' in shop['detail'] + # A proxied process is still reported, with why it is not adopted here. + assert 'Docker Compose or systemd' in checks['sites.unmanaged.api.example.com.conf']['detail'] + + client.post('/api/v1/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() == [] diff --git a/backend/tests/test_totp_service.py b/backend/tests/test_totp_service.py index ee248b04..f44f2c85 100644 --- a/backend/tests/test_totp_service.py +++ b/backend/tests/test_totp_service.py @@ -9,6 +9,8 @@ from werkzeug.security import generate_password_hash from app import db from app.models import User from app.services.totp_service import TOTPService, TwoFactorSetup +from app.exceptions import ConflictError +from factories import headers_for @pytest.fixture @@ -172,3 +174,69 @@ def test_regenerate_backup_codes_replaces_old_set(user): assert ok and len(new) == 10 assert not old_hashes & set(user.get_backup_codes()) assert setup.regenerate_backup_codes('abc') == (False, 'Invalid verification code') + + +def test_qr_code_is_built_from_the_provisioning_uri(secret, monkeypatch): + from app.services import totp_service + if not totp_service.HAS_QRCODE: + pytest.skip('qrcode not installed') + added = [] + real = totp_service.qrcode.QRCode + + class Spy(real): + def add_data(self, data, *a, **kw): + added.append(data) + return super().add_data(data, *a, **kw) + + monkeypatch.setattr(totp_service.qrcode, 'QRCode', Spy) + TOTPService.generate_qr_code_base64(secret, 'me@example.com') + assert added == [TOTPService.get_provisioning_uri(secret, 'me@example.com')] + parsed = urlparse(added[0]) + assert parsed.scheme == 'otpauth' and parsed.netloc == 'totp' + assert parse_qs(parsed.query) == {'secret': [secret], 'issuer': ['ServerKit']} + + +def test_second_initiate_reuses_pending_secret_and_confirm_works(user): + setup = TwoFactorSetup(user) + first = setup.initiate_setup() + second = TwoFactorSetup(user).initiate_setup() + assert second['secret'] == first['secret'] == user.totp_secret + assert second['uri'] == first['uri'] and second['issuer'] == 'ServerKit' + assert not user.totp_enabled + ok, _ = setup.confirm_setup(TOTPService.get_current_code(first['secret'])) + assert ok and user.totp_enabled + + +def test_regenerate_mints_new_secret_only_while_unconfirmed(user): + setup = TwoFactorSetup(user) + first = setup.initiate_setup()['secret'] + second = setup.initiate_setup(regenerate=True)['secret'] + assert second != first and user.totp_secret == second + setup.confirm_setup(TOTPService.get_current_code(second)) + with pytest.raises(ConflictError): + setup.initiate_setup(regenerate=True) + assert user.totp_secret == second + + +def test_setup_endpoint_reuses_secret_until_regenerate(client, user): + url = '/api/v1/auth/2fa/setup' + a = client.post(url, headers=headers_for(user)).get_json() + b = client.post(url, headers=headers_for(user)).get_json() + assert a['secret'] == b['secret'] and a['uri'] == b['uri'] + assert client.get('/api/v1/auth/2fa/status', headers=headers_for(user)).get_json()['enabled'] is False + c = client.post(url, json={'regenerate': True}, headers=headers_for(user)).get_json() + assert c['secret'] != a['secret'] + confirm = client.post(url + '/confirm', headers=headers_for(user), + json={'code': TOTPService.get_current_code(c['secret'])}) + assert confirm.status_code == 200 + + +def test_setup_endpoint_rejects_confirmed_user_without_rotating(client, user): + TwoFactorSetup(user).initiate_setup() + secret = user.totp_secret + TwoFactorSetup(user).confirm_setup(TOTPService.get_current_code(secret)) + for body in (None, {'regenerate': True}): + r = client.post('/api/v1/auth/2fa/setup', json=body, headers=headers_for(user)) + assert r.status_code == 400 + db.session.refresh(user) + assert user.totp_secret == secret and user.totp_enabled diff --git a/docs/API_SURFACE.md b/docs/API_SURFACE.md index 56c8c308..b93a4b07 100644 --- a/docs/API_SURFACE.md +++ b/docs/API_SURFACE.md @@ -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` diff --git a/docs/COEXISTENCE.md b/docs/COEXISTENCE.md index 50a6951d..5d57e56e 100644 --- a/docs/COEXISTENCE.md +++ b/docs/COEXISTENCE.md @@ -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 --apply`. + ## 3. Manage — full takeover on a clean box Today's normal mode: ServerKit owns the box and manages the web stack end to diff --git a/docs/MIGRATION_INVENTORY.md b/docs/MIGRATION_INVENTORY.md index 951bc903..760d1798 100644 --- a/docs/MIGRATION_INVENTORY.md +++ b/docs/MIGRATION_INVENTORY.md @@ -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 | diff --git a/frontend/src/components/Modal.jsx b/frontend/src/components/Modal.jsx index 28516053..c962bb7a 100644 --- a/frontend/src/components/Modal.jsx +++ b/frontend/src/components/Modal.jsx @@ -1,5 +1,6 @@ import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'; import { cn } from '@/lib/utils'; +import { dismissGuards } from '@/components/ui/dismissGuards'; // Generic modal built on the Radix Dialog primitive. SCSS owns all geometry // (styles/components/_ui.scss → .sk-modal*). `size` picks a max-width on @@ -12,6 +13,9 @@ import { cn } from '@/lib/utils'; // to the bottom of the scrolling body, and a nested .modal-body adds no extra // padding or scroller. Two-column .form-row stacks in narrow modals. // +// closeOnDismiss={false}: overlay click and Escape no longer close the modal +// (for flows that would lose in-progress state); explicit buttons still do. +// // Form mode: pass `onSubmit` and the body AND footer // are wrapped in one
. This exists because a submit button must live // inside the form it submits — without it, every modal with a form had to @@ -27,6 +31,7 @@ export default function Modal({ onSubmit, className = '', size = 'md', + closeOnDismiss = true, }) { const body = ( <> @@ -42,7 +47,7 @@ export default function Modal({ return ( !v && onClose()}> - + {title && (
{title} diff --git a/frontend/src/components/apps/AdoptSitesDialog.jsx b/frontend/src/components/apps/AdoptSitesDialog.jsx new file mode 100644 index 00000000..717f7ed0 --- /dev/null +++ b/frontend/src/components/apps/AdoptSitesDialog.jsx @@ -0,0 +1,131 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import api from '@/services/api'; +import Modal from '@/components/Modal'; +import { Button } from '@/components/ui/button'; +import { Pill } from '@/components/ds'; +import { useToast } from '@/contexts/useToast.js'; +import { toastError } from '@/utils/errorMessage'; + +// Sites host nginx is serving that no service accounts for. Each row shows +// what discovery found; adopting records the site as it is. Nothing on the +// server is rewritten, which the dialog says in so many words because that is +// the question anyone with a live site asks first. +export default function AdoptSitesDialog({ open, onClose, sites, onAdopted }) { + const { t } = useTranslation(); + const toast = useToast(); + const [adopting, setAdopting] = useState(null); + + const kindLabel = (site) => ({ + wordpress: t('app.services.adopt.kindWordpress', 'WordPress'), + php: t('app.services.adopt.kindPhp', 'PHP'), + static: t('app.services.adopt.kindStatic', 'Static'), + }[site.app_type] || (site.kind === 'proxy' + ? t('app.services.adopt.kindProxy', 'Proxied app') + : t('app.services.adopt.kindRedirect', 'Redirect'))); + + async function handleAdopt(site) { + setAdopting(site.id); + try { + const result = await api.adoptHostSite(site.id, { apply: true }); + toast.success(t('app.services.adopt.adopted', { + name: result?.app?.name || site.primary_domain, + defaultValue: '{{name}} is now managed. Nothing on the server was changed.', + })); + await onAdopted?.(result?.app); + } catch (err) { + toastError(toast, t('app.services.adopt.failed', "Couldn't adopt this site."), err); + } finally { + setAdopting(null); + } + } + + return ( + + {t('common.actions.close', 'Close')} + + )} + > +

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

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

    {site.reason}

    + )} +
    + {site.adoptable && ( + + )} +
  • + ))} +
+
+ ); +} diff --git a/frontend/src/components/settings/SecuritySettingsTab.jsx b/frontend/src/components/settings/SecuritySettingsTab.jsx index dc6c7874..92033443 100644 --- a/frontend/src/components/settings/SecuritySettingsTab.jsx +++ b/frontend/src/components/settings/SecuritySettingsTab.jsx @@ -1,10 +1,11 @@ -import { useState, useEffect, useId } from 'react'; +import { useState, useEffect, useId, useRef } from 'react'; import { useAuth } from '../../contexts/useAuth.js'; import api from '../../services/api'; import useSettingFocus from '../../hooks/useSettingFocus'; import TwoFactorPolicyCard from './TwoFactorPolicyCard'; import SSOProviderIcon from '../SSOProviderIcon'; import Modal from '../Modal'; +import { createSingleFlight } from '@/utils/singleFlight'; import ErrorState from '../ErrorState'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; @@ -155,6 +156,8 @@ const SecuritySettingsTab = () => { const [backupCodes, setBackupCodes] = useState([]); const [twoFAError, setTwoFAError] = useState(''); const [twoFALoadError, setTwoFALoadError] = useState(null); + const [confirmFailed, setConfirmFailed] = useState(false); + const initiateFlight = useRef(createSingleFlight()).current; useEffect(() => { load2FAStatus(); @@ -204,21 +207,25 @@ const SecuritySettingsTab = () => { } } - async function handleInitiate2FA() { - setTwoFAError(''); - setTwoFALoading(true); - try { - const data = await api.initiate2FASetup(); - setSetupData(data); - setShowSetupModal(true); - window.dispatchEvent(new CustomEvent('serverkit:walkthrough-signal', { - detail: { type: 'two-factor-setup-started' }, - })); - } catch (err) { - setTwoFAError(err.message); - } finally { - setTwoFALoading(false); - } + // The ref lock refuses a double-click before `twoFALoading` flushes. + function handleInitiate2FA() { + return initiateFlight(async () => { + setTwoFAError(''); + setConfirmFailed(false); + setTwoFALoading(true); + try { + const data = await api.initiate2FASetup(); + setSetupData(data); + setShowSetupModal(true); + window.dispatchEvent(new CustomEvent('serverkit:walkthrough-signal', { + detail: { type: 'two-factor-setup-started' }, + })); + } catch (err) { + setTwoFAError(err.message); + } finally { + setTwoFALoading(false); + } + }); } async function handleConfirm2FA() { @@ -229,6 +236,7 @@ const SecuritySettingsTab = () => { setTwoFALoading(true); setTwoFAError(''); + setConfirmFailed(false); try { const result = await api.confirm2FASetup(verificationCode); setBackupCodes(result.backup_codes); @@ -240,6 +248,7 @@ const SecuritySettingsTab = () => { detail: { type: 'two-factor-enabled' }, })); } catch (err) { + setConfirmFailed(true); setTwoFAError(err.message || t('auth.codeMismatch', "That code didn't match. Enter the current 6-digit code from your authenticator app.")); } finally { setTwoFALoading(false); @@ -455,7 +464,7 @@ Keep these codes in a safe place.`; {/* 2FA Setup Modal */} {showSetupModal && setupData && ( - setShowSetupModal(false)} title={t('app.securitySettingsTab.setUpTwoFactorAuthentication', 'Set up two-factor authentication')} size="md"> + setShowSetupModal(false)} closeOnDismiss={false} title={t('app.securitySettingsTab.setUpTwoFactorAuthentication', 'Set up two-factor authentication')} size="md">
1 @@ -494,6 +503,7 @@ Keep these codes in a safe place.`; autoFocus /> {twoFAError &&

{twoFAError}

} + {confirmFailed &&

{t('app.securitySettingsTab.codeMayBeFromOlderQr', 'The code may be from an older QR. Use the code for the QR currently on screen.')}

}
diff --git a/frontend/src/components/setup/SetupStepSecurity.jsx b/frontend/src/components/setup/SetupStepSecurity.jsx index 601da5db..9835df0e 100644 --- a/frontend/src/components/setup/SetupStepSecurity.jsx +++ b/frontend/src/components/setup/SetupStepSecurity.jsx @@ -1,4 +1,4 @@ -import { useState, useEffect } from 'react'; +import { useState, useEffect, useRef } from 'react'; import { ShieldCheck, Download, AlertTriangle, Check, Loader } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; @@ -7,6 +7,7 @@ import CopyField from '../CopyField'; import { downloadBlob } from '@/utils/downloadBlob'; import { useTranslation } from 'react-i18next'; import InfoTip from '@/components/InfoTip'; +import { createSingleFlight } from '@/utils/singleFlight'; // Enrolment is a three-beat flow. Offer is the default so someone who just // wants a dashboard is one click from moving on — 2FA is offered here because @@ -28,6 +29,8 @@ const SetupStepSecurity = ({ onComplete }) => { const [savedCodes, setSavedCodes] = useState(false); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); + const [confirmFailed, setConfirmFailed] = useState(false); + const enableFlight = useRef(createSingleFlight()).current; // Stepping back to Capacity and forward again re-mounts this step, but the // enrolment already landed server-side — re-offering it would just 400. @@ -45,18 +48,22 @@ const SetupStepSecurity = ({ onComplete }) => { }; }, []); - async function handleEnable() { - setBusy(true); - setError(''); - try { - const data = await api.initiate2FASetup(); - setSetupData(data); - setStage(STAGE_ENROLL); - } catch (err) { - setError(err.message || 'Could not start two-factor setup.'); - } finally { - setBusy(false); - } + // The ref lock refuses a double-click before `busy` flushes. + function handleEnable() { + return enableFlight(async () => { + setBusy(true); + setError(''); + setConfirmFailed(false); + try { + const data = await api.initiate2FASetup(); + setSetupData(data); + setStage(STAGE_ENROLL); + } catch (err) { + setError(err.message || 'Could not start two-factor setup.'); + } finally { + setBusy(false); + } + }); } async function handleConfirm() { @@ -66,11 +73,13 @@ const SetupStepSecurity = ({ onComplete }) => { } setBusy(true); setError(''); + setConfirmFailed(false); try { const result = await api.confirm2FASetup(code); setBackupCodes(result.backup_codes || []); setStage(STAGE_CODES); } catch (err) { + setConfirmFailed(true); setError(err.message || 'That code did not match. Try the next one.'); } finally { setBusy(false); @@ -221,7 +230,10 @@ const SetupStepSecurity = ({ onComplete }) => { {error && (
-
{error}
+
+ {error} + {confirmFailed && <> {t('app.securitySettingsTab.codeMayBeFromOlderQr', 'The code may be from an older QR. Use the code for the QR currently on screen.')}} +
)} diff --git a/frontend/src/components/ui/dismissGuards.js b/frontend/src/components/ui/dismissGuards.js new file mode 100644 index 00000000..71e6f624 --- /dev/null +++ b/frontend/src/components/ui/dismissGuards.js @@ -0,0 +1,9 @@ +// Radix Dialog props that stop overlay click / Escape from closing a dialog. +// Explicit close buttons (Cancel, the header X) still work. +const block = (event) => event.preventDefault(); + +export function dismissGuards(closeOnDismiss = true) { + return closeOnDismiss + ? {} + : { onPointerDownOutside: block, onInteractOutside: block, onEscapeKeyDown: block }; +} diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json index 0b5df0ce..fefd1f07 100644 --- a/frontend/src/i18n/locales/ar.json +++ b/frontend/src/i18n/locales/ar.json @@ -5265,6 +5265,7 @@ "changePassword": "تغيير كلمة المرور", "changing": "جارٍ التغيير…", "codeFromAuthenticatorOrBackupCode": "رمز من المصادقة أو رمز النسخ الاحتياطي", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "تأكيد كلمة المرور الجديدة", "confirmNewPassword2": "تأكيد كلمة المرور الجديدة", "connectExternalIdentityProvidersToYour": "قم بتوصيل موفري الهوية الخارجيين بحسابك", diff --git a/frontend/src/i18n/locales/bn.json b/frontend/src/i18n/locales/bn.json index ff8d184d..1cd7be17 100644 --- a/frontend/src/i18n/locales/bn.json +++ b/frontend/src/i18n/locales/bn.json @@ -5265,6 +5265,7 @@ "changePassword": "পাসওয়ার্ড পরিবর্তন করুন", "changing": "পরিবর্তন করা হচ্ছে…", "codeFromAuthenticatorOrBackupCode": "প্রমাণীকরণকারী বা ব্যাকআপ কোড থেকে কোড", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "নতুন পাসওয়ার্ড নিশ্চিত করুন", "confirmNewPassword2": "নতুন পাসওয়ার্ড নিশ্চিত করুন", "connectExternalIdentityProvidersToYour": "আপনার অ্যাকাউন্টে বহিরাগত পরিচয় প্রদানকারীকে সংযুক্ত করুন", diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.json index fd22a483..b70c40bc 100644 --- a/frontend/src/i18n/locales/de.json +++ b/frontend/src/i18n/locales/de.json @@ -5265,6 +5265,7 @@ "changePassword": "Passwort ändern", "changing": "Wird geändert…", "codeFromAuthenticatorOrBackupCode": "Code vom Authentifikator oder Backup-Code", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Bestätigen Sie das neue Passwort", "confirmNewPassword2": "Neues Passwort bestätigen", "connectExternalIdentityProvidersToYour": "Verbinden Sie externe Identitätsanbieter mit Ihrem Konto", diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json index d085560d..4812f927 100644 --- a/frontend/src/i18n/locales/en.json +++ b/frontend/src/i18n/locales/en.json @@ -5500,6 +5500,7 @@ "changePassword": "Change password", "changing": "Changing…", "codeFromAuthenticatorOrBackupCode": "Code from authenticator or backup code", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Confirm new password", "confirmNewPassword2": "Confirm new password", "connectExternalIdentityProvidersToYour": "Connect external identity providers to your account", @@ -6005,6 +6006,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 +6053,30 @@ "wordpress": "WordPress" }, "services": { + "adopt": { + "action": "Adopt", + "adopted": "{{name}} is now managed. Nothing on the server was changed.", + "adopting": "Adopting…", + "alsoServes": "Also serves", + "button": "Adopt ({{count}})", + "buttonTitle": "Sites running on this server that are not managed here yet", + "certificate": "Certificate", + "database": "Database", + "failed": "Couldn't adopt this site.", + "intro": "These sites are served by this server but are not managed here yet, so they have no monitoring, backups or SSL status. Adopting one records it as it is: the nginx config, PHP-FPM pool, database and certificate are left exactly as they are.", + "kindPhp": "PHP", + "kindProxy": "Proxied app", + "kindRedirect": "Redirect", + "kindStatic": "Static", + "kindWordpress": "WordPress", + "noCertificate": "None", + "php": "PHP-FPM", + "root": "Document root", + "title": "Adopt existing sites", + "unknownVersion": "Unknown version", + "upstream": "Proxies to", + "vhost": "nginx config" + }, "assignSelected_one": "Assign 1 selected service to a project and environment, or leave it unassigned.", "assignSelected_other": "Assign {{count}} selected services to a project and environment, or leave them unassigned.", "bulkRestartSent_one": "Restart sent to 1 service", diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json index c0c120c6..4db43646 100644 --- a/frontend/src/i18n/locales/es.json +++ b/frontend/src/i18n/locales/es.json @@ -5266,6 +5266,7 @@ "changePassword": "Cambiar contraseña", "changing": "Cambiando…", "codeFromAuthenticatorOrBackupCode": "Código de la app de autenticación o código de recuperación", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Confirmar nueva contraseña", "confirmNewPassword2": "Confirma la nueva contraseña", "connectExternalIdentityProvidersToYour": "Conecta proveedores de identidad externos a tu cuenta", diff --git a/frontend/src/i18n/locales/fr.json b/frontend/src/i18n/locales/fr.json index f52b4065..c64dbbd7 100644 --- a/frontend/src/i18n/locales/fr.json +++ b/frontend/src/i18n/locales/fr.json @@ -5265,6 +5265,7 @@ "changePassword": "Changer le mot de passe", "changing": "Modification…", "codeFromAuthenticatorOrBackupCode": "Code de l'authentificateur ou code de sauvegarde", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Confirmer le nouveau mot de passe", "confirmNewPassword2": "Confirmer le nouveau mot de passe", "connectExternalIdentityProvidersToYour": "Connectez des fournisseurs d'identité externes à votre compte", diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.json index b0257724..5671cbca 100644 --- a/frontend/src/i18n/locales/id.json +++ b/frontend/src/i18n/locales/id.json @@ -5265,6 +5265,7 @@ "changePassword": "Ubah Kata Sandi", "changing": "Mengubah…", "codeFromAuthenticatorOrBackupCode": "Kode dari pengautentikasi atau kode cadangan", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Konfirmasi Kata Sandi Baru", "confirmNewPassword2": "Konfirmasikan kata sandi baru", "connectExternalIdentityProvidersToYour": "Hubungkan penyedia identitas eksternal ke akun Anda", diff --git a/frontend/src/i18n/locales/it.json b/frontend/src/i18n/locales/it.json index 5f425bf8..9c30a8d0 100644 --- a/frontend/src/i18n/locales/it.json +++ b/frontend/src/i18n/locales/it.json @@ -5265,6 +5265,7 @@ "changePassword": "Cambiare la password", "changing": "Modifica…", "codeFromAuthenticatorOrBackupCode": "Codice dall'autenticatore o codice di backup", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Conferma nuova password", "confirmNewPassword2": "Conferma la nuova password", "connectExternalIdentityProvidersToYour": "Connetti i provider di identità esterni al tuo account", diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json index 732fb643..a8e119d1 100644 --- a/frontend/src/i18n/locales/ko.json +++ b/frontend/src/i18n/locales/ko.json @@ -5265,6 +5265,7 @@ "changePassword": "비밀번호 변경", "changing": "변경 중…", "codeFromAuthenticatorOrBackupCode": "인증자의 코드 또는 백업 코드", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "새 비밀번호 확인", "confirmNewPassword2": "새 비밀번호 확인", "connectExternalIdentityProvidersToYour": "외부 ID 공급자를 계정에 연결", diff --git a/frontend/src/i18n/locales/pl.json b/frontend/src/i18n/locales/pl.json index e5523fd9..9db6a6fd 100644 --- a/frontend/src/i18n/locales/pl.json +++ b/frontend/src/i18n/locales/pl.json @@ -5265,6 +5265,7 @@ "changePassword": "Zmień hasło", "changing": "Zmienianie…", "codeFromAuthenticatorOrBackupCode": "Kod z uwierzytelniacza lub kod zapasowy", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Potwierdź nowe hasło", "confirmNewPassword2": "Potwierdź nowe hasło", "connectExternalIdentityProvidersToYour": "Połącz zewnętrznych dostawców tożsamości ze swoim kontem", diff --git a/frontend/src/i18n/locales/pt.json b/frontend/src/i18n/locales/pt.json index eacf9acb..7dd30cdc 100644 --- a/frontend/src/i18n/locales/pt.json +++ b/frontend/src/i18n/locales/pt.json @@ -5265,6 +5265,7 @@ "changePassword": "Alterar senha", "changing": "Alterando…", "codeFromAuthenticatorOrBackupCode": "Código do autenticador ou código de backup", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Confirme a nova senha", "confirmNewPassword2": "Confirme a nova senha", "connectExternalIdentityProvidersToYour": "Conecte provedores de identidade externos à sua conta", diff --git a/frontend/src/i18n/locales/ru.json b/frontend/src/i18n/locales/ru.json index e19f0759..6220132a 100644 --- a/frontend/src/i18n/locales/ru.json +++ b/frontend/src/i18n/locales/ru.json @@ -5265,6 +5265,7 @@ "changePassword": "Изменить пароль", "changing": "Изменение…", "codeFromAuthenticatorOrBackupCode": "Код из аутентификатора или резервный код", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Подтвердите новый пароль", "confirmNewPassword2": "Подтвердите новый пароль", "connectExternalIdentityProvidersToYour": "Подключите внешних поставщиков удостоверений к своей учетной записи", diff --git a/frontend/src/i18n/locales/th.json b/frontend/src/i18n/locales/th.json index f37fbf74..72316914 100644 --- a/frontend/src/i18n/locales/th.json +++ b/frontend/src/i18n/locales/th.json @@ -5265,6 +5265,7 @@ "changePassword": "เปลี่ยนรหัสผ่าน", "changing": "กำลังเปลี่ยน…", "codeFromAuthenticatorOrBackupCode": "รหัสจากตัวตรวจสอบสิทธิ์หรือรหัสสำรอง", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "ยืนยันรหัสผ่านใหม่", "confirmNewPassword2": "ยืนยันรหัสผ่านใหม่", "connectExternalIdentityProvidersToYour": "เชื่อมต่อผู้ให้บริการข้อมูลประจำตัวภายนอกกับบัญชีของคุณ", diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.json index a3c5af47..2f676879 100644 --- a/frontend/src/i18n/locales/tr.json +++ b/frontend/src/i18n/locales/tr.json @@ -5265,6 +5265,7 @@ "changePassword": "Şifre değiştir", "changing": "Değiştiriliyor…", "codeFromAuthenticatorOrBackupCode": "Kimlik doğrulayıcıdan veya yedek koddan gelen kod", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Yeni Şifreyi Onayla", "confirmNewPassword2": "Yeni şifreyi onayla", "connectExternalIdentityProvidersToYour": "Harici kimlik sağlayıcılarını hesabınıza bağlayın", diff --git a/frontend/src/i18n/locales/vi.json b/frontend/src/i18n/locales/vi.json index c6914af5..a57db882 100644 --- a/frontend/src/i18n/locales/vi.json +++ b/frontend/src/i18n/locales/vi.json @@ -5265,6 +5265,7 @@ "changePassword": "Thay đổi mật khẩu", "changing": "Đang thay đổi…", "codeFromAuthenticatorOrBackupCode": "Mã từ trình xác thực hoặc mã dự phòng", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "Xác nhận mật khẩu mới", "confirmNewPassword2": "Xác nhận mật khẩu mới", "connectExternalIdentityProvidersToYour": "Kết nối nhà cung cấp danh tính bên ngoài với tài khoản của bạn", diff --git a/frontend/src/i18n/locales/zh-Hans.json b/frontend/src/i18n/locales/zh-Hans.json index 232ba85f..e8230970 100644 --- a/frontend/src/i18n/locales/zh-Hans.json +++ b/frontend/src/i18n/locales/zh-Hans.json @@ -5265,6 +5265,7 @@ "changePassword": "更改密码", "changing": "正在更改…", "codeFromAuthenticatorOrBackupCode": "来自验证器或备份代码的代码", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "确认新密码", "confirmNewPassword2": "确认新密码", "connectExternalIdentityProvidersToYour": "将外部身份提供商连接到您的帐户", diff --git a/frontend/src/i18n/locales/zh-Hant.json b/frontend/src/i18n/locales/zh-Hant.json index f939350d..2017bd5f 100644 --- a/frontend/src/i18n/locales/zh-Hant.json +++ b/frontend/src/i18n/locales/zh-Hant.json @@ -5265,6 +5265,7 @@ "changePassword": "更改密碼", "changing": "正在變更…", "codeFromAuthenticatorOrBackupCode": "驗證器或備用驗證碼", + "codeMayBeFromOlderQr": "The code may be from an older QR. Use the code for the QR currently on screen.", "confirmNewPassword": "確認新密碼", "confirmNewPassword2": "確認新密碼", "connectExternalIdentityProvidersToYour": "將外部身分提供者連線到您的帳戶", diff --git a/frontend/src/pages/ServiceDetail.jsx b/frontend/src/pages/ServiceDetail.jsx index 2d5954d8..21b6cd90 100644 --- a/frontend/src/pages/ServiceDetail.jsx +++ b/frontend/src/pages/ServiceDetail.jsx @@ -476,7 +476,7 @@ const ServiceDetail = () => { {service.managed_by && ( <> → - {service.managed_by === 'docker_compose' ? t('app.serviceDetail.dockerCompose', 'Docker Compose') : 'systemd'} + {managedByLabel(service.managed_by, t)} )} @@ -585,6 +585,14 @@ const ServiceDetail = () => { ); }; +// How a locally registered service is run. `host` is a site that was already +// being served by this server's nginx when it was adopted. +function managedByLabel(managedBy, t) { + if (managedBy === 'docker_compose') return t('app.serviceDetail.dockerCompose', 'Docker Compose'); + if (managedBy === 'host') return t('app.serviceDetail.hostManaged', 'Host nginx'); + return 'systemd'; +} + function extractRepoDisplay(url) { if (!url) return ''; try { diff --git a/frontend/src/pages/Services.jsx b/frontend/src/pages/Services.jsx index 03a185c4..ce4c7e29 100644 --- a/frontend/src/pages/Services.jsx +++ b/frontend/src/pages/Services.jsx @@ -1,6 +1,6 @@ import { useCallback, useState, useEffect, useMemo } from 'react'; import { useNavigate, Link } from 'react-router-dom'; -import { Layers, Plus, Square, Play, RotateCw, GitBranch, FolderOpen, FileArchive, FolderKanban, ArrowDownToLine } from 'lucide-react'; +import { Layers, Plus, Square, Play, RotateCw, GitBranch, FolderOpen, FileArchive, FolderKanban, ArrowDownToLine, ScanSearch } from 'lucide-react'; import { SiGithub as Github } from 'react-icons/si'; import api from '../services/api'; import { useToast } from '../contexts/useToast.js'; @@ -23,6 +23,8 @@ import { } from '@/components/ui/select'; import Modal from '@/components/Modal'; import RequiresDocker from '../components/RequiresDocker'; +import AdoptSitesDialog from '@/components/apps/AdoptSitesDialog'; +import { useAuth } from '@/contexts/useAuth.js'; import { useTranslation } from 'react-i18next'; import { toastError } from '@/utils/errorMessage'; import { translateLabel } from '@/i18n/labels'; @@ -120,6 +122,22 @@ const Services = () => { const [bulkLoading, setBulkLoading] = useState(false); const [showMoveDialog, setShowMoveDialog] = useState(false); const [bandwidth, setBandwidth] = useState({}); + const { isAdmin } = useAuth(); + // Sites this server's nginx is serving that no service accounts for. + const [unmanagedSites, setUnmanagedSites] = useState([]); + const [showAdoptDialog, setShowAdoptDialog] = useState(false); + + // Best-effort and admin-only (the endpoint reads host config): a failure + // just means the Adopt button does not appear. + const loadUnmanagedSites = useCallback(async () => { + if (!isAdmin) return; + try { + const data = await api.getHostSites(); + setUnmanagedSites((data?.sites || []).filter((site) => !site.linked_app && site.kind !== 'redirect')); + } catch { + setUnmanagedSites([]); + } + }, [isAdmin]); const loadApps = useCallback(async () => { try { @@ -141,6 +159,10 @@ const Services = () => { .catch(() => {}); }, [loadApps]); + useEffect(() => { + loadUnmanagedSites(); + }, [loadUnmanagedSites]); + async function handleAction(e, appId, action) { e.stopPropagation(); @@ -203,6 +225,17 @@ const Services = () => { useTopbarActions(() => <> + {unmanagedSites.length > 0 && ( + + )}