Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

test(drift): re-anchor the builtin-copy guard on serverkit-status

Juan Denis18767c224433
diff --git a/.gitignore b/.gitignore
index 82e22d3a..aeefdab7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -201,7 +201,9 @@ backend/app/plugins/serverkit-cloudflare-ops/
backend/app/plugins/serverkit-k8s/
backend/app/plugins/serverkit-mail/
backend/app/plugins/serverkit-remote-access/
-backend/app/plugins/serverkit-status/
+# serverkit-status is deliberately NOT ignored: it is the tracked live copy
+# that keeps test_builtin_extension_drift non-vacuous on a fresh clone.
+# (serverkit-email held this role until it left the tree in plan 52.)
backend/app/plugins/serverkit-tramo/
backend/app/plugins/serverkit-wordpress/
frontend/src/plugins/serverkit-analytics/
diff --git a/backend/app/plugins/serverkit-status/__init__.py b/backend/app/plugins/serverkit-status/__init__.py
new file mode 100644
index 00000000..5087b60e
--- /dev/null
+++ b/backend/app/plugins/serverkit-status/__init__.py
@@ -0,0 +1,16 @@
+"""ServerKit Status Pages extension backend package.
+
+Extracted from core (plan 47): the status-pages blueprint (public status/badge
+routes + authenticated management API) and its service ship here so a fresh panel
+that never publishes a status page loads none of it. Mounted under
+``/api/v1/status`` via the manifest's ``url_prefix``; the public /status/<slug>
+and /status/badge/<slug> pages work whenever the extension is installed. The
+StatusPage / StatusComponent / StatusIncident / HealthCheck models stay in core
+(G2). Core's WordPress health-check job reaches
+``StatusPageService.sync_component_from_health`` through
+``plugin_service.get_installed_extension_attr`` only when installed. Upgrades
+re-acquire it automatically (``CONVERTED_BUILTIN_SLUGS``).
+"""
+from .status_pages import status_pages_bp
+
+__all__ = ['status_pages_bp']
diff --git a/backend/app/plugins/serverkit-status/plugin.json b/backend/app/plugins/serverkit-status/plugin.json
new file mode 100644
index 00000000..9d782d44
--- /dev/null
+++ b/backend/app/plugins/serverkit-status/plugin.json
@@ -0,0 +1,42 @@
+{
+ "name": "serverkit-status",
+ "display_name": "Status Pages",
+ "version": "1.0.0",
+ "description": "Public status pages backed by uptime monitors, with the management UI as a tab in the Observability group. Installing the extension serves the public /status/<slug> and /status/badge/<slug> pages too.",
+ "author": "ServerKit",
+ "license": "MIT",
+ "category": "monitoring",
+ "homepage": "https://github.com/jhd3197/ServerKit",
+ "permissions": [],
+ "entry_point": "status_pages:status_pages_bp",
+ "url_prefix": "/api/v1/status",
+ "icon": "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\"/><path d=\"M2 12h20\"/>",
+ "contributions": {
+ "tabs": [
+ {
+ "group": "monitoring",
+ "to": "/status-pages",
+ "label": "Status Pages",
+ "icon": "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\"/><path d=\"M2 12h20\"/>"
+ }
+ ],
+ "routes": [
+ {
+ "path": "status-pages",
+ "component": "StatusPagesPage",
+ "group": "monitoring"
+ }
+ ],
+ "page_titles": {
+ "/status-pages": "Status Pages"
+ },
+ "command_palette": [
+ {
+ "label": "Status Pages",
+ "path": "/status-pages",
+ "category": "Pages",
+ "keywords": "uptime incidents public status"
+ }
+ ]
+ }
+}
diff --git a/backend/app/plugins/serverkit-status/status_page_service.py b/backend/app/plugins/serverkit-status/status_page_service.py
new file mode 100644
index 00000000..4b81fa28
--- /dev/null
+++ b/backend/app/plugins/serverkit-status/status_page_service.py
@@ -0,0 +1,213 @@
+"""Public status pages.
+
+Scope note: this service owns *publishing* — pages, branding, grouping and the
+public JSON/badge. It no longer owns the check engine. Monitors (what used to be
+called "components") and their incidents are core, in
+``app.services.monitor_service``, because watching a site must not depend on
+having this extension installed. The component/health/incident methods below are
+thin delegates kept so existing callers and the extension's own API blueprint
+keep working unchanged.
+"""
+import logging
+
+from app.models.status_page import StatusPage, StatusComponent, StatusIncident
+from app.services.monitor_service import MonitorService
+from app.utils.slug import validate_slug
+from app import db
+
+logger = logging.getLogger(__name__)
+
+
+class StatusPageService:
+ """Service for public status pages."""
+
+ @staticmethod
+ def normalize_slug(value):
+ return validate_slug(value)
+
+ # --- Pages ---
+
+ @staticmethod
+ def list_pages():
+ return StatusPage.query.order_by(StatusPage.name).all()
+
+ @staticmethod
+ def get_page(page_id):
+ return StatusPage.query.get(page_id)
+
+ @staticmethod
+ def get_page_by_slug(slug):
+ return StatusPage.query.filter_by(slug=slug).first()
+
+ @staticmethod
+ def create_page(data):
+ slug = StatusPageService.normalize_slug(data.get('slug'))
+ if StatusPage.query.filter_by(slug=slug).first():
+ raise ValueError(f"Status page '{slug}' already exists")
+
+ page = StatusPage(
+ name=data['name'],
+ slug=slug,
+ description=data.get('description', ''),
+ logo_url=data.get('logo_url'),
+ primary_color=data.get('primary_color', '#4f46e5'),
+ custom_domain=data.get('custom_domain'),
+ is_public=data.get('is_public', True),
+ show_uptime=data.get('show_uptime', True),
+ show_history=data.get('show_history', True),
+ )
+ db.session.add(page)
+ db.session.commit()
+ return page
+
+ @staticmethod
+ def update_page(page_id, data):
+ page = StatusPage.query.get(page_id)
+ if not page:
+ return None
+ for field in ['name', 'description', 'logo_url', 'primary_color',
+ 'custom_domain', 'is_public', 'show_uptime', 'show_history']:
+ if field in data:
+ setattr(page, field, data[field])
+ db.session.commit()
+ return page
+
+ @staticmethod
+ def delete_page(page_id):
+ page = StatusPage.query.get(page_id)
+ if not page:
+ return False
+ db.session.delete(page)
+ db.session.commit()
+ return True
+
+ @staticmethod
+ def get_public_page(slug):
+ """Get public status page data (no auth required)."""
+ page = StatusPage.query.filter_by(slug=slug, is_public=True).first()
+ if not page:
+ return None
+
+ # Internal probe config must not appear on the unauthenticated public page
+ # (a health-driven WP component may carry an internal localhost:port target).
+ public_hidden = ('check_type', 'check_target', 'check_interval', 'check_timeout',
+ 'check_method', 'expected_status', 'keyword', 'follow_redirects',
+ 'verify_tls', 'retries', 'consecutive_failures',
+ 'cert_issuer', 'cert_expires_at', 'next_check_at')
+ components = page.components.all()
+ grouped = {}
+ for comp in components:
+ group = comp.group or 'Services'
+ cd = comp.to_dict()
+ for k in public_hidden:
+ cd.pop(k, None)
+ grouped.setdefault(group, []).append(cd)
+
+ # Active incidents
+ active_incidents = page.incidents.filter(
+ StatusIncident.status != 'resolved'
+ ).limit(10).all()
+
+ # Recent resolved
+ resolved = page.incidents.filter_by(status='resolved').limit(5).all()
+
+ # Overall status
+ statuses = [c.status for c in components]
+ if any(s == 'major_outage' for s in statuses):
+ overall = 'major_outage'
+ elif any(s in ('partial_outage', 'degraded') for s in statuses):
+ overall = 'degraded'
+ elif any(s == 'maintenance' for s in statuses):
+ overall = 'maintenance'
+ else:
+ overall = 'operational'
+
+ return {
+ 'page': page.to_dict(),
+ 'overall_status': overall,
+ 'groups': grouped,
+ 'active_incidents': [i.to_dict() for i in active_incidents],
+ 'recent_incidents': [i.to_dict() for i in resolved],
+ }
+
+ # --- Components (monitors attached to a page) ---
+ # Delegates to MonitorService; a component is just a monitor with a page_id.
+
+ @staticmethod
+ def create_component(page_id, data):
+ page = StatusPage.query.get(page_id)
+ if not page:
+ raise ValueError('Status page not found')
+ return MonitorService.create({**data, 'page_id': page_id})
+
+ @staticmethod
+ def attach_component(page_id, monitor_id):
+ """Publish an existing monitor on a page. Lets an operator build a status
+ page out of monitors they already have instead of re-declaring probes."""
+ if not StatusPage.query.get(page_id):
+ raise ValueError('Status page not found')
+ return MonitorService.update(monitor_id, {'page_id': page_id})
+
+ @staticmethod
+ def detach_component(monitor_id):
+ """Remove a monitor from its page without deleting the monitor."""
+ return MonitorService.update(monitor_id, {'page_id': None})
+
+ @staticmethod
+ def update_component(comp_id, data):
+ return MonitorService.update(comp_id, data)
+
+ @staticmethod
+ def delete_component(comp_id):
+ return MonitorService.delete(comp_id)
+
+ # --- Health Checks (delegated to the core engine) ---
+
+ @staticmethod
+ def run_check(component_id):
+ return MonitorService.run_check(component_id)
+
+ @staticmethod
+ def get_check_history(component_id, hours=24):
+ return MonitorService.get_check_history(component_id, hours=hours)
+
+ @staticmethod
+ def recompute_uptime(comp):
+ return MonitorService.recompute_uptime(comp)
+
+ @staticmethod
+ def sync_component_from_health(comp, overall_status, error=None):
+ return MonitorService.sync_component_from_health(comp, overall_status, error)
+
+ # --- Incidents (delegated) ---
+
+ @staticmethod
+ def create_incident(page_id, data):
+ return MonitorService.create_incident(page_id, data)
+
+ @staticmethod
+ def update_incident(incident_id, data):
+ return MonitorService.update_incident(incident_id, data)
+
+ @staticmethod
+ def delete_incident(incident_id):
+ return MonitorService.delete_incident(incident_id)
+
+ @staticmethod
+ def get_badge(slug):
+ """Generate status badge data."""
+ page = StatusPage.query.filter_by(slug=slug).first()
+ if not page:
+ return None
+
+ components = page.components.all()
+ statuses = [c.status for c in components]
+
+ if not statuses or all(s == 'operational' for s in statuses):
+ return {'label': 'status', 'message': 'operational', 'color': 'brightgreen'}
+ elif any(s == 'major_outage' for s in statuses):
+ return {'label': 'status', 'message': 'major outage', 'color': 'red'}
+ elif any(s in ('partial_outage', 'degraded') for s in statuses):
+ return {'label': 'status', 'message': 'degraded', 'color': 'yellow'}
+ else:
+ return {'label': 'status', 'message': 'maintenance', 'color': 'blue'}
diff --git a/backend/app/plugins/serverkit-status/status_pages.py b/backend/app/plugins/serverkit-status/status_pages.py
new file mode 100644
index 00000000..a71540d0
--- /dev/null
+++ b/backend/app/plugins/serverkit-status/status_pages.py
@@ -0,0 +1,200 @@
+from flask import Blueprint, request, jsonify
+from flask_jwt_extended import jwt_required
+from app.middleware.rbac import get_current_user
+from .status_page_service import StatusPageService
+
+status_pages_bp = Blueprint('status_pages', __name__)
+
+
+# --- Public endpoints (no auth) ---
+
+@status_pages_bp.route('/public/<slug>', methods=['GET'])
+def get_public_page(slug):
+ data = StatusPageService.get_public_page(slug)
+ if not data:
+ return jsonify({'error': 'Status page not found'}), 404
+ return jsonify(data)
+
+
+@status_pages_bp.route('/badge/<slug>', methods=['GET'])
+def get_badge(slug):
+ badge = StatusPageService.get_badge(slug)
+ if not badge:
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify(badge)
+
+
+# --- Admin endpoints ---
+
+@status_pages_bp.route('/', methods=['GET'])
+@jwt_required()
+def list_pages():
+ pages = StatusPageService.list_pages()
+ return jsonify({'pages': [p.to_dict() for p in pages]})
+
+
+@status_pages_bp.route('/<int:page_id>', methods=['GET'])
+@jwt_required()
+def get_page(page_id):
+ page = StatusPageService.get_page(page_id)
+ if not page:
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify(page.to_dict())
+
+
+@status_pages_bp.route('/', methods=['POST'])
+@jwt_required()
+def create_page():
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ data = request.get_json()
+ if not data or 'name' not in data or 'slug' not in data:
+ return jsonify({'error': 'name and slug required'}), 400
+ try:
+ page = StatusPageService.create_page(data)
+ return jsonify(page.to_dict()), 201
+ except ValueError as e:
+ return jsonify({'error': str(e)}), 400
+
+
+@status_pages_bp.route('/<int:page_id>', methods=['PUT'])
+@jwt_required()
+def update_page(page_id):
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ data = request.get_json()
+ page = StatusPageService.update_page(page_id, data)
+ if not page:
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify(page.to_dict())
+
+
+@status_pages_bp.route('/<int:page_id>', methods=['DELETE'])
+@jwt_required()
+def delete_page(page_id):
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ if not StatusPageService.delete_page(page_id):
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify({'message': 'Status page deleted'})
+
+
+# --- Components ---
+
+@status_pages_bp.route('/<int:page_id>/components', methods=['GET'])
+@jwt_required()
+def get_components(page_id):
+ page = StatusPageService.get_page(page_id)
+ if not page:
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify({'components': [c.to_dict() for c in page.components.all()]})
+
+
+@status_pages_bp.route('/<int:page_id>/components', methods=['POST'])
+@jwt_required()
+def create_component(page_id):
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ data = request.get_json()
+ try:
+ comp = StatusPageService.create_component(page_id, data)
+ return jsonify(comp.to_dict()), 201
+ except ValueError as e:
+ return jsonify({'error': str(e)}), 400
+
+
+@status_pages_bp.route('/components/<int:comp_id>', methods=['PUT'])
+@jwt_required()
+def update_component(comp_id):
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ data = request.get_json()
+ comp = StatusPageService.update_component(comp_id, data)
+ if not comp:
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify(comp.to_dict())
+
+
+@status_pages_bp.route('/components/<int:comp_id>', methods=['DELETE'])
+@jwt_required()
+def delete_component(comp_id):
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ if not StatusPageService.delete_component(comp_id):
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify({'message': 'Component deleted'})
+
+
+@status_pages_bp.route('/components/<int:comp_id>/check', methods=['POST'])
+@jwt_required()
+def run_check(comp_id):
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ hc = StatusPageService.run_check(comp_id)
+ if not hc:
+ return jsonify({'error': 'Component not found'}), 404
+ return jsonify(hc.to_dict())
+
+
+@status_pages_bp.route('/components/<int:comp_id>/history', methods=['GET'])
+@jwt_required()
+def get_history(comp_id):
+ hours = request.args.get('hours', 24, type=int)
+ checks = StatusPageService.get_check_history(comp_id, hours)
+ return jsonify({'checks': [c.to_dict() for c in checks]})
+
+
+# --- Incidents ---
+
+@status_pages_bp.route('/<int:page_id>/incidents', methods=['GET'])
+@jwt_required()
+def list_incidents(page_id):
+ page = StatusPageService.get_page(page_id)
+ if not page:
+ return jsonify({'error': 'Not found'}), 404
+ incidents = page.incidents.limit(50).all()
+ return jsonify({'incidents': [i.to_dict() for i in incidents]})
+
+
+@status_pages_bp.route('/<int:page_id>/incidents', methods=['POST'])
+@jwt_required()
+def create_incident(page_id):
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ data = request.get_json()
+ if not data or 'title' not in data:
+ return jsonify({'error': 'title required'}), 400
+ incident = StatusPageService.create_incident(page_id, data)
+ return jsonify(incident.to_dict()), 201
+
+
+@status_pages_bp.route('/incidents/<int:incident_id>', methods=['PUT'])
+@jwt_required()
+def update_incident(incident_id):
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ data = request.get_json()
+ incident = StatusPageService.update_incident(incident_id, data)
+ if not incident:
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify(incident.to_dict())
+
+
+@status_pages_bp.route('/incidents/<int:incident_id>', methods=['DELETE'])
+@jwt_required()
+def delete_incident(incident_id):
+ user = get_current_user()
+ if not user or not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ if not StatusPageService.delete_incident(incident_id):
+ return jsonify({'error': 'Not found'}), 404
+ return jsonify({'message': 'Incident deleted'})
diff --git a/backend/tests/test_builtin_extension_drift.py b/backend/tests/test_builtin_extension_drift.py
index 3908336b..4575a480 100644
--- a/backend/tests/test_builtin_extension_drift.py
+++ b/backend/tests/test_builtin_extension_drift.py
@@ -13,11 +13,11 @@ Written while drift is **zero** (21 file pairs). That is the point — this lock
in a clean invariant rather than repairing a dirty one, and it only stays cheap
while that is true.
-Scope note: only pairs present on BOTH sides are compared. Several extensions
-legitimately have one side only — cloudflare-ops and localkit ship source with
-no materialised live copy, serverkit-git uses a different layout — and most live
-copies are gitignored, so a fresh clone sees fewer pairs than a dev machine.
-`test_drift_check_is_not_vacuous` stops that from quietly reducing to nothing.
+Scope note: only pairs present on BOTH sides are compared. Some extensions
+legitimately have one side only, and most live copies are gitignored, so a
+fresh clone sees fewer pairs than a dev machine. serverkit-status is the one
+live copy git tracks, so a fresh clone always has at least one comparable
+pair; `test_drift_check_is_not_vacuous` stops that reducing to nothing.
That machine-dependence is also why the test-count ratchet runs collection with
`SERVERKIT_CLEAN_COLLECT=1` — see `CLEAN_COLLECT` below.
@@ -149,15 +149,16 @@ def test_drift_check_is_not_vacuous():
"""Guard the guard.
Most live copies are gitignored, so a fresh clone sees far fewer pairs than
- a dev machine. serverkit-email's live copy predates that ignore rule and is
- tracked, so at least one extension must always be comparable. Without this,
- a reorganisation could silently reduce the parametrised test above to zero
- cases and it would still report green.
+ a dev machine. serverkit-status's live copy is deliberately tracked (see the
+ note in .gitignore), so at least one extension must always be comparable.
+ Without this, a reorganisation could silently reduce the parametrised test
+ above to zero cases and it would still report green -- which is exactly what
+ happened when serverkit-email, the previous anchor, left the tree in plan 52.
"""
assert PAIRS, (
'No extension had both a builtin-extensions/<ext>/backend and an '
'app/plugins/<ext> copy, so the drift check compared nothing. Either '
- 'the layout moved or the tracked serverkit-email copy is gone.'
+ 'the layout moved or the tracked serverkit-status copy is gone.'
)