diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e447d1f..6357b9da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,15 @@ release history; historical `agent-v*` tags are not panel releases. ### Added +- Agent permission levels (Monitor / Protect / Full), enforced by the agent and + reported to the panel. Adds a signed `POST /api/v1/agent/report` endpoint for + report-only Monitor agents, per-server level and service-check state (server + list badge and health, server detail panel), offline / service-down alerts + through the existing fleet alerts and notification channels, audited level + changes, and a panel-side command gate. The panel cannot set the level; it is + changed on the server with `serverkit-agent permissions set`. See + [docs/AGENT_PERMISSION_LEVELS.md](docs/AGENT_PERMISSION_LEVELS.md). Migration + 112. The Add Server commands now pass `--level` / `-Level`. - `GET /api/v1/servers` now accepts an API key (`X-API-Key`) carrying the `servers:read` scope, in addition to the usual JWT, so external tools can poll the server list read-only without a short-lived token. JWT callers are diff --git a/SECURITY.md b/SECURITY.md index 2c693641..15da1660 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -7,8 +7,8 @@ release line and the `main` branch. | Version | Supported | |---------|-----------| -| 1.7.x | ✅ | -| < 1.7 | ❌ (please upgrade) | +| 1.11.x | ✅ | +| < 1.11 | ❌ (please upgrade) | The **agent** ships from its own repository, `jhd3197/serverkit-agent`, and is versioned independently (`vX.Y.Z` — it used `agent-vX.Y.Z` while it lived in this @@ -47,6 +47,12 @@ trust boundaries: (`system:exec`) and interactive PTY sessions are controlled by the agent's `Features.Exec` flag, which is **off by default**. Enable it only on servers where you intend the panel to run shell commands. +- **Permission levels bound what a compromised panel can do.** An agent runs as + Monitor (report-only, no inbound command channel), Protect (security allowlist + only) or Full. The level is read only from the agent's local config and can + only be changed on the server (`serverkit-agent permissions set`); the panel + records and audits the reported level but has no API to set it. See + [docs/AGENT_PERMISSION_LEVELS.md](docs/AGENT_PERMISSION_LEVELS.md). - **Transport & connection controls.** Agents authenticate to the panel with per-connection HMAC-SHA256 (with nonce/replay protection and a timestamp-skew check), and the panel enforces a per-server IP allowlist. Use `wss://` @@ -137,6 +143,13 @@ carry a `sink-safe: — ` comment. `scripts/check-html-sinks.mj fails CI on any new unannotated sink, so a raw-HTML injection point can't land silently. +## Known Limitations + +- **Tokens in `localStorage`.** The SPA keeps its JWT access/refresh tokens in + `localStorage`, so an XSS bug would expose them. The production CSP now + forbids inline and `eval` scripts (`script-src 'self'`) to reduce that risk; + planned follow-up: move tokens to `httpOnly` `SameSite` cookies with CSRF protection. + ## Extension Trust Model Extensions are **in-process code**. An installed extension runs with the panel's diff --git a/VERSION b/VERSION index c7b3d9fd..b85d56fb 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.11.37 +1.11.38 diff --git a/backend/app/agent_gateway.py b/backend/app/agent_gateway.py index cefc2de4..7dfb17fa 100644 --- a/backend/app/agent_gateway.py +++ b/backend/app/agent_gateway.py @@ -136,7 +136,10 @@ class AgentNamespace(Namespace): return metrics = data.get('metrics', {}) - agent_registry.ingest_agent_state(agent, metrics=metrics) + agent_registry.ingest_agent_state( + agent, metrics=metrics, + permission_level=data.get('permission_level'), + service_checks=data.get('service_checks')) emit('heartbeat_ack', {'type': 'heartbeat_ack'}) diff --git a/backend/app/api/advanced_ssl.py b/backend/app/api/advanced_ssl.py index e8045663..dd949d93 100644 --- a/backend/app/api/advanced_ssl.py +++ b/backend/app/api/advanced_ssl.py @@ -1,3 +1,4 @@ +import logging from flask import Blueprint, request, jsonify from flask_jwt_extended import jwt_required from app.services.advanced_ssl_service import AdvancedSSLService @@ -6,6 +7,8 @@ from app.models.audit_log import AuditLog from app.middleware.rbac import get_current_user from app.api._request import json_object +logger = logging.getLogger(__name__) + advanced_ssl_bp = Blueprint('advanced_ssl', __name__) @@ -79,8 +82,9 @@ def upload_cert(): try: result = AdvancedSSLService.upload_custom_cert(domain, cert, key, chain) return jsonify(result), 201 - except Exception as e: - return jsonify({'error': str(e)}), 400 + except Exception: + logger.exception('Custom certificate upload failed') + return jsonify({'error': 'Could not install the certificate'}), 400 @advanced_ssl_bp.route('/health/', methods=['GET']) diff --git a/backend/app/api/agent_poll.py b/backend/app/api/agent_poll.py index e63f27bd..11451655 100644 --- a/backend/app/api/agent_poll.py +++ b/backend/app/api/agent_poll.py @@ -108,7 +108,9 @@ def poll(): # Shared transport-neutral ingest: capability # side-effects (e.g. tunnel reconcile) fire exactly as on the WS path. agent_registry.ingest_agent_state(agent, metrics=metrics, sysinfo=sysinfo, - capabilities=caps) + capabilities=caps, + permission_level=body.get('permission_level'), + service_checks=body.get('service_checks')) # Long-poll up to 25s for any queued command. Below the typical # tunnel idle-timeout (Cloudflare ~100s, ngrok ~60s) so we never diff --git a/backend/app/api/agent_report.py b/backend/app/api/agent_report.py new file mode 100644 index 00000000..958c2321 --- /dev/null +++ b/backend/app/api/agent_report.py @@ -0,0 +1,56 @@ +"""Monitor-mode agent report endpoint. + +``POST /api/v1/agent/report`` is the ONLY channel a monitor-level agent uses: +a signed, outbound-only HTTPS POST. The reply never carries commands. + +Auth (no JWT/CSRF; the HMAC is the credential): + X-Agent-Key: -> server looked up by its key prefix + X-Timestamp: -> |skew| <= 300s + X-Nonce: =32 chars> -> single use (TTL cache, 5 min) + X-Signature: hex(HMAC_SHA256(api_secret, ts + "." + nonce + "." + sha256hex(body))) +""" + +from flask import Blueprint, jsonify, request + +from app import limiter +from app.exceptions import ( + AuthenticationError, PayloadTooLargeError, PermissionDeniedError, ValidationError, +) +from app.services import agent_health_service, permission_levels +from app.utils.ip_utils import is_ip_allowed + + +agent_report_bp = Blueprint('agent_report', __name__) + +MAX_BODY_BYTES = 64 * 1024 +MAX_SKEW_SECONDS = 300 + + +def _rate_key(): + return f"{request.remote_addr}:{(request.headers.get('X-Agent-Key') or '')[:12]}" + + +@agent_report_bp.route('/report', methods=['POST']) +@limiter.limit("30 per minute", key_func=_rate_key) +def report(): + if (request.content_length or 0) > MAX_BODY_BYTES: + raise PayloadTooLargeError() + raw = request.get_data(cache=True) + if len(raw) > MAX_BODY_BYTES: + raise PayloadTooLargeError() + + server = agent_health_service.authenticate_report(raw, request.headers, MAX_SKEW_SECONDS) + if not server: + raise AuthenticationError('authentication failed') + if server.allowed_ips and not is_ip_allowed(request.remote_addr, server.allowed_ips): + raise PermissionDeniedError('IP not allowed') + + body = request.get_json(silent=True) + if not isinstance(body, dict): + raise ValidationError('JSON object required') + level = body.get('permission_level') + if level not in permission_levels.LEVELS: + raise ValidationError('permission_level must be monitor, protect or full') + + interval = agent_health_service.ingest_report(server, level, body) + return jsonify({'ok': True, 'interval_seconds': interval}) diff --git a/backend/app/api/backups.py b/backend/app/api/backups.py index 609304a4..9578f935 100644 --- a/backend/app/api/backups.py +++ b/backend/app/api/backups.py @@ -1,3 +1,4 @@ +import logging import os from flask import Blueprint, request, jsonify from flask_jwt_extended import jwt_required @@ -7,10 +8,21 @@ from app.services.backup_service import BackupService from app.services.backup_policy_service import BackupPolicyService, BackupPolicyError from app.services.storage_provider_service import StorageProviderService from app import db, paths -from app.exceptions import field_required, not_found +from app.exceptions import DependencyUnavailableError, field_required, not_found from app.api._request import json_object backups_bp = Blueprint('backups', __name__) +logger = logging.getLogger(__name__) + +_STORAGE_UNAVAILABLE = ('Backup storage is not accessible: the panel cannot create or read ' + 'its backup directory. Check its ownership and permissions.') + + +@backups_bp.errorhandler(PermissionError) +def _backup_dir_unavailable(exc): + logger.error('Backup directory is not writable: %s', exc) + err = DependencyUnavailableError('Backup directory is not writable', code='backup_dir_unavailable') + return jsonify(err.to_dict()), err.status_code # UI-facing metadata for the CORE target types. Extension kinds @@ -62,7 +74,12 @@ def list_target_types(): def list_backups(): """List all backups.""" backup_type = request.args.get('type') - backups = BackupService.list_backups(backup_type) + try: + backups = BackupService.list_backups(backup_type) + except OSError: + # e.g. PermissionError creating /var/backups/serverkit: keep the page usable. + logger.exception('Backup directory is not accessible') + return jsonify({'backups': [], 'warning': _STORAGE_UNAVAILABLE}), 200 return jsonify({'backups': backups}), 200 @@ -70,7 +87,14 @@ def list_backups(): @admin_required def get_stats(): """Get backup statistics.""" - stats = BackupService.get_backup_stats() + try: + stats = BackupService.get_backup_stats() + except OSError: + logger.exception('Backup directory is not accessible') + stats = {'total_backups': 0, 'application_backups': 0, 'database_backups': 0, + 'file_backups': 0, 'total_size': 0, 'total_size_human': '0 B', + 'remote_count': 0, 'remote_size': 0, 'remote_size_human': '0 B', + 'warning': _STORAGE_UNAVAILABLE} return jsonify(stats), 200 diff --git a/backend/app/api/buildpacks.py b/backend/app/api/buildpacks.py index 2eec6ad8..55d0bb7c 100644 --- a/backend/app/api/buildpacks.py +++ b/backend/app/api/buildpacks.py @@ -12,6 +12,7 @@ Two endpoints: * POST /generate — pure: given a plan dict, return Dockerfile + compose. """ +import logging import os import shutil import tempfile @@ -25,6 +26,8 @@ from app.services.source_connection_service import SourceConnectionService from app.middleware.rbac import developer_required, get_current_user from app.api._request import json_object +logger = logging.getLogger(__name__) + buildpacks_bp = Blueprint('buildpacks', __name__) @@ -113,8 +116,9 @@ def detect(): plan = BuildpackService.detect(clone_target) BuildpackService.cache_plan(cache_key_url, plan, commit or branch) return jsonify(_build_response(plan, app_name)), 200 - except Exception as exc: # pragma: no cover - defensive - return jsonify({'error': str(exc)}), 400 + except Exception: # pragma: no cover - defensive + logger.exception('Buildpack detection failed') + return jsonify({'error': 'Could not detect a build plan for this repository'}), 400 finally: shutil.rmtree(workdir, ignore_errors=True) diff --git a/backend/app/api/docker.py b/backend/app/api/docker.py index 86fcc648..7aeec0b4 100644 --- a/backend/app/api/docker.py +++ b/backend/app/api/docker.py @@ -1,3 +1,5 @@ +import logging + from flask import Blueprint, request, jsonify from flask_jwt_extended import jwt_required, get_jwt_identity from app.models import User, Application @@ -7,6 +9,8 @@ from app import db, paths from app.error_reporting import unexpected_response from app.api._request import json_object +logger = logging.getLogger(__name__) + docker_bp = Blueprint('docker', __name__) @@ -505,8 +509,9 @@ def docker_cleanup(): } else: results['containers'] = {'removed': 0, 'success': True} - except Exception as e: - results['containers'] = {'error': str(e)} + except Exception: + logger.exception('Docker cleanup step failed') + results['containers'] = {'error': 'Cleanup step failed; see server log'} # Remove dangling images try: @@ -515,8 +520,9 @@ def docker_cleanup(): 'success': result['success'], 'output': result['output'].strip() } - except Exception as e: - results['images'] = {'error': str(e)} + except Exception: + logger.exception('Docker cleanup step failed') + results['images'] = {'error': 'Cleanup step failed; see server log'} # Remove unused networks try: @@ -525,8 +531,9 @@ def docker_cleanup(): 'success': result['success'], 'output': result['output'].strip() } - except Exception as e: - results['networks'] = {'error': str(e)} + except Exception: + logger.exception('Docker cleanup step failed') + results['networks'] = {'error': 'Cleanup step failed; see server log'} # Remove unused volumes (optional) if include_volumes: @@ -536,8 +543,9 @@ def docker_cleanup(): 'success': result['success'], 'output': result['output'].strip() } - except Exception as e: - results['volumes'] = {'error': str(e)} + except Exception: + logger.exception('Docker cleanup step failed') + results['volumes'] = {'error': 'Cleanup step failed; see server log'} else: results['volumes'] = {'skipped': True, 'message': 'Volume cleanup not requested'} @@ -581,24 +589,27 @@ def cleanup_all_apps(): try: compose_result = DockerService.compose_down(app.root_path, volumes=True, remove_orphans=True) app_result['steps'].append({'action': 'docker_down', 'success': compose_result.get('success', False)}) - except Exception as e: - app_result['steps'].append({'action': 'docker_down', 'error': str(e)}) + except Exception: + logger.exception('App cleanup step failed') + app_result['steps'].append({'action': 'docker_down', 'error': 'Step failed; see server log'}) app_result['success'] = False # Delete folder try: shutil.rmtree(app.root_path) app_result['steps'].append({'action': 'delete_folder', 'success': True}) - except Exception as e: - app_result['steps'].append({'action': 'delete_folder', 'error': str(e)}) + except Exception: + logger.exception('App cleanup step failed') + app_result['steps'].append({'action': 'delete_folder', 'error': 'Step failed; see server log'}) app_result['success'] = False # Remove from database try: db.session.delete(app) app_result['steps'].append({'action': 'delete_db', 'success': True}) - except Exception as e: - app_result['steps'].append({'action': 'delete_db', 'error': str(e)}) + except Exception: + logger.exception('App cleanup step failed') + app_result['steps'].append({'action': 'delete_db', 'error': 'Step failed; see server log'}) app_result['success'] = False results.append(app_result) diff --git a/backend/app/api/plugins.py b/backend/app/api/plugins.py index 2d753db5..0e749499 100644 --- a/backend/app/api/plugins.py +++ b/backend/app/api/plugins.py @@ -643,10 +643,21 @@ def list_updates(): """List installed plugins that have a newer version in the registry. Each entry: {slug, plugin_id, installed_version, available_version, - update_available, compatible, source}. + update_available, compatible, source, display_name, update_source, + incompatible_reason, requires_ack, risk}. ``?refresh=1`` refetches the + registry index first. """ + from datetime import datetime, timezone + from app.services import registry_service from app.services.plugin_service import check_for_updates - return jsonify({'updates': check_for_updates()}) + refresh = request.args.get('refresh', '').lower() in ('1', 'true', 'yes') + updates = check_for_updates(refresh=refresh) + return jsonify({ + 'updates': updates, + 'count': sum(1 for u in updates if u['update_available'] and u['compatible']), + 'checked_at': datetime.now(timezone.utc).isoformat(), + 'registry_source': registry_service.registry_source_label(), + }) @plugins_bp.route('//update', methods=['POST']) @@ -670,21 +681,23 @@ def update_plugin_route(plugin_id): if not plugin: return jsonify({'error': 'Plugin not found'}), 404 - entry = registry_service.get_entry(plugin.slug) - if not entry: + builtin = plugin.source_type == 'builtin' # local bundled code: no consent + entry = None if builtin else registry_service.get_entry(plugin.slug) + if not builtin and not entry: return jsonify({ 'error': f"No registry entry for '{plugin.slug}' — cannot update " f"from the registry." }), 400 # Hidden means not updatable either: unreviewed entries only exist in # development contexts (see registry_service._show_unreviewed). - if entry.get('trust') == 'unreviewed' \ + if entry and entry.get('trust') == 'unreviewed' \ and not registry_service._show_unreviewed(): return jsonify({'error': 'Extension not found in the registry'}), 404 body = json_object(optional=True) acknowledged = body.get('acknowledge_risk') is True - reason, message = registry_service.consent_gate(entry, acknowledged) + reason, message = (None, None) if builtin else \ + registry_service.consent_gate(entry, acknowledged) if reason: return jsonify({ 'error': f'{message} Resend with acknowledge_risk: true to proceed.', @@ -703,7 +716,7 @@ def update_plugin_route(plugin_id): target_id=plugin.id, details={ 'name': plugin.name, 'version': plugin.version, - 'source': 'registry-update', + 'source': 'builtin-update' if builtin else 'registry-update', # Forensics (audit I7): the signature verdict of the bytes # that just landed. 'signature': sig.get('status') or 'unsigned', diff --git a/backend/app/api/servers.py b/backend/app/api/servers.py index b1c81b8e..f05bffe4 100644 --- a/backend/app/api/servers.py +++ b/backend/app/api/servers.py @@ -13,6 +13,7 @@ from flask_jwt_extended import jwt_required, get_jwt_identity from sqlalchemy.orm import joinedload from app import db, limiter +from app.services import permission_levels from app.services.server_metrics_service import latest_metrics_by_server from app.api._query import apply_query, QueryParseError from app.api._request import json_object @@ -440,6 +441,8 @@ def create_server(): registered_by=user_id, workspace_id=ws_id, registration_token_expires=expires_at, + # What the install command asks for; the agent's report is the truth. + requested_permission_level=permission_levels.normalize(data.get('requested_level')), ) server.set_registration_token(registration_token) @@ -718,6 +721,7 @@ def regenerate_token(server_id): registration_token = Server.generate_registration_token() server.set_registration_token(registration_token) server.registration_token_expires = expires_at + server.requested_permission_level = permission_levels.normalize(data.get('requested_level')) server.status = 'pending' server.agent_id = None @@ -792,6 +796,10 @@ def register_agent(): server.total_disk = system_info.get('total_disk', server.total_disk) server.agent_version = data.get('agent_version') + # Level is whatever the agent says it was installed with; the panel never + # sets it. A mismatch with the requested level is surfaced in the UI. + from app.services import agent_health_service + agent_health_service.record_level(server, data.get('permission_level')) # Replace the panel-issued placeholder name with whatever the agent # reports — preferring the OS hostname over the agent's optional @@ -883,15 +891,15 @@ def get_server_metrics(server_id): try: from_dt = datetime.fromisoformat(from_time.replace('Z', '+00:00')) query = query.filter(ServerMetrics.timestamp >= from_dt) - except: - pass + except ValueError: + raise ValidationError("Invalid 'from' timestamp; use ISO 8601") if to_time: try: to_dt = datetime.fromisoformat(to_time.replace('Z', '+00:00')) query = query.filter(ServerMetrics.timestamp <= to_dt) - except: - pass + except ValueError: + raise ValidationError("Invalid 'to' timestamp; use ISO 8601") metrics = query.order_by(ServerMetrics.timestamp.desc()).limit(limit).all() diff --git a/backend/app/api/servers_agents.py b/backend/app/api/servers_agents.py index db47e704..3a11880b 100644 --- a/backend/app/api/servers_agents.py +++ b/backend/app/api/servers_agents.py @@ -5,6 +5,7 @@ import os import re import requests from app.models.server import AgentVersion, Server +from app.services import permission_levels from flask import Response, current_app, jsonify, redirect, request from app.middleware.rbac import admin_required, developer_required from app.exceptions import agent_offline, field_required @@ -178,8 +179,11 @@ def get_install_instructions(server_id): # Get base URL base_url = _get_external_base_url() api_url = f"{base_url}/api/v1/servers" + level = (permission_levels.normalize(request.args.get('level')) + or server.requested_permission_level or 'monitor') return jsonify({ + 'permission_level': level, 'linux': { # Download-then-run rather than `curl … | sudo bash`: in a pipeline # the shell reports bash's exit status, so a failed download exits 0 @@ -187,7 +191,7 @@ def get_install_instructions(server_id): 'one_liner': ( f'curl -fsSL {api_url}/install.sh -o /tmp/serverkit-agent-install.sh ' f'&& sudo bash /tmp/serverkit-agent-install.sh ' - f'--token "YOUR_TOKEN" --server "{base_url}"' + f'--token "YOUR_TOKEN" --server "{base_url}" --level {level}' ), 'manual': [ f'# Download the script', @@ -195,17 +199,17 @@ def get_install_instructions(server_id): f'chmod +x install.sh', f'', f'# Run installation', - f'sudo ./install.sh --token "YOUR_TOKEN" --server "{base_url}"' + f'sudo ./install.sh --token "YOUR_TOKEN" --server "{base_url}" --level {level}' ] }, 'windows': { - 'one_liner': f'irm {api_url}/install.ps1 | iex; Install-ServerKitAgent -Token "YOUR_TOKEN" -Server "{base_url}"', + 'one_liner': f'irm {api_url}/install.ps1 | iex; Install-ServerKitAgent -Token "YOUR_TOKEN" -Server "{base_url}" -Level {level}', 'manual': [ f'# Download the script (run in PowerShell as Administrator)', f'Invoke-WebRequest -Uri "{api_url}/install.ps1" -OutFile install.ps1', f'', f'# Run installation', - f'.\\install.ps1 -Token "YOUR_TOKEN" -Server "{base_url}"' + f'.\\install.ps1 -Token "YOUR_TOKEN" -Server "{base_url}" -Level {level}' ] }, 'note': 'Replace YOUR_TOKEN with the registration token shown in the UI' @@ -409,7 +413,8 @@ def _compare_versions(v1, v2): elif a > b: return 1 return 0 - except: + except (ValueError, AttributeError, TypeError): + current_app.logger.warning('Could not compare versions %r and %r', v1, v2) return 0 diff --git a/backend/app/api/sso.py b/backend/app/api/sso.py index d8a831aa..52c24cd4 100644 --- a/backend/app/api/sso.py +++ b/backend/app/api/sso.py @@ -1,4 +1,5 @@ """SSO / OAuth API blueprint.""" +import logging from datetime import datetime, timedelta from flask import Blueprint, request, jsonify, session from flask_jwt_extended import ( @@ -16,6 +17,8 @@ from app.error_reporting import record_unexpected from app.exceptions import NotFoundError from app.api._request import json_object +logger = logging.getLogger(__name__) + sso_bp = Blueprint('sso', __name__) VALID_PROVIDERS = ('google', 'github', 'oidc', 'saml') @@ -47,8 +50,9 @@ def authorize(provider): try: auth_url, state = sso_service.generate_auth_url(provider, redirect_uri) return jsonify({'auth_url': auth_url, 'state': state}), 200 - except Exception as e: - return jsonify({'error': str(e)}), 400 + except Exception: + logger.exception('SSO authorize failed for %s', provider) + return jsonify({'error': 'Could not start single sign-on'}), 400 @sso_bp.route('/callback/', methods=['POST']) @@ -169,8 +173,9 @@ def link_provider(provider): try: profile = sso_service.handle_oauth_callback(provider, code, state, redirect_uri) - except Exception as e: - return jsonify({'error': str(e)}), 400 + except Exception: + logger.exception('SSO link callback failed for %s', provider) + return jsonify({'error': 'Single sign-on failed'}), 400 # Check if this identity is already linked to another user existing = OAuthIdentity.query.filter_by( diff --git a/backend/app/api/system.py b/backend/app/api/system.py index 68b5b9f0..39aa3849 100644 --- a/backend/app/api/system.py +++ b/backend/app/api/system.py @@ -84,7 +84,7 @@ def check_update(): def parse_version(v): try: return tuple(int(x) for x in v.split('.')) - except: + except ValueError: return (0, 0, 0) if parse_version(latest_version) > parse_version(current_version): @@ -96,7 +96,8 @@ def check_update(): else: result['error'] = f'GitHub API error: {e.code}' except Exception as e: - result['error'] = f'Failed to check for updates: {str(e)}' + current_app.logger.warning('Update check failed: %s', e) + result['error'] = 'Failed to check for updates' # Cache the result _update_cache['last_check'] = time.time() diff --git a/backend/app/api/waf.py b/backend/app/api/waf.py index cf0fac0d..c1bc9554 100644 --- a/backend/app/api/waf.py +++ b/backend/app/api/waf.py @@ -6,6 +6,7 @@ Routes are mounted at ``/api/v1/waf``. Reads require access to the target app; mutations and install require an admin user (mirrors ``app/api/dns_zones.py``). Service ``ValueError``s map to HTTP 400. """ +import logging from flask import Blueprint, request, jsonify from flask_jwt_extended import jwt_required @@ -14,6 +15,8 @@ from app.middleware.rbac import require_admin_user from app.api._access import require_app from app.api._request import json_object +logger = logging.getLogger(__name__) + waf_bp = Blueprint('waf', __name__) @@ -47,8 +50,9 @@ def update_policy(app_id): # ModSecurity isn't present on the host. try: apply_result = WafService.apply(app_id) - except Exception as e: # pragma: no cover - defensive - apply_result = {'success': False, 'error': str(e)} + except Exception: # pragma: no cover - defensive + logger.exception('WAF apply failed for app %s', app_id) + apply_result = {'success': False, 'error': 'Failed to apply WAF policy'} response = policy.to_dict() response['apply'] = apply_result diff --git a/backend/app/core_blueprints.py b/backend/app/core_blueprints.py index 2e815888..4743fbdc 100644 --- a/backend/app/core_blueprints.py +++ b/backend/app/core_blueprints.py @@ -46,6 +46,7 @@ class BlueprintSpec: CORE_BLUEPRINTS: tuple[BlueprintSpec, ...] = ( BlueprintSpec('app.api.auth', 'auth_bp', '/api/v1/auth'), BlueprintSpec('app.api.agent_poll', 'agent_poll_bp', '/api/v1/agent'), + BlueprintSpec('app.api.agent_report', 'agent_report_bp', '/api/v1/agent'), BlueprintSpec('app.api.linked_panel', 'linked_panel_bp', '/api/v1/linked-panel'), BlueprintSpec('app.api.apps', 'apps_bp', '/api/v1/apps'), BlueprintSpec('app.api.apps', 'apps_bp', '/api/v1/services', name='services'), diff --git a/backend/app/data/themes/default.json b/backend/app/data/themes/default.json index e534983d..0b5c74b2 100644 --- a/backend/app/data/themes/default.json +++ b/backend/app/data/themes/default.json @@ -20,7 +20,7 @@ "--border-strong": "#2c313b", "--text": "#e9ebf0", "--text-dim": "#9aa1af", - "--text-faint": "#646b7a", + "--text-faint": "#868e9c", "--text-ghost": "#444b58", "--green": "#3ddc97", "--green-bg": "rgba(61,220,151,0.12)", @@ -54,7 +54,7 @@ "--border-strong": "#cdd3e0", "--text": "#161a23", "--text-dim": "#515a6b", - "--text-faint": "#79818f", + "--text-faint": "#5f6777", "--text-ghost": "#a6adba", "--green": "#3ddc97", "--green-bg": "rgba(61,220,151,0.12)", diff --git a/backend/app/exceptions.py b/backend/app/exceptions.py index 52f896b4..d0dcb47f 100644 --- a/backend/app/exceptions.py +++ b/backend/app/exceptions.py @@ -57,6 +57,12 @@ class PermissionDeniedError(ApplicationError, PermissionError): default_message = 'Access denied' +class PayloadTooLargeError(ApplicationError): + status_code = 413 + code = 'payload_too_large' + default_message = 'Payload too large' + + class NotFoundError(ApplicationError, LookupError): status_code = 404 code = 'not_found' diff --git a/backend/app/jobs/builtin_handlers.py b/backend/app/jobs/builtin_handlers.py index ea0e1446..7708733a 100644 --- a/backend/app/jobs/builtin_handlers.py +++ b/backend/app/jobs/builtin_handlers.py @@ -534,7 +534,7 @@ def _notify_fleet_alerts(opened, resolved): 'metric': alert.metric, 'value': alert.value, 'threshold': alert.threshold, - 'message': ( + 'message': alert.detail or ( f'{hostname}: {alert.metric} averaged {alert.value} over ' f'{alert.duration_seconds}s, past the ' f'{alert.severity} threshold of {alert.threshold}.'), @@ -555,7 +555,9 @@ def _notify_fleet_alerts(opened, resolved): 'hostname': hostname, 'alert_type': f'{alert.metric} recovered', 'metric': alert.metric, - 'message': (f'{hostname}: {alert.metric} is back under its ' + 'message': (f'{hostname}: {alert.metric} recovered.' + if alert.detail else + f'{hostname}: {alert.metric} is back under its ' f'threshold.'), }, ) diff --git a/backend/app/middleware/security.py b/backend/app/middleware/security.py index 9c9b5ea9..3dfa8676 100644 --- a/backend/app/middleware/security.py +++ b/backend/app/middleware/security.py @@ -2,6 +2,10 @@ from flask import Flask +# sha256 of the build-injected import map (frontend/vite.config.js, from +# src/plugins/runtime/vendorManifest.js). test_security_headers recomputes it. +VENDOR_IMPORTMAP_HASH = 'sha256-lIJXjhqB4GwFLcjRTSjM91Q7vwXxH4Wbcn475CzkW4U=' + def register_security_headers(app: Flask): """Register security headers as an after_request handler.""" @@ -37,9 +41,13 @@ def register_security_headers(app: Flask): "form-action 'self' https://github.com", ] else: + # style-src keeps 'unsafe-inline' because React renders style="" attributes; + # script-src has no 'unsafe-inline'/'unsafe-eval': the FOUC snippet is + # /theme-init.js; the one inline script (build-injected vendor importmap) + # is allowed by hash; blob: is for runtime extensions (plugins/runtime/loader.js). csp_directives = [ "default-src 'self'", - "script-src 'self' 'unsafe-inline' 'unsafe-eval'", + "script-src 'self' '%s' blob:" % VENDOR_IMPORTMAP_HASH, "style-src 'self' 'unsafe-inline'", "img-src 'self' data: https:", "font-src 'self'", diff --git a/backend/app/models/metric_alert.py b/backend/app/models/metric_alert.py index 24e29893..7bb5f999 100644 --- a/backend/app/models/metric_alert.py +++ b/backend/app/models/metric_alert.py @@ -49,6 +49,8 @@ class MetricAlert(db.Model): threshold = db.Column(db.Float) # the threshold exceeded duration_seconds = db.Column(db.Integer) # how long it was exceeded + detail = db.Column(db.Text) # human message for offline / service-check alerts + status = db.Column(db.String(20), default='active', index=True) # active, acknowledged, resolved acknowledged_by = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True, index=True) @@ -67,6 +69,7 @@ class MetricAlert(db.Model): 'value': self.value, 'threshold': self.threshold, 'duration_seconds': self.duration_seconds, + 'detail': self.detail, 'status': self.status, 'acknowledged_by': self.acknowledged_by, 'created_at': self.created_at.isoformat() if self.created_at else None, diff --git a/backend/app/models/server.py b/backend/app/models/server.py index ba6e9e80..7b011715 100644 --- a/backend/app/models/server.py +++ b/backend/app/models/server.py @@ -126,6 +126,17 @@ class Server(TimestampMixin, JsonColumnMixin, db.Model): allow_agent_update_observed = db.Column(db.Boolean, nullable=False, default=False, server_default='0') + # Agent permission level (monitor|protect|full). REPORTED BY THE AGENT + # only -- no panel API writes it. NULL = unknown/legacy, treated as full. + # requested_permission_level is what the install command asked for, kept + # only to flag a mismatch with what the agent reports. + permission_level = db.Column(db.String(16), nullable=True) + permission_level_updated_at = db.Column(db.DateTime, nullable=True) + requested_permission_level = db.Column(db.String(16), nullable=True) + last_report_at = db.Column(db.DateTime, nullable=True) + report_interval_seconds = db.Column(db.Integer, nullable=True) + service_checks = db.Column(db.JSON, nullable=True) # latest state per check + @property def is_managed(self): """False only for observed boxes.""" @@ -490,6 +501,12 @@ class Server(TimestampMixin, JsonColumnMixin, db.Model): 'last_error': self.last_error, 'management_mode': self.management_mode or 'managed', 'allow_agent_update_observed': bool(self.allow_agent_update_observed), + 'permission_level': self.permission_level, + 'permission_level_effective': self.permission_level or 'full', + 'permission_level_updated_at': self.permission_level_updated_at.isoformat() if self.permission_level_updated_at else None, + 'requested_permission_level': self.requested_permission_level, + 'last_report_at': self.last_report_at.isoformat() if self.last_report_at else None, + 'service_checks': self.service_checks or [], 'onboarding_state': self.onboarding_state, 'onboarding_updated_at': self.onboarding_updated_at.isoformat() if self.onboarding_updated_at else None, 'agent_version': self.agent_version, diff --git a/backend/app/services/agent_health_service.py b/backend/app/services/agent_health_service.py new file mode 100644 index 00000000..2272469a --- /dev/null +++ b/backend/app/services/agent_health_service.py @@ -0,0 +1,223 @@ +"""Agent-reported health: permission level, service checks, silence, alerts. + +Everything here consumes what the agent REPORTS (registration, auth, heartbeat, +or the monitor-mode ``/agent/report`` POST). Alerts reuse ``MetricAlert`` and the +fleet notification path; one active row per (server, metric) de-duplicates. +""" +import hashlib +import hmac +import logging +import time +from datetime import datetime, timedelta + +from app import db +from app.models.audit_log import AuditLog +from app.models.metric_alert import MetricAlert +from app.models.server import Server +from app.services import permission_levels +from app.services.nonce_service import nonce_service + +logger = logging.getLogger(__name__) + +MIN_SILENCE_SECONDS = 180 # monitor agents: offline after max(3 min, 3x interval) +DEFAULT_INTERVAL_SECONDS = 60 +DEFAULT_INTERVAL = DEFAULT_INTERVAL_SECONDS +OFFLINE_METRIC = 'offline' +OPEN = ('active', 'acknowledged') +BAD = ('down',) + + +def _notify(opened=(), resolved=()): + if not opened and not resolved: + return + try: + from app.jobs.builtin_handlers import _notify_fleet_alerts + _notify_fleet_alerts(list(opened), list(resolved)) + except Exception: + logger.exception('Could not notify agent health alerts') + + +def _open_alert(server, metric, detail): + """Open an alert unless one is already open. Returns it if newly opened.""" + if MetricAlert.query.filter(MetricAlert.server_id == server.id, + MetricAlert.metric == metric, + MetricAlert.status.in_(OPEN)).first(): + return None + alert = MetricAlert(server_id=server.id, metric=metric, severity='critical', + detail=detail, status='active') + db.session.add(alert) + return alert + + +def _resolve_alerts(server, metric): + rows = MetricAlert.query.filter(MetricAlert.server_id == server.id, + MetricAlert.metric == metric, + MetricAlert.status.in_(OPEN)).all() + for row in rows: + row.status = 'resolved' + row.resolved_at = datetime.utcnow() + return rows + + +def record_level(server, reported): + """Persist a level reported by the agent; audit when it changes. + + Invalid/missing values are ignored. Escalations (monitor->protect->full) are + logged like any change but flagged, since they mean someone re-ran the + local confirmation on the box. + """ + level = permission_levels.normalize(reported) + if level is None: + return + old = server.permission_level + if old == level: + return + server.permission_level = level + server.permission_level_updated_at = datetime.utcnow() + AuditLog.log( + 'server.permission_level_changed', target_type='server', target_id=server.id, + details={'server_id': server.id, 'from': old, 'to': level, + 'escalation': permission_levels.is_escalation(old, level), + 'source': 'agent_report'}) + logger.warning('Server %s reported permission level %s -> %s', server.id, old, level) + + +def record_service_checks(server, checks): + """Store the latest per-check state and open/resolve alerts on transitions.""" + if not isinstance(checks, list): + return + previous = {c.get('name'): c.get('status') for c in (server.service_checks or [])} + clean, opened, resolved = [], [], [] + for raw in checks[:50]: + if not isinstance(raw, dict) or not isinstance(raw.get('name'), str): + continue + item = {k: (str(raw.get(k))[:200] if raw.get(k) is not None else None) + for k in ('name', 'kind', 'status', 'detail', 'checked_at')} + item['name'] = item['name'][:60] + if item['status'] not in ('up', 'down', 'degraded', 'unknown'): + item['status'] = 'unknown' + clean.append(item) + metric = f"svc:{item['name']}"[:20] + if item['status'] == 'down': + alert = _open_alert( + server, metric, + f"{server.name}: service '{item['name']}' is down since " + f"{datetime.utcnow():%Y-%m-%d %H:%M} UTC" + + (f" ({item['detail']})" if item['detail'] else '')) + if alert: + opened.append(alert) + elif item['status'] == 'up' or (item['status'] == 'degraded' + and previous.get(item['name']) == 'down'): + resolved += _resolve_alerts(server, metric) + server.service_checks = clean + db.session.flush() + _notify(opened, resolved) + + +def mark_offline(server, reason): + """Open the (de-duplicated) offline alert. Caller commits.""" + since = server.last_report_at or server.last_seen or datetime.utcnow() + alert = _open_alert( + server, OFFLINE_METRIC, + f"{server.name} is offline since {since:%Y-%m-%d %H:%M} UTC: {reason}") + db.session.flush() + _notify([alert] if alert else []) + + +def mark_online(server): + resolved = _resolve_alerts(server, OFFLINE_METRIC) + db.session.flush() + _notify(resolved=resolved) + + +def silence_limit(server): + interval = server.report_interval_seconds or DEFAULT_INTERVAL_SECONDS + return timedelta(seconds=max(MIN_SILENCE_SECONDS, 3 * interval)) + + +def sweep_silent_reporters(now=None): + """Flip report-only (monitor) servers offline once their reports stop. + + Reports are not a socket, so the registry's heartbeat reaper never sees + them. Only servers that have ever reported are considered. + """ + now = now or datetime.utcnow() + flipped = [] + for server in Server.query.filter(Server.permission_level == 'monitor', + Server.last_report_at.isnot(None), + Server.status != 'offline').all(): + if now - server.last_report_at > silence_limit(server): + server.status = 'offline' + server.last_error = 'Agent stopped reporting' + mark_offline(server, 'no report received') + flipped.append(server.id) + if flipped: + db.session.commit() + return flipped + + +def authenticate_report(raw, headers, max_skew): + """Return the Server for a validly signed report request, else None.""" + key = headers.get('X-Agent-Key') or '' + ts = headers.get('X-Timestamp') or '' + nonce = headers.get('X-Nonce') or '' + signature = headers.get('X-Signature') or '' + if not (key and ts and signature) or len(nonce) < 32: + return None + try: + if abs(time.time() - int(ts)) > max_skew: + return None + except ValueError: + return None + + prefix = key[:12] + server = Server.query.filter( + (Server.api_key_prefix == prefix) | (Server.api_key_pending_prefix == prefix) + ).first() + if not server: + return None + pending = (server.api_key_pending_prefix == prefix and server.api_key_prefix != prefix + and server.api_key_rotation_expires + and datetime.utcnow() <= server.api_key_rotation_expires) + secret = server.get_pending_api_secret() if pending else server.get_api_secret() + if not secret: + return None + + message = f"{ts}.{nonce}.{hashlib.sha256(raw).hexdigest()}" + expected = hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest() + if not hmac.compare_digest(signature, expected): + return None + # Consume the nonce only after the signature proves valid. + if not nonce_service.check_and_record(server.id, nonce): + return None + return server + + +def ingest_report(server, level, body): + """Apply a verified report to the server row; returns the interval in use.""" + interval = body.get('interval_seconds') + interval = interval if isinstance(interval, int) and 5 <= interval <= 3600 else DEFAULT_INTERVAL + + now = datetime.utcnow() + was_offline = server.status != 'online' + server.status = 'online' + server.last_error = None + server.last_seen = now + server.last_report_at = now + server.report_interval_seconds = interval + if isinstance(body.get('agent_version'), str): + server.agent_version = body['agent_version'][:20] + record_level(server, level) + record_service_checks(server, body.get('service_checks')) + if was_offline: + mark_online(server) + db.session.commit() + + metrics = body.get('metrics') + if isinstance(metrics, dict): + from app.services.server_metrics_service import ServerMetricsService + ServerMetricsService.record_metrics(server.id, { + **{k: metrics.get(k) for k in ('cpu_percent', 'memory_percent', 'disk_percent')}, + 'extra': {k: metrics.get(k) for k in ('uptime_seconds', 'load1')}, + }) + return interval diff --git a/backend/app/services/agent_registry.py b/backend/app/services/agent_registry.py index 98162e0a..19f0c81c 100644 --- a/backend/app/services/agent_registry.py +++ b/backend/app/services/agent_registry.py @@ -22,6 +22,7 @@ from collections import defaultdict from app import db from app.models.server import Server, ServerCommand, AgentSession +from app.services import permission_levels # --------------------------------------------------------------------------- # Per-IP auth rate limiter — transport-neutral state shared by the WS @@ -245,6 +246,12 @@ class AgentRegistry: self._agents.pop(server_id, None) self._socket_to_server.pop(socket_id, None) + # Report-only (monitor) agents hold no socket; sweep them too. + if self._app is not None: + with self._app.app_context(): + from app.services import agent_health_service + agent_health_service.sweep_silent_reporters() + except Exception as e: logger.error("Error in heartbeat checker: %s", e) @@ -279,6 +286,8 @@ class AgentRegistry: if server: server.status = 'offline' server.last_error = 'Agent heartbeat timeout' + from app.services import agent_health_service + agent_health_service.mark_offline(server, 'heartbeat timeout') db.session.commit() # Mark session as inactive @@ -392,6 +401,8 @@ class AgentRegistry: # even for healthy connected agents. if ip_address and ip_address != 'unknown': server.ip_address = ip_address + from app.services import agent_health_service + agent_health_service.mark_online(server) db.session.commit() # Create session record @@ -519,6 +530,8 @@ class AgentRegistry: server.last_seen = now if server.status != 'online': server.status = 'online' + from app.services import agent_health_service + agent_health_service.mark_online(server) db.session.commit() # Update session latency @@ -589,6 +602,12 @@ class AgentRegistry: # Check permissions server = Server.query.get(server_id) + # Defence in depth: never send what the agent's reported level refuses. + refused = permission_levels.refusal( + server.permission_level if server else None, action) + if refused: + return {'success': False, 'error': refused, 'code': 'LEVEL_DENIED'} + if server and not server.has_permission(action): return { 'success': False, @@ -863,13 +882,15 @@ class AgentRegistry: # in-memory state — the adapter must not report success. if not session_token: return None, server, 'registration_failed' + self.record_agent_health(server.id, payload.get('permission_level')) logger.info("Agent %s authenticated successfully from %s (%s)", agent_id, ip_address, transport) return session_token, server, None def ingest_agent_state(self, agent, metrics=None, sysinfo=None, - capabilities=None): + capabilities=None, permission_level=None, + service_checks=None): """One ingest path for agent-reported state on BOTH transports. Owns the capability side-effects (the WireGuard tunnel reconcile @@ -882,6 +903,20 @@ class AgentRegistry: self.update_system_info(agent.server_id, sysinfo) if capabilities: self.update_capabilities(agent.server_id, capabilities) + if permission_level is not None or service_checks is not None: + self.record_agent_health(agent.server_id, permission_level, service_checks) + + def record_agent_health(self, server_id, permission_level=None, service_checks=None): + from app.services import agent_health_service + try: + server = Server.query.get(server_id) + if server: + agent_health_service.record_level(server, permission_level) + agent_health_service.record_service_checks(server, service_checks) + db.session.commit() + except Exception: + logger.exception("Error recording agent health") + db.session.rollback() def verify_agent_auth( self, diff --git a/backend/app/services/chat_webhook_service.py b/backend/app/services/chat_webhook_service.py index 65d5acaf..99473a6b 100644 --- a/backend/app/services/chat_webhook_service.py +++ b/backend/app/services/chat_webhook_service.py @@ -19,10 +19,9 @@ import logging import re from datetime import datetime -import requests - from app import db from app.models.chat_webhook import ChatWebhookConnection +from app.utils import safe_http from app.utils.crypto import encrypt_secret logger = logging.getLogger(__name__) @@ -405,8 +404,11 @@ class ChatWebhookService: headers[SIGNATURE_HEADER] = 'sha256=' + signature try: - resp = requests.post(url, data=body, headers=headers, - timeout=_REQUEST_TIMEOUT) + resp = safe_http.post(url, data=body, headers=headers, + timeout=_REQUEST_TIMEOUT) + except safe_http.UnsafeURLError as exc: + # Non-retryable: the URL itself is the problem, retrying can't help. + return DeliveryResult.skipped(f'webhook url refused: {exc}') except Exception as exc: # network error -> retryable failure return DeliveryResult.failed(str(exc)) diff --git a/backend/app/services/monitoring_service.py b/backend/app/services/monitoring_service.py index cba6d702..ed8a576a 100644 --- a/backend/app/services/monitoring_service.py +++ b/backend/app/services/monitoring_service.py @@ -214,7 +214,7 @@ class MonitoringService: @classmethod def send_webhook_alert(cls, alerts: List[Dict]) -> Dict: """Send webhook alert notification.""" - import requests + from app.utils import safe_http config = cls.get_config() webhook_config = config.get('webhook', {}) @@ -229,7 +229,7 @@ class MonitoringService: 'alerts': alerts } - response = requests.post( + response = safe_http.post( webhook_config['url'], json=payload, timeout=10 @@ -239,6 +239,8 @@ class MonitoringService: return {'success': True, 'message': 'Webhook sent'} return {'success': False, 'error': f'Webhook returned {response.status_code}'} + except safe_http.UnsafeURLError as e: + return {'success': False, 'error': f'Webhook URL refused: {e}'} except Exception as e: return {'success': False, 'error': str(e)} diff --git a/backend/app/services/nginx/templates.py b/backend/app/services/nginx/templates.py index e60ec4de..ba6bbeff 100644 --- a/backend/app/services/nginx/templates.py +++ b/backend/app/services/nginx/templates.py @@ -214,13 +214,13 @@ SSL_BLOCK = ''' add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always; # Baseline response-header hardening. These are safe for reverse-proxied apps; - # the CSP is deliberately permissive so it does not break managed apps while + # the CSP is permissive (inline allowed, no eval) so it does not break managed apps while # still satisfying "a CSP is present" and blocking cross-origin framing. # Tighten the CSP per-app when the upstream can support a stricter policy. add_header X-Content-Type-Options "nosniff" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always; - add_header Content-Security-Policy "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: blob: https:; frame-ancestors 'self'; upgrade-insecure-requests" always; + add_header Content-Security-Policy "default-src 'self' 'unsafe-inline' data: blob: https:; frame-ancestors 'self'; upgrade-insecure-requests" always; ''' SSL_REDIRECT_TEMPLATE = '''server {{ diff --git a/backend/app/services/permission_levels.py b/backend/app/services/permission_levels.py new file mode 100644 index 00000000..c7af05f7 --- /dev/null +++ b/backend/app/services/permission_levels.py @@ -0,0 +1,56 @@ +"""Agent permission levels and the one command-gate table. + +The level is chosen on the server (``permissions.level`` in the agent's +config.yaml) and REPORTED to the panel. The panel never sets it. This module +is only the panel's defence in depth: it refuses to send a command the agent +would refuse anyway. ``PROTECT_ACTIONS`` must stay identical to the agent's +allowlist (docs/AGENT_PERMISSION_LEVELS.md; checked by a test). +""" + +LEVELS = ('monitor', 'protect', 'full') +_RANK = {level: i for i, level in enumerate(LEVELS)} +LABELS = {'monitor': 'Monitor', 'protect': 'Protect', 'full': 'Full'} + +PROTECT_ACTIONS = frozenset({ + 'firewall:allow_port', 'firewall:deny_port', 'firewall:status', + 'firewall:allow_ip', 'firewall:deny_ip', + 'fail2ban:status', 'fail2ban:ban', 'fail2ban:unban', + 'crowdsec:decisions:list', 'crowdsec:ban', 'crowdsec:unban', + 'cloudflare:origin_lock:status', 'cloudflare:origin_lock:apply', + 'cloudflare:origin_lock:remove', +}) + +# Signature-verified key rotation is not control; allowed at every level. +ALWAYS_ALLOWED = frozenset({'credential_update'}) + + +def normalize(level): + """Return a valid level string, or None for missing/unknown values.""" + level = level.strip().lower() if isinstance(level, str) else None + return level if level in _RANK else None + + +def effective_level(level): + """Unknown/legacy (None) means a pre-levels agent, i.e. full.""" + return normalize(level) or 'full' + + +def is_escalation(old, new): + return old is not None and _RANK[new] > _RANK[old] + + +def refusal(level, action): + """Message explaining why ``action`` is refused at ``level``, else None.""" + level = effective_level(level) + if level == 'full' or action in ALWAYS_ALLOWED: + return None + if level == 'protect' and action in PROTECT_ACTIONS: + return None + if level == 'monitor': + return (f"server is in Monitor mode: '{action}' refused. Monitor agents " + "are report-only and accept no commands. The level can only be " + "changed on the server itself (serverkit-agent permissions set).") + return (f"server is in Protect mode: '{action}' refused. Protect agents only " + "run firewall, fail2ban, CrowdSec and Cloudflare origin-lock actions. " + "The level can only be changed on the server itself " + "(serverkit-agent permissions set).") diff --git a/backend/app/services/plugin_service.py b/backend/app/services/plugin_service.py index d6a6f809..144c1090 100644 --- a/backend/app/services/plugin_service.py +++ b/backend/app/services/plugin_service.py @@ -2133,37 +2133,71 @@ def install_registry_extension(slug, user_id=None): ) -def check_for_updates(): - """Compare installed plugins to the registry; return update candidates. +def check_for_updates(refresh=False): + """Compare installed plugins to the registry / bundled manifests. - Update v1 is registry-driven: a plugin whose slug is in the registry with a - higher version than installed is flagged. Panel-version compatibility is - surfaced so the UI can gray out an update the panel can't run yet. The - installed plugin's ``source_type`` is included so callers can see the - provenance the update would cross (audit M2 — a registry entry only ever - matches on slug; the update route's consent gate is the enforcement). + Registry-driven for url/registry rows (matched on slug); ``builtin`` rows + compare against the bundled manifest in builtin-extensions/. Rows with no + known source of truth (url/local/upload/git without a registry entry) are + skipped. A malformed version means "no update"; one bad row never breaks + the list. ``requires_ack``/``risk`` mirror the update route's consent gate. """ from app.services import registry_service from app.utils.version import compare_versions, version_satisfies, get_panel_version + if refresh: + registry_service.refresh(force=True) panel = get_panel_version() + bundled = {b['slug']: b['manifest'] for b in list_builtin_extensions()} out = [] for p in InstalledPlugin.query.all(): - entry = registry_service.get_entry(p.slug) - if not entry: - continue - available = entry.get('version') - out.append({ - 'slug': p.slug, - 'plugin_id': p.id, - 'installed_version': p.version, - 'available_version': available, - 'update_available': compare_versions(available, p.version) > 0, - 'compatible': version_satisfies( - panel, entry.get('min_panel_version'), entry.get('max_panel_version') - ), - 'source': entry.get('source'), - 'installed_source_type': p.source_type, - }) + try: + if p.source_type == 'builtin': + m = bundled.get(p.slug) + if not m: + continue + available = m.get('version') + row = { + 'display_name': m.get('display_name') or p.name, + 'update_source': 'builtin', 'source': None, + 'compatible': True, 'requires_ack': False, 'risk': None, + } + minv = m.get('min_panel_version') + maxv = m.get('max_panel_version') + else: + entry = registry_service.get_entry(p.slug) + if not entry: + continue + available = entry.get('version') + minv = entry.get('min_panel_version') + maxv = entry.get('max_panel_version') + risk, _ = registry_service.consent_gate(entry, False) + row = { + 'display_name': entry.get('display_name') or p.name, + 'update_source': 'registry', 'source': entry.get('source'), + 'requires_ack': bool(risk), 'risk': risk, + } + try: + newer = compare_versions(available, p.version) > 0 + except Exception: # noqa: BLE001 - malformed version = no update + newer = False + compatible = version_satisfies(panel, minv, maxv) + row['compatible'] = bool(compatible) + row['incompatible_reason'] = None if compatible else ( + f"Needs panel {minv or '*'}–{maxv or '*'} (this panel is {panel})." + ) + if minv: + row['min_panel_version'] = minv + out.append({ + 'slug': p.slug, + 'plugin_id': p.id, + 'installed_version': p.version, + 'available_version': available, + 'update_available': newer, + 'installed_source_type': p.source_type, + **row, + }) + except Exception as exc: # noqa: BLE001 - isolate bad rows + logger.warning(f'Update check skipped {p.slug}: {exc}') return out @@ -2173,6 +2207,15 @@ def update_plugin(plugin_id, user_id=None): plugin = InstalledPlugin.query.get(plugin_id) if not plugin: raise ValueError('Plugin not found') + folder = next((b['path'] for b in list_builtin_extensions() + if b['slug'] == plugin.slug), None) \ + if plugin.source_type == 'builtin' else None + # A builtin row with no bundled folder (e.g. stamped by hand) falls + # through to the registry path below. + if folder: + return install_from_path( + folder, user_id=user_id, force=True, source_type='builtin', + ) entry = registry_service.get_entry(plugin.slug) if not entry: raise ValueError( diff --git a/backend/app/services/server_timeline_service.py b/backend/app/services/server_timeline_service.py index 8da66702..40cd2978 100644 --- a/backend/app/services/server_timeline_service.py +++ b/backend/app/services/server_timeline_service.py @@ -52,6 +52,7 @@ _AUDIT_DETAIL_KEYS = frozenset({ 'application_id', 'code', 'endpoint', + 'escalation', 'from', 'kind', 'label', diff --git a/backend/app/sockets.py b/backend/app/sockets.py index a20153ce..6bb0c1a5 100644 --- a/backend/app/sockets.py +++ b/backend/app/sockets.py @@ -5,6 +5,8 @@ import threading import time import queue import re +import logging +import subprocess from app.services.system_service import SystemService from app.services.log_service import LogService, LogStreamer @@ -12,6 +14,8 @@ from app.services.docker_service import DockerService from app import sockets_rooms as rooms from app.utils.background_loop import BackgroundLoop +logger = logging.getLogger(__name__) + class AuthorizedSocketIO(SocketIO): """Recheck audience authorization before every server-side delivery. @@ -775,11 +779,11 @@ def handle_subscribe_container_logs(data): try: process.terminate() process.wait(timeout=2) - except: + except (OSError, subprocess.SubprocessError): try: process.kill() - except: - pass + except OSError as kill_err: + logger.debug('Could not kill log stream process: %s', kill_err) thread = threading.Thread(target=stream_logs, daemon=True) thread.start() @@ -836,11 +840,11 @@ def stop_container_log_stream(sid: str): try: process.terminate() process.wait(timeout=2) - except: + except (OSError, subprocess.SubprocessError): try: process.kill() - except: - pass + except OSError as kill_err: + logger.debug('Could not kill log stream process: %s', kill_err) def emit_container_log(app_id: int, line: str, level: str = 'info'): diff --git a/backend/migrations/versions/112_agent_permission_levels.py b/backend/migrations/versions/112_agent_permission_levels.py new file mode 100644 index 00000000..e65a5908 --- /dev/null +++ b/backend/migrations/versions/112_agent_permission_levels.py @@ -0,0 +1,36 @@ +"""Agent-reported permission level, report bookkeeping and service checks.""" +import sqlalchemy as sa +from alembic import op + +revision = '112_agent_permission_levels' +down_revision = '111_preview_runtime' +branch_labels = None +depends_on = None + +SERVER_COLUMNS = [ + ('permission_level', sa.String(16)), + ('permission_level_updated_at', sa.DateTime()), + ('requested_permission_level', sa.String(16)), + ('last_report_at', sa.DateTime()), + ('report_interval_seconds', sa.Integer()), + ('service_checks', sa.JSON()), +] + + +def upgrade(): + inspector = sa.inspect(op.get_bind()) + existing = {c['name'] for c in inspector.get_columns('servers')} + for name, kind in SERVER_COLUMNS: + if name not in existing: + op.add_column('servers', sa.Column(name, kind, nullable=True)) + existing = {c['name'] for c in inspector.get_columns('metric_alerts')} + if 'detail' not in existing: + op.add_column('metric_alerts', sa.Column('detail', sa.Text(), nullable=True)) + + +def downgrade(): + with op.batch_alter_table('metric_alerts') as batch: + batch.drop_column('detail') + with op.batch_alter_table('servers') as batch: + for name, _ in reversed(SERVER_COLUMNS): + batch.drop_column(name) diff --git a/backend/scripts/seed_permission_demo.py b/backend/scripts/seed_permission_demo.py new file mode 100644 index 00000000..a076facc --- /dev/null +++ b/backend/scripts/seed_permission_demo.py @@ -0,0 +1,80 @@ +"""Seed five demo servers showing every permission-level / health state. + +Dev sandbox only; never run automatically. Idempotent: demo rows are keyed by +agent_id 'demo-perm-*' and are rebuilt on each run. + + cd backend && python scripts/seed_permission_demo.py +""" +import os +import sys +from datetime import datetime, timedelta + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from app import create_app, db # noqa: E402 +from app.models.metric_alert import MetricAlert # noqa: E402 +from app.models.server import Server, ServerMetrics # noqa: E402 + +UP, DOWN, DEG = 'up', 'down', 'degraded' + + +def checks(now, web=UP, php=UP, database=UP, disk=UP): + stamp = now.isoformat() + 'Z' + rows = [('nginx', 'web', web, ''), ('php8.2-fpm', 'php_fpm', php, 'slow pool' if php == DEG else ''), + ('mysql', 'database', database, 'connection refused on 3306' if database == DOWN else ''), + ('disk /', 'disk', disk, ''), ('cpu', 'cpu', UP, ''), ('memory', 'memory', UP, '')] + return [{'name': n, 'kind': k, 'status': s, 'detail': d, 'checked_at': stamp} for n, k, s, d in rows] + + +# (name, level, status, minutes since last report, check overrides, cpu) +DEMOS = [ + ('demo-monitor-healthy', 'monitor', 'online', 1, {}, 14.0), + ('demo-monitor-degraded', 'monitor', 'online', 1, {'database': DOWN, 'php': DEG}, 71.0), + ('demo-protect-healthy', 'protect', 'online', 0, {}, 22.0), + ('demo-full-healthy', 'full', 'online', 0, {}, 35.0), + ('demo-monitor-offline', 'monitor', 'offline', 20, {'database': DOWN}, 9.0), +] + + +def seed(): + now = datetime.utcnow() + for name, level, status, age, overrides, cpu in DEMOS: + agent_id = f'demo-perm-{name}' + old = Server.query.filter_by(agent_id=agent_id).first() + if old: + MetricAlert.query.filter_by(server_id=old.id).delete() + ServerMetrics.query.filter_by(server_id=old.id).delete() + db.session.delete(old) + db.session.flush() + reported = now - timedelta(minutes=age) + srv = Server(name=name, agent_id=agent_id, hostname=name, status=status, + os_type='linux', permission_level=level, requested_permission_level=level, + permission_level_updated_at=reported, last_seen=reported, + last_report_at=reported, report_interval_seconds=60, + service_checks=checks(reported, **overrides)) + db.session.add(srv) + db.session.flush() + for i in range(12): + db.session.add(ServerMetrics( + server_id=srv.id, timestamp=reported - timedelta(minutes=i), + cpu_percent=cpu + i % 3, memory_percent=48.0, disk_percent=61.0)) + for check in srv.service_checks: + if check['status'] == DOWN: + db.session.add(MetricAlert( + server_id=srv.id, metric=f"svc:{check['name']}"[:20], severity='critical', + status='active', created_at=reported, + detail=f"{name}: service '{check['name']}' is down since " + f"{reported:%Y-%m-%d %H:%M} UTC ({check['detail']})")) + if status == 'offline': + db.session.add(MetricAlert( + server_id=srv.id, metric='offline', severity='critical', status='active', + created_at=now, detail=f"{name} is offline since {reported:%Y-%m-%d %H:%M} UTC: " + "no report received")) + db.session.commit() + print(f'Seeded {len(DEMOS)} demo servers.') + + +if __name__ == '__main__': + app = create_app(os.environ.get('FLASK_ENV') or 'development') + with app.app_context(): + seed() diff --git a/backend/tests/BASELINE_COUNT b/backend/tests/BASELINE_COUNT index 844039bc..7e8c942e 100644 --- a/backend/tests/BASELINE_COUNT +++ b/backend/tests/BASELINE_COUNT @@ -1 +1 @@ -5279 +6102 diff --git a/backend/tests/fixtures/nginx-render-contract.json b/backend/tests/fixtures/nginx-render-contract.json index 4d1497e6..f1f62200 100644 --- a/backend/tests/fixtures/nginx-render-contract.json +++ b/backend/tests/fixtures/nginx-render-contract.json @@ -1,10 +1,10 @@ { - "php": "e6d77fd5ac90d438b9f694b3dcf50d63746bd87f3e20030e0c4bd6e94c6f372a", - "wordpress": "e6d77fd5ac90d438b9f694b3dcf50d63746bd87f3e20030e0c4bd6e94c6f372a", - "flask": "dba3ba47c2d2407bcbcf3b8014bc6f5dc105db8a7e5837f849b871fd5960329b", - "django": "dba3ba47c2d2407bcbcf3b8014bc6f5dc105db8a7e5837f849b871fd5960329b", - "python": "dba3ba47c2d2407bcbcf3b8014bc6f5dc105db8a7e5837f849b871fd5960329b", - "docker": "a18576b49626ed0f88126de8946163720d715016ee24119de22afdb38fda4400", - "remote": "7bc871f2c95a333cfe14129ae40df409a3a2165e79fb7c9205510957c95af99f", - "static": "91d63c4279f9fa1fa1ecc1cfd0e3f8c5b63e134613d319ae189a4560d3738e28" + "php": "a1de4fd08a9d277ecf4c7aaa46514bcae28a05b0a90a87bc2190cfa18dbb237f", + "wordpress": "a1de4fd08a9d277ecf4c7aaa46514bcae28a05b0a90a87bc2190cfa18dbb237f", + "flask": "15ffdb7f2221e465689f1662d49cf913861032d1ba1689f71ed78cd0dc2d963c", + "django": "15ffdb7f2221e465689f1662d49cf913861032d1ba1689f71ed78cd0dc2d963c", + "python": "15ffdb7f2221e465689f1662d49cf913861032d1ba1689f71ed78cd0dc2d963c", + "docker": "362d30566ba5452cb3ed9e7376da4f95c1fda61e6ec5b6a65b1ef98aa461aca5", + "remote": "0589dd632da88d569e41c339681c0a38656037d40b733179986bfc5f80f5bd27", + "static": "d3ff984ff1aac1c22e8e59f70f7fdf0c3d838726b4621f3313aa7cd4d78ee139" } diff --git a/backend/tests/test_agent_permission_levels.py b/backend/tests/test_agent_permission_levels.py new file mode 100644 index 00000000..b5ab40ab --- /dev/null +++ b/backend/tests/test_agent_permission_levels.py @@ -0,0 +1,208 @@ +"""Agent permission levels: report endpoint, level reporting, dispatch gate, +silence sweep, service-check alerts and install commands.""" +import hashlib +import hmac +import json +import re +import secrets +import time +from datetime import datetime, timedelta +from pathlib import Path + +import pytest + +from app import db +from app.models.audit_log import AuditLog +from app.models.metric_alert import MetricAlert +from app.models.server import Server +from app.services import agent_health_service, permission_levels +from app.services.agent_registry import ConnectedAgent, agent_registry + +REPORT = '/api/v1/agent/report' +SECRET = 'test-secret' + + +@pytest.fixture +def server(app, monkeypatch): + monkeypatch.setattr(Server, 'get_api_secret', lambda self: SECRET) + key, _ = Server.generate_api_credentials() + srv = Server(name='web-1', agent_id=secrets.token_hex(8)) + srv.set_api_key(key) + db.session.add(srv) + db.session.commit() + srv.test_key = key + return srv + + +def _post(client, srv, body=None, ts=None, nonce=None, secret=SECRET, raw=None): + body = body if body is not None else { + 'permission_level': 'monitor', 'interval_seconds': 60, + 'metrics': {'cpu_percent': 12.5, 'memory_percent': 40.0, 'disk_percent': 55.0, + 'uptime_seconds': 99, 'load1': 0.3}, + 'service_checks': []} + raw = raw if raw is not None else json.dumps(body).encode() + ts = str(int(time.time())) if ts is None else str(ts) + nonce = nonce or secrets.token_hex(16) + sig = hmac.new(secret.encode(), + f'{ts}.{nonce}.{hashlib.sha256(raw).hexdigest()}'.encode(), + hashlib.sha256).hexdigest() + return client.post(REPORT, data=raw, content_type='application/json', headers={ + 'X-Agent-Key': srv.test_key, 'X-Timestamp': ts, 'X-Nonce': nonce, + 'X-Signature': sig}) + + +def test_good_signature_updates_server(client, server): + resp = _post(client, server) + assert resp.status_code == 200 + assert resp.get_json() == {'ok': True, 'interval_seconds': 60} + srv = db.session.get(Server, server.id) + assert srv.status == 'online' and srv.last_report_at is not None + assert srv.permission_level == 'monitor' + assert 'commands' not in resp.get_json() + + +def test_bad_signature_rejected(client, server): + assert _post(client, server, secret='wrong').status_code == 401 + + +def test_stale_timestamp_rejected(client, server): + assert _post(client, server, ts=int(time.time()) - 400).status_code == 401 + + +def test_replayed_nonce_rejected(client, server): + nonce = secrets.token_hex(16) + assert _post(client, server, nonce=nonce).status_code == 200 + assert _post(client, server, nonce=nonce).status_code == 401 + + +def test_oversize_body_rejected(client, server): + assert _post(client, server, raw=b'{"x":"' + b'a' * 70000 + b'"}').status_code == 413 + + +def test_invalid_level_rejected(client, server): + assert _post(client, server, body={'permission_level': 'root'}).status_code == 400 + + +def test_level_persisted_and_escalation_audited(client, server): + _post(client, server, body={'permission_level': 'monitor'}) + _post(client, server, body={'permission_level': 'full'}) + rows = AuditLog.query.filter_by(action='server.permission_level_changed').order_by(AuditLog.id).all() + details = [r.get_details() for r in rows] + assert [(d['from'], d['to'], d['escalation']) for d in details] == [ + (None, 'monitor', False), ('monitor', 'full', True)] + assert db.session.get(Server, server.id).permission_level == 'full' + + +def test_no_api_sets_level(client, server, auth_headers): + resp = client.put(f'/api/v1/servers/{server.id}', headers=auth_headers, + json={'permission_level': 'full', 'name': 'x'}) + assert resp.status_code in (200, 400) + assert db.session.get(Server, server.id).permission_level is None + writers = [r.rule for r in client.application.url_map.iter_rules() + if 'level' in r.rule and r.methods & {'POST', 'PUT', 'PATCH'}] + assert writers == [] + + +def _connect(server_id): + agent_registry._agents[server_id] = ConnectedAgent( + server_id=server_id, socket_id='s', session_token='t', + connected_at=datetime.utcnow(), last_heartbeat=datetime.utcnow(), + ip_address='1.1.1.1', agent_version='1', transport='poll') + + +@pytest.mark.parametrize('level,action,refused', [ + ('monitor', 'firewall:status', True), + ('monitor', 'docker:container:list', True), + ('protect', 'docker:container:list', True), + ('protect', 'system:exec', True), + ('protect', 'firewall:status', False), + ('protect', 'cloudflare:origin_lock:apply', False), + ('protect', 'credential_update', False), + ('full', 'system:exec', False), + (None, 'system:exec', False), +]) +def test_refusal_table(level, action, refused): + assert bool(permission_levels.refusal(level, action)) is refused + + +@pytest.mark.parametrize('level', ['monitor', 'protect']) +def test_send_command_gate(server, level): + server.permission_level = level + db.session.commit() + _connect(server.id) + try: + result = agent_registry.send_command(server.id, 'system:exec', {}) + finally: + agent_registry._agents.pop(server.id, None) + assert result['code'] == 'LEVEL_DENIED' + assert result['error'].startswith(f'server is in {level.title()} mode') + + +def test_protect_allowlist_matches_documented_contract(): + doc = Path(__file__).parents[2] / 'docs/AGENT_PERMISSION_LEVELS.md' + block = re.search(r'```text allowlist\n(.*?)```', doc.read_text(), re.S).group(1) + assert set(block.split()) == set(permission_levels.PROTECT_ACTIONS) + + +def test_silent_monitor_goes_offline_with_one_alert(server): + server.permission_level = 'monitor' + server.status = 'online' + server.last_report_at = datetime.utcnow() - timedelta(minutes=20) + db.session.commit() + assert agent_health_service.sweep_silent_reporters() == [server.id] + assert agent_health_service.sweep_silent_reporters() == [] + assert db.session.get(Server, server.id).status == 'offline' + assert MetricAlert.query.filter_by(metric='offline', status='active').count() == 1 + + +def test_recent_monitor_stays_online(server): + server.permission_level, server.status = 'monitor', 'online' + server.last_report_at = datetime.utcnow() - timedelta(minutes=2) + db.session.commit() + assert agent_health_service.sweep_silent_reporters() == [] + + +def _checks(status): + return {'permission_level': 'monitor', 'service_checks': [ + {'name': 'mysql', 'kind': 'database', 'status': status, 'detail': 'refused', + 'checked_at': '2026-01-01T00:00:00Z'}]} + + +def test_service_down_alert_dedupes_and_resolves(client, server): + _post(client, server, body=_checks('up')) + assert MetricAlert.query.count() == 0 + _post(client, server, body=_checks('down')) + _post(client, server, body=_checks('down')) + alert = MetricAlert.query.one() + assert alert.status == 'active' and 'mysql' in alert.detail and 'web-1' in alert.detail + _post(client, server, body=_checks('up')) + assert MetricAlert.query.one().status == 'resolved' + + +def test_degraded_to_down_alerts_and_report_recovers_offline(client, server): + _post(client, server, body=_checks('degraded')) + assert MetricAlert.query.count() == 0 + _post(client, server, body=_checks('down')) + assert MetricAlert.query.filter_by(status='active').count() == 1 + agent_health_service.mark_offline(server, 'test') + db.session.commit() + server.status = 'offline' + db.session.commit() + _post(client, server, body=_checks('down')) + assert MetricAlert.query.filter_by(metric='offline', status='resolved').count() == 1 + + +def test_install_instructions_include_level(client, server, auth_headers): + server.set_registration_token('sk_reg_x') + db.session.commit() + data = client.get(f'/api/v1/servers/install-instructions/{server.id}?level=protect', + headers=auth_headers).get_json() + assert data['permission_level'] == 'protect' + assert '--level protect' in data['linux']['one_liner'] + assert '-Level protect' in data['windows']['one_liner'] + + +def test_token_records_requested_level(client, server, auth_headers): + client.post(f'/api/v1/servers/{server.id}/regenerate-token', headers=auth_headers, + json={'requested_level': 'protect'}) + assert db.session.get(Server, server.id).requested_permission_level == 'protect' diff --git a/backend/tests/test_backups_unwritable_dir.py b/backend/tests/test_backups_unwritable_dir.py new file mode 100644 index 00000000..6a7e7d20 --- /dev/null +++ b/backend/tests/test_backups_unwritable_dir.py @@ -0,0 +1,33 @@ +"""GET /backups must not 500 when the backup directory cannot be created.""" +import pytest + +from app.services.backup_service import BackupService + + +@pytest.fixture +def unwritable(monkeypatch): + def deny(): + raise PermissionError(13, 'Permission denied', '/var/backups/serverkit') + monkeypatch.setattr(BackupService, 'ensure_backup_dirs', deny) + + +@pytest.mark.parametrize('path', ['/api/v1/backups', '/api/v1/backups/stats']) +def test_get_degrades_with_a_warning(client, auth_headers, unwritable, path): + resp = client.get(path, headers=auth_headers) + + assert resp.status_code == 200 + body = resp.get_json() + assert 'not accessible' in body['warning'] + assert '/var/backups' not in body['warning'] + assert body.get('backups', []) == [] + + +def test_create_returns_503_with_code_when_dir_unwritable(client, auth_headers, unwritable): + resp = client.post('/api/v1/backups/database', headers=auth_headers, + json={'db_type': 'mysql', 'db_name': 'x'}) + + assert resp.status_code == 503 + body = resp.get_json() + assert body['code'] == 'backup_dir_unavailable' + assert body['error'] == 'Backup directory is not writable' + assert '/var/backups' not in resp.get_data(as_text=True) diff --git a/backend/tests/test_core_blueprint_registry.py b/backend/tests/test_core_blueprint_registry.py index 3b4e86e4..beba6dfe 100644 --- a/backend/tests/test_core_blueprint_registry.py +++ b/backend/tests/test_core_blueprint_registry.py @@ -7,9 +7,9 @@ from pathlib import Path from app.core_blueprints import CORE_BLUEPRINTS -EXPECTED_CORE_BLUEPRINT_COUNT = 116 +EXPECTED_CORE_BLUEPRINT_COUNT = 117 EXPECTED_MANIFEST_SHA256 = ( - '25d28d92ccddddc246d5b2081d84b11f1df10cb662f33c256ebcbe390d2813d5' + '52abbc7429d079c7cf6ea61a638f5dc4dbd991e4f02ec31c81563e01442aa7fb' ) diff --git a/backend/tests/test_no_exception_text_leak.py b/backend/tests/test_no_exception_text_leak.py new file mode 100644 index 00000000..e8f19e4b --- /dev/null +++ b/backend/tests/test_no_exception_text_leak.py @@ -0,0 +1,13 @@ +"""Unexpected failures answer with a generic message; the detail is only logged.""" +from app.services import sso_service + + +def test_sso_authorize_does_not_echo_exception_text(client, monkeypatch): + def boom(*a, **kw): + raise RuntimeError('secret internal path /etc/serverkit/oidc.key') + monkeypatch.setattr(sso_service, 'generate_auth_url', boom) + + resp = client.get('/api/v1/sso/authorize/google?redirect_uri=http://localhost/cb') + + assert resp.status_code == 400 + assert '/etc/serverkit' not in resp.get_data(as_text=True) diff --git a/backend/tests/test_notification_chat_connections.py b/backend/tests/test_notification_chat_connections.py index 202b8b09..ec1f3df0 100644 --- a/backend/tests/test_notification_chat_connections.py +++ b/backend/tests/test_notification_chat_connections.py @@ -321,7 +321,7 @@ class TestSigningAndDelivery: captured.update({'url': url, 'data': data, 'headers': headers}) return _Resp() - monkeypatch.setattr('app.services.chat_webhook_service.requests.post', fake_post) + monkeypatch.setattr('app.services.chat_webhook_service.safe_http.post', fake_post) user = _make_user() conn = ChatWebhookService.add({'kind': 'webhook', 'name': 'Ops', 'url': 'https://hooks/x', @@ -392,7 +392,7 @@ class TestConnectionTesting: status_code = 503 monkeypatch.setattr( - 'app.services.chat_webhook_service.requests.post', + 'app.services.chat_webhook_service.safe_http.post', lambda *args, **kwargs: _Resp(), ) conn = ChatWebhookService.add({ @@ -428,7 +428,7 @@ class TestConnectionTesting: raise RuntimeError(f'failed POST {url}') monkeypatch.setattr( - 'app.services.chat_webhook_service.requests.post', fail_post, + 'app.services.chat_webhook_service.safe_http.post', fail_post, ) secret_url = 'https://hooks.example/super-secret-token' conn = ChatWebhookService.add({ @@ -454,7 +454,7 @@ class TestConnectionTesting: raise RuntimeError(f'failed POST {url}') monkeypatch.setattr( - 'app.services.chat_webhook_service.requests.post', fail_post, + 'app.services.chat_webhook_service.safe_http.post', fail_post, ) conn = ChatWebhookService.add({ 'kind': 'webhook', @@ -624,7 +624,7 @@ class TestApi: status_code = 503 monkeypatch.setattr( - 'app.services.chat_webhook_service.requests.post', + 'app.services.chat_webhook_service.safe_http.post', lambda *args, **kwargs: _Resp(), ) conn = ChatWebhookService.add({ diff --git a/backend/tests/test_permission_service.py b/backend/tests/test_permission_service.py new file mode 100644 index 00000000..c3e99165 --- /dev/null +++ b/backend/tests/test_permission_service.py @@ -0,0 +1,107 @@ +"""PermissionService + User permission resolution per role.""" +import pytest +from werkzeug.security import generate_password_hash + +from app import db +from app.models import User +from app.services.permission_service import PermissionService + + +def _user(role, name=None): + u = User(email=f'{name or role}@example.com', username=name or role, + password_hash=generate_password_hash('x'), role=role, is_active=True) + db.session.add(u) + db.session.commit() + return u + + +def test_role_templates_cover_every_feature_for_admin(): + admin = PermissionService.get_role_template('admin') + assert set(admin) == set(User.PERMISSION_FEATURES) + assert all(v == {'read': True, 'write': True} for v in admin.values()) + + +def test_unknown_role_has_no_permissions(app): + assert PermissionService.get_role_template('wizard') == {} + u = _user('viewer', 'nobody') + u.role = 'wizard' + assert not u.has_permission('files') + + +def test_developer_defaults_follow_template(app): + dev = _user('developer') + assert dev.has_permission('applications', 'write') + assert dev.has_permission('monitoring', 'read') + assert not dev.has_permission('monitoring', 'write') + assert not dev.has_permission('users') # not in the developer template + + +def test_admin_always_allowed(app): + admin = _user('admin') + assert all(admin.has_permission(f, 'write') for f in User.PERMISSION_FEATURES) + assert admin.has_permission('anything-at-all') + + +def test_viewer_cannot_write_anything(app): + viewer = _user('viewer') + assert not any(viewer.has_permission(f, 'write') for f in User.PERMISSION_FEATURES) + + +def test_get_user_permissions_missing_user(app): + assert PermissionService.get_user_permissions(999999) is None + + +def test_update_custom_permissions_overrides_role(app): + dev = _user('developer') + res = PermissionService.update_user_permissions( + dev.id, {'files': {'read': True, 'write': False}}) + assert res['success'] + assert res['permissions'] == {'files': {'read': True, 'write': False}} + assert not dev.has_permission('files', 'write') + assert not dev.has_permission('applications') # custom set replaces the template wholesale + + +def test_reset_restores_role_template(app): + dev = _user('developer') + PermissionService.update_user_permissions(dev.id, {'files': {'read': True}}) + res = PermissionService.reset_to_role_defaults(dev.id) + assert res['success'] and res['permissions'] == User.ROLE_PERMISSION_TEMPLATES['developer'] + assert dev.permissions is None + + +def test_admin_permissions_cannot_be_customized(app): + admin = _user('admin') + res = PermissionService.update_user_permissions(admin.id, {'files': {'read': False}}) + assert res == {'success': False, 'error': 'Admin permissions cannot be customized'} + + +def test_unknown_user_is_reported(app): + assert PermissionService.update_user_permissions(424242, {}) == { + 'success': False, 'error': 'User not found'} + assert PermissionService.reset_to_role_defaults(424242) == { + 'success': False, 'error': 'User not found'} + + +@pytest.mark.parametrize('perms, fragment', [ + ('nope', 'must be an object'), + ({'bogus': {'read': True}}, 'Unknown feature'), + ({'files': True}, 'read/write object'), + ({'files': {'execute': True}}, 'Invalid permission key'), + ({'files': {'read': 'yes'}}, 'must be boolean'), + ({'files': {'read': False, 'write': True}}, 'without read'), +]) +def test_validate_permissions_rejects(perms, fragment): + assert fragment in PermissionService.validate_permissions(perms) + + +def test_validate_permissions_accepts_good_input(): + assert PermissionService.validate_permissions({}) is None + assert PermissionService.validate_permissions( + {'files': {'read': True, 'write': True}, 'cron': {'read': True}}) is None + + +def test_invalid_update_does_not_persist(app): + dev = _user('developer') + res = PermissionService.update_user_permissions(dev.id, {'bogus': {}}) + assert not res['success'] + assert dev.permissions is None diff --git a/backend/tests/test_plugin_updates.py b/backend/tests/test_plugin_updates.py new file mode 100644 index 00000000..abf973c1 --- /dev/null +++ b/backend/tests/test_plugin_updates.py @@ -0,0 +1,137 @@ +"""Update detection: registry + builtin rows, compat, consent hints, API shape.""" +import io +import json +import zipfile + +import pytest + +from app import db +from app.models.plugin import InstalledPlugin +from app.services import plugin_service, registry_service + +pytestmark = pytest.mark.fresh_app + + +@pytest.fixture(autouse=True) +def _reset_registry_cache(): + registry_service._cache.update({'ts': 0.0, 'entries': None, 'source': None}) + yield + registry_service._cache.update({'ts': 0.0, 'entries': None, 'source': None}) + + +@pytest.fixture +def plugin_dirs(tmp_path, monkeypatch): + d = {n: tmp_path / n for n in ('b', 'f', 'builtin')} + for p in d.values(): + p.mkdir() + monkeypatch.setattr(plugin_service, 'BACKEND_PLUGINS_DIR', str(d['b'])) + monkeypatch.setattr(plugin_service, 'FRONTEND_PLUGINS_DIR', str(d['f'])) + monkeypatch.setattr(plugin_service, 'BUILTIN_EXTENSIONS_DIR', str(d['builtin'])) + return d + + +def _manifest(slug, version): + return {'name': slug, 'display_name': 'Ext ' + slug, 'version': version, + 'category': 'utility', + 'contributions': {'nav': [{'id': slug, 'label': 'X', 'route': '/x'}]}} + + +def _zip(slug, version): + buf = io.BytesIO() + with zipfile.ZipFile(buf, 'w') as zf: + zf.writestr('plugin.json', json.dumps(_manifest(slug, version))) + zf.writestr('frontend/index.jsx', 'export function P(){return null;}\n') + return buf.getvalue() + + +def _install_registry_row(monkeypatch, version='1.0.0'): + data = _zip('regext', version) + monkeypatch.setattr(plugin_service, '_download_zip', lambda url: io.BytesIO(data)) + return plugin_service.install_from_url('https://x/regext.zip') + + +def _advertise(version, **extra): + registry_service._cache.update({ + 'ts': 9e18, 'source': 'test', + 'entries': [registry_service._normalize({ + 'slug': 'regext', 'display_name': 'Registry Ext', 'version': version, + 'source': 'https://x/regext.zip', 'min_panel_version': '0.0.1', + **extra})], + }) + + +def _by_slug(): + return {u['slug']: u for u in plugin_service.check_for_updates()} + + +def test_registry_update_fields(app, plugin_dirs, monkeypatch): + _install_registry_row(monkeypatch) + _advertise('2.0.0') + u = _by_slug()['regext'] + assert u['update_available'] is True + assert u['display_name'] == 'Registry Ext' + assert u['update_source'] == 'registry' + assert isinstance(u['requires_ack'], bool) + assert u['requires_ack'] == (u['risk'] is not None) + assert u['incompatible_reason'] is None + + +def test_up_to_date(app, plugin_dirs, monkeypatch): + _install_registry_row(monkeypatch) + _advertise('1.0.0') + assert _by_slug()['regext']['update_available'] is False + + +def test_incompatible_panel(app, plugin_dirs, monkeypatch): + _install_registry_row(monkeypatch) + _advertise('2.0.0', min_panel_version='999.0.0') + u = _by_slug()['regext'] + assert u['compatible'] is False + assert '999.0.0' in u['incompatible_reason'] + + +def test_malformed_version_no_raise(app, plugin_dirs, monkeypatch): + p = _install_registry_row(monkeypatch) + _advertise('banana') + assert _by_slug()['regext']['update_available'] is False + p.version = 'also-bad' + db.session.commit() + assert _by_slug()['regext']['update_available'] is False + + +def test_builtin_update(app, plugin_dirs, monkeypatch): + folder = plugin_dirs['builtin'] / 'bi-ext' + (folder / 'frontend').mkdir(parents=True) + (folder / 'frontend' / 'index.jsx').write_text('export function P(){return null;}\n') + (folder / 'plugin.json').write_text(json.dumps(_manifest('bi-ext', '1.0.0'))) + p = plugin_service.install_from_path(str(folder), source_type='builtin') + assert p.source_type == 'builtin' + # A registry entry with the same slug must be ignored for builtin rows. + assert plugin_service.check_for_updates()[0]['update_available'] is False + + (folder / 'plugin.json').write_text(json.dumps(_manifest('bi-ext', '1.1.0'))) + u = _by_slug()['bi-ext'] + assert u['update_available'] is True + assert u['update_source'] == 'builtin' + assert u['requires_ack'] is False and u['risk'] is None + + updated = plugin_service.update_plugin(p.id) + assert updated.version == '1.1.0' + assert updated.source_type == 'builtin' + assert InstalledPlugin.query.filter_by(slug='bi-ext').count() == 1 + + +def test_api_shape_and_refresh(app, client, auth_headers, plugin_dirs, monkeypatch): + calls = [] + _install_registry_row(monkeypatch) + _advertise('2.0.0') + monkeypatch.setattr(registry_service, 'refresh', + lambda force=False: calls.append(force) or registry_service._cache['entries']) + r = client.get('/api/v1/plugins/updates', headers=auth_headers) + assert r.status_code == 200 + body = r.get_json() + assert body['count'] == 1 and body['checked_at'] + assert 'registry_source' in body + assert True not in calls + client.get('/api/v1/plugins/updates?refresh=1', headers=auth_headers) + assert True in calls diff --git a/backend/tests/test_route_authz_static.py b/backend/tests/test_route_authz_static.py index a7a1e24d..0c842e91 100644 --- a/backend/tests/test_route_authz_static.py +++ b/backend/tests/test_route_authz_static.py @@ -145,6 +145,7 @@ PUBLIC_ALT_AUTH = { # Public by design; the value names the mechanism that authenticates the call. 'agent_poll.connect': 'agent HMAC handshake + per-IP throttle', 'agent_poll.disconnect': 'X-Session-Token lookup', + 'agent_report.report': 'HMAC over timestamp+nonce+body hash, skew/replay/rate limits', 'agent_poll.poll': 'X-Session-Token resolves the ConnectedAgent', 'agent_poll.result': 'X-Session-Token resolves the ConnectedAgent', 'auth.connect_session': 'loopback-only + Cloud grant verified against JWKS, 30/min', diff --git a/backend/tests/test_route_authz_sweep.py b/backend/tests/test_route_authz_sweep.py index 4265b385..d7af9e6f 100644 --- a/backend/tests/test_route_authz_sweep.py +++ b/backend/tests/test_route_authz_sweep.py @@ -221,6 +221,7 @@ VIEWER_WRITABLE = { 'docker.get_containers_stats', # PUBLIC transport — agent long-poll fallback; user JWT is ignored here. 'agent_poll.disconnect', + 'agent_report.report', # PUBLIC authentication challenge only; credential verification and UV are # required by passkey_authenticate before any session tokens are issued. 'auth.passkey_auth_options', diff --git a/backend/tests/test_security_headers.py b/backend/tests/test_security_headers.py index 2d3f06be..9e60d855 100644 --- a/backend/tests/test_security_headers.py +++ b/backend/tests/test_security_headers.py @@ -20,6 +20,14 @@ PANEL_NGINX_CONFIGS = [ / 'sites-available' / 'serverkit.conf', ] +ROOT = Path(__file__).resolve().parents[2] +ALL_CSP_CONFIGS = PANEL_NGINX_CONFIGS + [ + ROOT / 'nginx' / 'sites-available' / 'example.conf.template', +] + + +def _script_src(csp): + return next(d.strip() for d in csp.split(';') if d.strip().startswith('script-src ')) def _make_app(hsts_enabled, debug): @@ -86,3 +94,43 @@ def test_resolve_ssl_mode(monkeypatch): assert cfg._resolve_ssl_mode() == 'insecure' monkeypatch.delenv('SERVERKIT_SSL_MODE', raising=False) assert cfg._resolve_ssl_mode() == 'insecure' + + +def test_prod_csp_script_src_is_strict(): + r = _make_app(hsts_enabled=False, debug=False).test_client().get('/ping') + script_src = _script_src(r.headers['Content-Security-Policy']) + assert 'unsafe-eval' not in script_src + assert 'unsafe-inline' not in script_src + + +@pytest.mark.parametrize('config_path', ALL_CSP_CONFIGS) +def test_nginx_csp_script_src_is_strict(config_path): + line = next( + l for l in config_path.read_text(encoding='utf-8').splitlines() + if 'Content-Security-Policy' in l + ) + script_src = _script_src(line.split('"')[1]) + assert 'unsafe-eval' not in script_src + assert 'unsafe-inline' not in script_src + + +def test_index_html_has_no_inline_script(): + html = (ROOT / 'frontend' / 'index.html').read_text(encoding='utf-8') + assert ' + diff --git a/frontend/public/fonts/ibm-plex-sans-400.woff2 b/frontend/public/fonts/ibm-plex-sans-400.woff2 index ab60668b..231a1ad7 100644 Binary files a/frontend/public/fonts/ibm-plex-sans-400.woff2 and b/frontend/public/fonts/ibm-plex-sans-400.woff2 differ diff --git a/frontend/public/fonts/new400.woff2 b/frontend/public/fonts/new400.woff2 new file mode 100644 index 00000000..231a1ad7 Binary files /dev/null and b/frontend/public/fonts/new400.woff2 differ diff --git a/frontend/public/theme-init.js b/frontend/public/theme-init.js new file mode 100644 index 00000000..276873dc --- /dev/null +++ b/frontend/public/theme-init.js @@ -0,0 +1,26 @@ +// Prevent flash of unstyled content (FOUC) by setting theme + accent before React loads. +// External file (not inline) so the CSP needs no 'unsafe-inline' for scripts. +(function() { + var d = document.documentElement; + d.setAttribute('data-theme', localStorage.getItem('theme') || 'dark'); + var accent = localStorage.getItem('accent_color'); + if (accent) { + var m = accent.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i); + if (m) { + var r = parseInt(m[1],16), g = parseInt(m[2],16), b = parseInt(m[3],16); + var hx = function(v){ return Math.max(0,Math.min(255,v)).toString(16).padStart(2,'0'); }; + var dk = function(v){ return Math.round(v*0.88); }; + var br = function(v){ return Math.round(v + (255-v)*0.30); }; // toward white + var dm = function(v){ return Math.round(v*0.70); }; + d.style.setProperty('--accent-primary', accent); + d.style.setProperty('--accent', accent); + d.style.setProperty('--accent-hover', '#'+hx(dk(r))+hx(dk(g))+hx(dk(b))); + d.style.setProperty('--accent-bright', '#'+hx(br(r))+hx(br(g))+hx(br(b))); + d.style.setProperty('--accent-dim', '#'+hx(dm(r))+hx(dm(g))+hx(dm(b))); + d.style.setProperty('--accent-bg', 'rgba('+r+','+g+','+b+',0.13)'); + d.style.setProperty('--accent-bg-soft', 'rgba('+r+','+g+','+b+',0.07)'); + d.style.setProperty('--accent-glow', 'rgba('+r+','+g+','+b+',0.35)'); + d.style.setProperty('--accent-shadow', 'rgba('+r+','+g+','+b+',0.3)'); + } + } +})(); diff --git a/frontend/scripts/LABEL_ASSOCIATION_CEILING b/frontend/scripts/LABEL_ASSOCIATION_CEILING index 87523dd7..425151f3 100644 --- a/frontend/scripts/LABEL_ASSOCIATION_CEILING +++ b/frontend/scripts/LABEL_ASSOCIATION_CEILING @@ -1 +1 @@ -41 +40 diff --git a/frontend/scripts/check-font-integrity.mjs b/frontend/scripts/check-font-integrity.mjs index f297a3a0..5d909287 100644 --- a/frontend/scripts/check-font-integrity.mjs +++ b/frontend/scripts/check-font-integrity.mjs @@ -1,6 +1,7 @@ #!/usr/bin/env node import { readFile } from 'node:fs/promises'; +import { brotliDecompressSync } from 'node:zlib'; import { fileURLToPath } from 'node:url'; import { dirname, join } from 'node:path'; @@ -9,11 +10,72 @@ const FRONTEND = join(dirname(fileURLToPath(import.meta.url)), '..'); const FONT_DIR = join(FRONTEND, 'public', 'fonts'); const FONT_STYLES = join(FRONTEND, 'src', 'styles', 'base', '_fonts.scss'); const FONTS = [ + ['ibm-plex-sans-400.woff2', 400], ['ibm-plex-sans-500.woff2', 500], ['ibm-plex-sans-600.woff2', 600], ['ibm-plex-sans-700.woff2', 700], ]; +const GLYF = 10; +const LOCA = 11; +const KNOWN_TAGS = { 1: 'head', 4: 'maxp', [GLYF]: 'glyf' }; +const HEAD_MAGIC = 0x5f0f3cf5; + +// Parse the WOFF2 header + table directory and brotli-decode the table data, +// so a truncated or bit-rotted file fails here instead of silently in the browser. +function validateWoff2(font, filename) { + const fail = (why) => { throw new Error(`${filename}: ${why}`); }; + if (font.length < 48) fail('shorter than the WOFF2 header'); + if (font.readUInt32BE(8) !== font.length) fail('header length does not match file size'); + const numTables = font.readUInt16BE(12); + const compressedSize = font.readUInt32BE(20); + if (numTables === 0) fail('has no tables'); + + let pos = 48; + const base128 = () => { + let value = 0; + for (let i = 0; i < 5; i += 1) { + if (pos >= font.length) fail('table directory is truncated'); + const byte = font[pos++]; + value = value * 128 + (byte & 0x7f); + if (!(byte & 0x80)) return value; + } + return fail('invalid UIntBase128 in table directory'); + }; + let expected = 0; + const tables = {}; + for (let i = 0; i < numTables; i += 1) { + const flags = font[pos++]; + const index = flags & 0x3f; + const version = flags >> 6; + if (index === 63) pos += 4; + const origLength = base128(); + const transformed = index === GLYF || index === LOCA ? version !== 3 : version !== 0; + const length = transformed ? base128() : origLength; + if (KNOWN_TAGS[index]) tables[KNOWN_TAGS[index]] = { offset: expected, length }; + expected += length; + } + if (pos + compressedSize > font.length) fail('compressed table data runs past end of file'); + + let data; + try { + data = brotliDecompressSync(font.subarray(pos, pos + compressedSize)); + } catch (error) { + fail(`table data does not brotli-decode (${error.message})`); + } + if (data.length !== expected) { + fail(`decoded table data is ${data.length} bytes, directory declares ${expected}`); + } + + // brotli can succeed on zeroed-out tables, which browsers' font sanitizer then rejects. + const { head, maxp, glyf } = tables; + if (!head || !maxp || !glyf) fail('missing head/maxp/glyf table'); + if (data.readUInt32BE(head.offset + 12) !== HEAD_MAGIC) fail('head table magic number is wrong'); + const numGlyphs = data.readUInt16BE(maxp.offset + 4); + if (numGlyphs === 0) fail('maxp declares zero glyphs'); + if (data.readUInt16BE(glyf.offset + 4) !== numGlyphs) fail('glyf glyph count does not match maxp'); +} + const styles = await readFile(FONT_STYLES, 'utf8'); const fontFaces = [...styles.matchAll(/@font-face\s*\{([\s\S]*?)\}/g)] .map((match) => match[1]); @@ -27,6 +89,7 @@ for (const [filename, weight] of FONTS) { if (!font.some((byte) => byte !== 0)) { throw new Error(`${filename} contains only zero bytes`); } + validateWoff2(font, filename); const face = fontFaces.find((block) => block.includes(filename)); if (!face || !face.includes(`font-weight: ${weight};`)) { @@ -34,4 +97,4 @@ for (const [filename, weight] of FONTS) { } } -console.log('✓ font integrity: IBM Plex Sans 500/600/700 are valid WOFF2 assets'); +console.log('✓ font integrity: IBM Plex Sans 400/500/600/700 decode as valid WOFF2 assets'); diff --git a/frontend/scripts/check-frontend-boundaries.mjs b/frontend/scripts/check-frontend-boundaries.mjs index 1bb3ca42..e619fa30 100644 --- a/frontend/scripts/check-frontend-boundaries.mjs +++ b/frontend/scripts/check-frontend-boundaries.mjs @@ -86,7 +86,6 @@ const LEGACY_COLOR_LITERALS = new Map(Object.entries({ 'styles/pages/_file-manager.scss': 10, 'styles/pages/_git.scss': 6, 'styles/pages/_import-wizard.scss': 1, - 'styles/pages/_marketplace.scss': 2, 'styles/pages/_notification-center.scss': 4, 'styles/pages/_settings.scss': 14, 'styles/pages/_setup-wizard.scss': 5, @@ -227,7 +226,7 @@ for (const file of LEGACY_POLLERS.keys()) { const ADOPTION_CEILINGS = [ { name: 'raw api.* calls in pages/ (E1: useServerQuery/useServerMutation)', - ceiling: 398, + ceiling: 371, include: (file) => file.startsWith('pages/'), pattern: /\bapi\s*\.\s*\w+\s*\(/g, }, diff --git a/frontend/scripts/check-orphan-files.mjs b/frontend/scripts/check-orphan-files.mjs index b0d8435c..7340c394 100644 --- a/frontend/scripts/check-orphan-files.mjs +++ b/frontend/scripts/check-orphan-files.mjs @@ -22,10 +22,6 @@ const KEEP = { 'main.jsx': 'entry point', 'styles/main.scss': 'entry stylesheet', 'plugins/runtime/vendorManifest.js': 'read by the vendor-shim generator and extension bundle checks', - 'components/domains/CutoverDrawer.jsx': 'built, never mounted: wire into Domains or delete (product call)', - 'components/settings/MemberActionsCard.jsx': 'built, never mounted: wire in or delete (product call)', - 'components/dashboard/AccountSecurityNudge.jsx': 'built, never mounted: wire in or delete (product call)', - 'styles/pages/_cutover.scss': 'styles CutoverDrawer above; goes or gets imported with it', 'utils/snapshotBones.js': 'imported by scripts/capture-skeletons.mjs', }; // Trees loaded by import.meta.glob, tests, and bundled extension copies. diff --git a/frontend/scripts/fetch-fonts.mjs b/frontend/scripts/fetch-fonts.mjs index c3fa0b80..7bdc4612 100644 --- a/frontend/scripts/fetch-fonts.mjs +++ b/frontend/scripts/fetch-fonts.mjs @@ -5,7 +5,7 @@ // ServerKit self-hosts its fonts for privacy (no Google Fonts CDN — that would // leak every visitor's IP + usage to a third party). This script downloads the // OFL-licensed IBM Plex faces once into the repo's public/fonts/ folder so -// they're served from our own origin. The Sans 500/600/700 faces come directly +// they're served from our own origin. The Sans 400/500/600/700 faces come directly // from the official IBM/plex repository; existing valid faces retain their // original @fontsource jsDelivr source. // @@ -27,7 +27,7 @@ const IBM_PLEX_BASE = `https://raw.githubusercontent.com/IBM/plex/${IBM_PLEX_REV // local filename -> source URL const FONTS = { - 'ibm-plex-sans-400.woff2': `${FONTSOURCE_BASE}/@fontsource/ibm-plex-sans/files/ibm-plex-sans-latin-400-normal.woff2`, + 'ibm-plex-sans-400.woff2': `${IBM_PLEX_BASE}/packages/plex-sans/fonts/complete/woff2/IBMPlexSans-Regular.woff2`, 'ibm-plex-sans-500.woff2': `${IBM_PLEX_BASE}/packages/plex-sans/fonts/complete/woff2/IBMPlexSans-Medium.woff2`, 'ibm-plex-sans-600.woff2': `${IBM_PLEX_BASE}/packages/plex-sans/fonts/complete/woff2/IBMPlexSans-SemiBold.woff2`, 'ibm-plex-sans-700.woff2': `${IBM_PLEX_BASE}/packages/plex-sans/fonts/complete/woff2/IBMPlexSans-Bold.woff2`, diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index f632fc84..1e7486a8 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -143,8 +143,17 @@ function SetupRoute({ children }) { return children; } +// /git-ext was the in-tree git page; it now ships as the serverkit-git +// extension at /git. Without the extension that route is never registered, so +// send the operator to its marketplace entry instead of a "page not found". +const GIT_EXTENSION_SLUG = 'serverkit-git'; + function LegacyGitExtRedirect() { const { tab } = useParams(); + const { routes, __ready } = useContributions(); + if (!__ready) return ; + const installed = (routes || []).some((route) => route.plugin === GIT_EXTENSION_SLUG); + if (!installed) return ; return ; } diff --git a/frontend/src/components/FormField.jsx b/frontend/src/components/FormField.jsx index 4ec2a80a..b36cab57 100644 --- a/frontend/src/components/FormField.jsx +++ b/frontend/src/components/FormField.jsx @@ -2,6 +2,7 @@ import { useId, useMemo } from 'react'; import { Label } from '@/components/ui/label'; import { FieldContext } from '@/components/ui/field-context'; import { cn } from '@/lib/utils'; +import InfoTip from './InfoTip'; /** * Standard form field wrapper: label, hint, error message, and input slot. @@ -22,6 +23,7 @@ export function FormField({ children, error, hint, + info, required = false, className, labelClassName, @@ -42,12 +44,17 @@ export function FormField({ return (
- {label && ( - - )} + {label && (() => { + const labelEl = ( + + ); + return info + ?
{labelEl}{info}
+ : labelEl; + })()}
{children} diff --git a/frontend/src/components/IconStepStrip.jsx b/frontend/src/components/IconStepStrip.jsx new file mode 100644 index 00000000..2a9bd481 --- /dev/null +++ b/frontend/src/components/IconStepStrip.jsx @@ -0,0 +1,36 @@ +import { Info, ChevronRight } from 'lucide-react'; +import InfoTip from './InfoTip'; + +// 2-4 steps as equal-width pills (icon + short label) joined by chevrons. +// A step with `info` makes its whole pill the tap/hover target for the detail. +// steps = [{ icon: ReactNode, label: string, info?: ReactNode }] +export default function IconStepStrip({ steps, className = '' }) { + return ( +
    + {steps.map((s, i) => { + const body = ( + <> + + {s.label} + + ); + return ( +
  1. + {i > 0 &&
  2. + ); + })} +
+ ); +} diff --git a/frontend/src/components/InfoTip.jsx b/frontend/src/components/InfoTip.jsx new file mode 100644 index 00000000..b91cff26 --- /dev/null +++ b/frontend/src/components/InfoTip.jsx @@ -0,0 +1,79 @@ +import { useRef, useState } from 'react'; +import { Info } from 'lucide-react'; +import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover'; +import { Sheet, SheetTrigger, SheetContent, SheetTitle } from '@/components/ui/sheet'; +import useMediaQuery from '../hooks/useMediaQuery'; +import { t } from '../i18n/t'; + +// An (i) button that holds the explanation a page used to print inline. +// Mouse: hover/focus previews it. Touch, click, Enter and Space: toggles a +// pinned popover that closes on outside tap or Escape. Narrow screens get a +// bottom sheet instead, so the text never sits on top of the content it +// explains. Both are portalled (no button-in-button) and above Modal/Sheet. +// `trigger` replaces the (i) glyph (e.g. a whole step pill); `title` heads the sheet. +export default function InfoTip({ children, label, title, trigger, side = 'top', size = 'sm', className = '' }) { + const [open, setOpen] = useState(false); + const narrow = useMediaQuery('(max-width: 640px)'); + const pinned = useRef(false); + const hoverable = (e) => e.pointerType === 'mouse'; + + const onOpenChange = (next) => { + pinned.current = next; + setOpen(next); + }; + const stop = (e) => e.stopPropagation(); + const noFocus = (e) => e.preventDefault(); + + const button = ( + // eslint-disable-next-line no-restricted-syntax -- bare 18px glyph button; Button/IconButton add control-sized chrome and a nested Tip + + ); + + if (narrow) { + return ( + + {button} + + {title || label || t('common.moreInfo', 'More info')} +
{children}
+
+
+ ); + } + + return ( + + {button} + + {children} + + + ); +} diff --git a/frontend/src/components/ManagedCard.jsx b/frontend/src/components/ManagedCard.jsx index d4585b22..0ba1d8d7 100644 --- a/frontend/src/components/ManagedCard.jsx +++ b/frontend/src/components/ManagedCard.jsx @@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next'; import useLabel from '../i18n/labels'; import { MANAGED_CAPABILITY_MAP } from './sidebarItems'; import { formatDate } from '@/utils/intl'; +import InfoTip from '@/components/InfoTip'; // The managed card: what a held capability's page shows instead of // its content. It names the capability, who holds it and since when, and links @@ -36,9 +37,12 @@ export default function ManagedCard({ capability, profile, compact = false }) { {t('managed.card.title', '{{label}} is managed by {{heldBy}}', { label, heldBy })}

+ {t('managed.card.bodyShort', 'Hidden, not removed. Returns when Managed ends.')}{' '} + {since ? t('managed.card.bodySince', 'ServerKit Cloud took this over on {{date}} as part of your Managed service. The page is hidden, not removed. Its API still answers and everything returns the moment the Managed scope ends.', { date: since }) : t('managed.card.body', 'ServerKit Cloud takes care of this as part of your Managed service. The page is hidden, not removed. Its API still answers and everything returns the moment the Managed scope ends.')} + {capability === 'updates' && ( <> {t('managed.card.updatesNote', 'The panel still updates itself; only the update screens are hidden.')} )} diff --git a/frontend/src/components/RequiresDocker.jsx b/frontend/src/components/RequiresDocker.jsx index 9692a828..47528021 100644 --- a/frontend/src/components/RequiresDocker.jsx +++ b/frontend/src/components/RequiresDocker.jsx @@ -2,6 +2,7 @@ import { Link } from 'react-router-dom'; import { Boxes, Terminal } from 'lucide-react'; import { useResourceTier } from '../contexts/useResourceTier.js'; import { useTranslation } from 'react-i18next'; +import InfoTip from './InfoTip'; /** * Explains a Dockerless install instead of letting the page fail at click time. @@ -31,7 +32,10 @@ const RequiresDocker = ({ children, what = 'This page' }) => {

{t('app.requiresDocker.dockerIsnTAvailable', 'Docker isn\'t available')}

- {what} {t('app.requiresDocker.needsDockerToRunContainersAnd', 'needs Docker to run containers, and this server was installed with the')} {profileLabel} {t('app.requiresDocker.profileWhichLeavesItOutNothing', 'profile, which leaves it out. Nothing is locked; adding Docker turns this page on.')} + {what} {t('app.requiresDocker.needsDocker', 'needs Docker.')} + + {what} {t('app.requiresDocker.needsDockerToRunContainersAnd', 'needs Docker to run containers, and this server was installed with the')} {profileLabel} {t('app.requiresDocker.profileWhichLeavesItOutNothing', 'profile, which leaves it out. Nothing is locked; adding Docker turns this page on.')} +

@@ -48,8 +52,12 @@ const RequiresDocker = ({ children, what = 'This page' }) => {

- {t('app.requiresDocker.serverkitReChecksForDockerAutomatically', 'ServerKit re-checks for Docker automatically. Monitoring, domains, certificates, cron and DNS keep working without it. See')}{' '} - {t('app.requiresDocker.settingsSystem', 'Settings → System')} {t('app.requiresDocker.forThisInstallSProfile', 'for this install\'s profile.')} + {t('app.requiresDocker.checkedAutomatically', 'Re-checked automatically.')}{' '} + {t('app.requiresDocker.settingsSystem', 'Settings → System')} + + {t('app.requiresDocker.serverkitReChecksForDockerAutomatically', 'ServerKit re-checks for Docker automatically. Monitoring, domains, certificates, cron and DNS keep working without it. See')}{' '} + {t('app.requiresDocker.settingsSystem', 'Settings → System')} {t('app.requiresDocker.forThisInstallSProfile', 'for this install\'s profile.')} +

); diff --git a/frontend/src/components/SectionIntro.jsx b/frontend/src/components/SectionIntro.jsx new file mode 100644 index 00000000..156359ee --- /dev/null +++ b/frontend/src/components/SectionIntro.jsx @@ -0,0 +1,26 @@ +import InfoTip from './InfoTip'; +import IconStepStrip from './IconStepStrip'; + +// One short line with the longer explanation tucked in an (i). With `icon` +// and/or `steps` it becomes a compact card banner: icon tile + title + (i), +// then the IconStepStrip (one row on desktop, two on mobile). +export default function SectionIntro({ children, info, icon, steps, className = '' }) { + if (!icon && !steps) { + return ( +

+ {children} + {info && {info}} +

+ ); + } + return ( +
+
+ {icon && } + {children} + {info && {info}} +
+ {steps && } +
+ ); +} diff --git a/frontend/src/components/appdetail/DeployTab.jsx b/frontend/src/components/appdetail/DeployTab.jsx index 102611cf..42b4dbd2 100644 --- a/frontend/src/components/appdetail/DeployTab.jsx +++ b/frontend/src/components/appdetail/DeployTab.jsx @@ -15,6 +15,7 @@ import { useTranslation } from 'react-i18next'; import { Card as SharedCard } from '@/components/ui/card'; import { CardFooter as SharedCardFooter } from '@/components/ui/card'; import { formatDateTime } from '@/utils/intl'; +import InfoTip from '@/components/InfoTip'; // `embedded` renders this inside the Settings → Git & Deploy section, where the // shared RepoConnectForm already owns the connect/disconnect + repo identity. In @@ -257,7 +258,7 @@ const DeployTab = ({ appId, embedded = false }) => {

{t('app.deployTab.configCheckpoints', 'Restore points')}

- {t('app.deployTab.anImmutableConfigCheckpointEnvKeys', 'An immutable restore point (env keys, domains, image, build method, volumes) is captured before each deployment. Secret values are masked. Open a restore point to diff it against the previous one or restore it.')} + {t('app.deployTab.restorePointsShort', 'Captured before every deployment.')} {t('app.deployTab.anImmutableConfigCheckpointEnvKeys', 'An immutable restore point (env keys, domains, image, build method, volumes) is captured before each deployment. Secret values are masked. Open a restore point to diff it against the previous one or restore it.')}

diff --git a/frontend/src/components/apps/ContainerOpsPanel.jsx b/frontend/src/components/apps/ContainerOpsPanel.jsx index 3f402243..b4577a3e 100644 --- a/frontend/src/components/apps/ContainerOpsPanel.jsx +++ b/frontend/src/components/apps/ContainerOpsPanel.jsx @@ -15,6 +15,7 @@ import { InfoList, InfoItem } from '../InfoList'; import { useTranslation } from 'react-i18next'; import { toastError } from '@/utils/errorMessage'; import { formatDateTime } from '@/utils/intl'; +import InfoTip from '@/components/InfoTip'; // Short SHA helper for image digests (handles "sha256:abcdef..." or bare hashes) function shortDigest(digest) { @@ -122,7 +123,7 @@ const ImageUpdateSection = ({ app, onChanged }) => {
{!isCompose && (

- {t('app.containerOpsPanel.imageUpdatesApplyToDockerCompose', 'Image updates apply to services deployed with Docker Compose. You can still check this service\'s digest, but "Update now" is only available for Docker Compose deployments.')} + {t('app.containerOpsPanel.imageUpdatesApplyToDockerComposeShort', 'Image updates need Docker Compose.')} {t('app.containerOpsPanel.imageUpdatesApplyToDockerCompose', 'Image updates apply to services deployed with Docker Compose. You can still check this service\'s digest, but "Update now" is only available for Docker Compose deployments.')}

)} diff --git a/frontend/src/components/apps/DeploySafetyPanel.jsx b/frontend/src/components/apps/DeploySafetyPanel.jsx index 16a62958..6beda6ac 100644 --- a/frontend/src/components/apps/DeploySafetyPanel.jsx +++ b/frontend/src/components/apps/DeploySafetyPanel.jsx @@ -7,6 +7,7 @@ import { Input } from '@/components/ui/input'; import { Switch } from '@/components/ui/switch'; import { useTranslation } from 'react-i18next'; import { toastError } from '@/utils/errorMessage'; +import InfoTip from '@/components/InfoTip'; // Must match app/services/deploy_settings.py DEFAULTS / _RULES. const TIMEOUT_DEFAULT = 120; @@ -59,7 +60,7 @@ const DeploySafetyPanel = ({ app, onChanged }) => {

- {t('app.deploySafetyPanel.intro', 'Before a new release counts as live, ServerKit asks it for this path and waits for a 2xx or 3xx answer three times in a row. A release that never answers fails the deploy.')} + {t('app.deploySafetyPanel.introShort', 'New releases must answer before going live.')} {t('app.deploySafetyPanel.intro', 'Before a new release counts as live, ServerKit asks it for this path and waits for a 2xx or 3xx answer three times in a row. A release that never answers fails the deploy.')}

diff --git a/frontend/src/components/apps/HtaccessConverter.jsx b/frontend/src/components/apps/HtaccessConverter.jsx index 28cfff9c..53c2d822 100644 --- a/frontend/src/components/apps/HtaccessConverter.jsx +++ b/frontend/src/components/apps/HtaccessConverter.jsx @@ -9,6 +9,7 @@ import api from '../../services/api'; import { useToast } from '../../contexts/useToast.js'; import { useTranslation } from 'react-i18next'; import { toastError } from '@/utils/errorMessage'; +import InfoTip from '@/components/InfoTip'; // Paste-in .htaccess -> nginx converter for the per-site custom nginx rules // editor. Pairs with the site-import feature: imported cPanel sites carry @@ -112,7 +113,7 @@ export default function HtaccessConverter({ onInsert, trigger = null }) { >

- {t('app.htaccessConverter.pasteTheContentsOfAnApache', 'Paste the contents of an Apache')} .htaccess {t('app.htaccessConverter.fileEGFromAnImported', 'file (e.g. from an imported cPanel site). Rewrites, redirects, access rules and basic auth are translated to nginx directives for the custom rules box; anything that has no equivalent is listed below instead of being dropped.')} + {t('app.htaccessConverter.hintShort', 'Paste an .htaccess file to convert it.')} {t('app.htaccessConverter.pasteTheContentsOfAnApache', 'Paste the contents of an Apache')} .htaccess {t('app.htaccessConverter.fileEGFromAnImported', 'file (e.g. from an imported cPanel site). Rewrites, redirects, access rules and basic auth are translated to nginx directives for the custom rules box; anything that has no equivalent is listed below instead of being dropped.')}