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.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Protect ServerKit containers from lifecycle actions
Juan Denised2c9c342618
diff --git a/backend/app/api/docker.py b/backend/app/api/docker.pyindex db72d30b..d33b06f9 100644--- a/backend/app/api/docker.py+++ b/backend/app/api/docker.py@@ -114,11 +114,28 @@ def start_container(container_id):return jsonify(result), 200 if result['success'] else 400+def _reject_if_protected(container_id):+ """Return a 403 response if the container is ServerKit's own, else None.++ Stopping/restarting/removing the panel's own containers would take+ ServerKit offline, so these lifecycle actions are blocked outright.+ """+ if DockerService.is_protected_container(container_id):+ return jsonify({+ 'error': 'This is a ServerKit system container and cannot be '+ 'controlled from here. Managing it would take the panel offline.'+ }), 403+ return None++@docker_bp.route('/containers/<container_id>/stop', methods=['POST'])@jwt_required()@admin_requireddef stop_container(container_id):"""Stop a container."""+ blocked = _reject_if_protected(container_id)+ if blocked:+ return blockeddata = request.get_json() or {}timeout = data.get('timeout', 10)result = DockerService.stop_container(container_id, timeout)@@ -130,27 +147,23 @@ def stop_container(container_id):@admin_requireddef restart_container(container_id):"""Restart a container."""+ blocked = _reject_if_protected(container_id)+ if blocked:+ return blockeddata = request.get_json() or {}timeout = data.get('timeout', 10)result = DockerService.restart_container(container_id, timeout)return jsonify(result), 200 if result['success'] else 400-PROTECTED_CONTAINERS = ['serverkit-frontend', 'serverkit_frontend', 'serverkit']-@docker_bp.route('/containers/<container_id>', methods=['DELETE'])@jwt_required()@admin_requireddef remove_container(container_id):"""Remove a container."""- # Protect ServerKit containers from deletion- container = DockerService.get_container(container_id)- if container:- container_name = container.get('name', '').lower().replace('/', '')- if any(protected in container_name for protected in PROTECTED_CONTAINERS):- return jsonify({- 'error': 'Cannot delete ServerKit system container. This container is required for the panel to function.'- }), 403+ blocked = _reject_if_protected(container_id)+ if blocked:+ return blockeddata = request.get_json() or {}force = data.get('force', False)@@ -485,7 +498,7 @@ def docker_cleanup():parts = line.split(' ', 1)if len(parts) == 2:container_id, name = parts- if any(p in name.lower() for p in PROTECTED_CONTAINERS):+ if DockerService.is_protected_name(name):protected_ids.add(container_id)except Exception:passdiff --git a/backend/app/services/docker_service.py b/backend/app/services/docker_service.pyindex d8d5ac4d..421a75e7 100644--- a/backend/app/services/docker_service.py+++ b/backend/app/services/docker_service.py@@ -66,6 +66,37 @@ class DockerService:# ==================== CONTAINER MANAGEMENT ====================+ # ServerKit's own infrastructure containers run the panel itself, so their+ # lifecycle must never be controllable from the Docker page — stopping,+ # restarting or removing one would take ServerKit offline. Matched as a+ # substring (case-insensitive) so both compose project names and the bare+ # service names ('serverkit-backend', 'serverkit_frontend', ...) are caught.+ PROTECTED_CONTAINER_NAMES = (+ 'serverkit-frontend', 'serverkit_frontend',+ 'serverkit-backend', 'serverkit_backend',+ 'serverkit',+ )++ @staticmethod+ def is_protected_name(name):+ """True if a container name belongs to ServerKit's own infrastructure."""+ if not name:+ return False+ normalized = str(name).lower().replace('/', '')+ return any(p in normalized for p in DockerService.PROTECTED_CONTAINER_NAMES)++ @staticmethod+ def is_protected_container(container_id):+ """Resolve a container id/name to its real name and check protection.++ Accepts either an id or a name. Uses `docker inspect`, whose top-level+ ``Name`` key is the canonical name (e.g. ``/serverkit-backend``).+ """+ container = DockerService.get_container(container_id)+ name = (container or {}).get('Name', '') if container else ''+ # Fall back to the id itself when the user passed a name directly.+ return DockerService.is_protected_name(name) or DockerService.is_protected_name(container_id)+@staticmethoddef list_containers(all_containers=True):"""List Docker containers."""@@ -82,15 +113,19 @@ class DockerService:for line in result.stdout.strip().split('\n'):if line:container = json.loads(line)+ name = container.get('Names')containers.append({'id': container.get('ID'),- 'name': container.get('Names'),+ 'name': name,'image': container.get('Image'),'status': container.get('Status'),'state': container.get('State'),'ports': container.get('Ports'),'created': container.get('CreatedAt'),'size': container.get('Size'),+ # Flag ServerKit's own containers so the UI can hide+ # lifecycle controls; the API rejects them regardless.+ 'protected': DockerService.is_protected_name(name),})return containersexcept Exception as e:diff --git a/backend/tests/test_docker_protection.py b/backend/tests/test_docker_protection.pynew file mode 100644index 00000000..18f34942--- /dev/null+++ b/backend/tests/test_docker_protection.py@@ -0,0 +1,97 @@+"""Tests for ServerKit system-container protection on the Docker page.++ServerKit's own containers (serverkit-frontend / serverkit-backend) run the+panel itself, so the Docker API must refuse to stop/restart/remove them and the+container list must flag them so the UI can hide lifecycle controls.++The predicate and the list annotation are pure (subprocess is mocked); the+route guard tests drive the real blueprint with an admin JWT.+"""+from unittest.mock import patch++import pytest++from app.services.docker_service import DockerService+++class TestIsProtectedName:+ @pytest.mark.parametrize('name', [+ 'serverkit-frontend',+ 'serverkit_frontend',+ 'serverkit-backend',+ 'serverkit_backend',+ 'serverkit',+ '/serverkit-backend', # docker inspect Name has a leading slash+ 'SERVERKIT-FRONTEND', # case-insensitive+ ])+ def test_serverkit_names_are_protected(self, name):+ assert DockerService.is_protected_name(name) is True++ @pytest.mark.parametrize('name', [+ 'nginx',+ 'my-app_web_1',+ 'postgres',+ '',+ None,+ ])+ def test_other_names_are_not_protected(self, name):+ assert DockerService.is_protected_name(name) is False+++class TestListContainersAnnotation:+ def _fake_ps(self, names):+ lines = '\n'.join(+ '{"ID": "abc%d", "Names": "%s", "Image": "img", "Status": "Up", '+ '"State": "running", "Ports": "", "CreatedAt": "now", "Size": "0B"}'+ % (i, n)+ for i, n in enumerate(names)+ )++ class _Result:+ returncode = 0+ stdout = lines++ return _Result()++ def test_protected_flag_set_per_container(self):+ with patch('subprocess.run', return_value=self._fake_ps(['serverkit-backend', 'nginx'])):+ containers = DockerService.list_containers()++ by_name = {c['name']: c for c in containers}+ assert by_name['serverkit-backend']['protected'] is True+ assert by_name['nginx']['protected'] is False+++class TestIsProtectedContainer:+ def test_resolves_name_from_inspect(self):+ # docker inspect returns the canonical Name with a leading slash.+ with patch.object(DockerService, 'get_container', return_value={'Name': '/serverkit-frontend'}):+ assert DockerService.is_protected_container('abc123') is True++ def test_unknown_container_not_protected(self):+ with patch.object(DockerService, 'get_container', return_value=None):+ assert DockerService.is_protected_container('abc123') is False+++class TestRouteGuards:+ """The destructive lifecycle routes must 403 on a protected container."""++ @pytest.mark.parametrize('method,path', [+ ('post', '/api/v1/docker/containers/abc123/stop'),+ ('post', '/api/v1/docker/containers/abc123/restart'),+ ('delete', '/api/v1/docker/containers/abc123'),+ ])+ def test_protected_container_is_rejected(self, client, auth_headers, method, path):+ with patch.object(DockerService, 'is_protected_container', return_value=True):+ resp = getattr(client, method)(path, headers=auth_headers, json={})+ assert resp.status_code == 403+ assert 'system container' in resp.get_json()['error'].lower()++ def test_normal_container_stop_passes_through(self, client, auth_headers):+ with patch.object(DockerService, 'is_protected_container', return_value=False), \+ patch.object(DockerService, 'stop_container', return_value={'success': True}) as stop:+ resp = client.post(+ '/api/v1/docker/containers/abc123/stop', headers=auth_headers, json={}+ )+ assert resp.status_code == 200+ stop.assert_called_once()diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 1d0aa970..ab4f41c4 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -45,6 +45,7 @@ import { MARKET_TABS } from './components/marketplace/marketTabs';import { WORDPRESS_TABS } from './components/wordpress/wordpressTabs';import { BACKUP_TABS } from './components/backups/backupTabs';import { SECURITY_TABS } from './components/security/securityTabs';+import { ORG_TABS } from './components/organization/organizationTabs';import Downloads from './pages/Downloads';import WordPress from './pages/WordPress';import WordPressDetail from './pages/WordPressDetail';@@ -362,11 +363,16 @@ function AppRoutes() {<Route path="servers/:id" element={<ServerDetail />} /><Route path="servers/:id/:tab" element={<ServerDetail />} /><Route path="agent-plugins" element={<Navigate to="/marketplace" replace />} />- <Route path="projects" element={<Projects />} />+ {/* Organization tab group — Projects / Shared Variables /+ Workspaces share one PageTopbar + tabs (ORG_TABS) instead of+ a collapsible sidebar sub-menu. Detail routes stay outside. */}+ <Route element={<TabGroupLayout tabs={ORG_TABS} />}>+ <Route path="projects" element={<Projects />} />+ <Route path="shared-variables" element={<SharedVariables />} />+ <Route path="workspaces" element={<Workspaces />} />+ </Route><Route path="projects/:id" element={<ProjectDetail />} /><Route path="projects/:id/:tab" element={<ProjectDetail />} />- <Route path="shared-variables" element={<SharedVariables />} />- <Route path="workspaces" element={<Workspaces />} /><Route path="workspaces/:id" element={<WorkspaceDetail />} /><Route path="workspaces/:id/:tab" element={<WorkspaceDetail />} /><Route path="workspaces/:id/:tab/:section" element={<WorkspaceDetail />} />diff --git a/frontend/src/components/organization/organizationTabs.jsx b/frontend/src/components/organization/organizationTabs.jsxnew file mode 100644index 00000000..e29ab0b3--- /dev/null+++ b/frontend/src/components/organization/organizationTabs.jsx@@ -0,0 +1,13 @@+import { FolderKanban, Braces, LayoutGrid } from 'lucide-react';++// Shared sub-nav for the Organization page group (Projects / Shared Variables /+// Workspaces). Rendered in the shared PageTopbar via TabGroupLayout — the+// top-bar layout replaces the old collapsible sidebar sub-menu, matching every+// other group (Servers, Domains, Services, …). See docs/REDESIGN_MAP.md §6+// decision 3. Routes /projects, /shared-variables, /workspaces are unchanged+// and still reachable from these tabs.+export const ORG_TABS = [+ { to: '/projects', label: 'Projects', end: true, icon: <FolderKanban size={15} /> },+ { to: '/shared-variables', label: 'Shared Variables', icon: <Braces size={15} /> },+ { to: '/workspaces', label: 'Workspaces', icon: <LayoutGrid size={15} /> },+];diff --git a/frontend/src/components/sidebarItems.js b/frontend/src/components/sidebarItems.jsindex 2f61034a..66eaf549 100644--- a/frontend/src/components/sidebarItems.js+++ b/frontend/src/components/sidebarItems.js@@ -4,6 +4,7 @@ import { SERVICE_TABS } from './services/serviceTabs';import { FILE_TABS } from './files/fileTabs';import { MONITOR_TABS } from './monitoring/monitorTabs';import { MARKET_TABS } from './marketplace/marketTabs';+import { ORG_TABS } from './organization/organizationTabs';// Path prefixes for a tab group, used to keep the group's sidebar item lit// across all its tabs (e.g. Servers stays active on /fleet, /cloud, …).@@ -34,36 +35,17 @@ export const SIDEBAR_ITEMS = [},{// "Organization" groups the cross-cutting features that structure work- // across a team/account — Projects, Shared Variables, and Workspaces —- // so they don't each clutter the top level. Renders as a collapsible- // group (Sidebar.renderNavItem handles item.subItems). matchPrefixes- // keeps the group lit on any of its sub-routes.+ // across a team/account — Projects, Shared Variables, and Workspaces.+ // Like every other group (Servers, Domains, …) it uses the top-bar tab+ // layout, NOT a collapsible sidebar sub-menu: the sub-nav lives in the+ // page's PageTopbar (ORG_TABS via TabGroupLayout). matchPrefixes keeps+ // the single sidebar item lit across all three routes.id: 'organization',label: 'Organization',route: '/projects',- matchPrefixes: ['/projects', '/shared-variables', '/workspaces'],+ matchPrefixes: groupPrefixes(ORG_TABS),category: 'overview',icon: '<path d="M3 21h18"/><path d="M5 21V7l8-4v18"/><path d="M19 21V11l-6-4"/><path d="M9 9v.01"/><path d="M9 12v.01"/><path d="M9 15v.01"/><path d="M9 18v.01"/>',- subItems: [- {- id: 'projects',- label: 'Projects',- route: '/projects',- icon: '<path d="M3 7a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.7.9H19a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>'- },- {- id: 'shared-variables',- label: 'Shared Variables',- route: '/shared-variables',- icon: '<path d="M4 7h16M4 12h16M4 17h10"/><circle cx="18" cy="17" r="2"/>'- },- {- id: 'workspaces',- label: 'Workspaces',- route: '/workspaces',- icon: '<path d="M3 3h7v7H3zM14 3h7v7h-7zM14 14h7v7h-7zM3 14h7v7H3z"/>'- }- ]},{// Redesign: Servers uses the top-bar layout (REDESIGN_MAP §6 decision 3).diff --git a/frontend/src/pages/Docker.jsx b/frontend/src/pages/Docker.jsxindex f358ed02..c9a62822 100644--- a/frontend/src/pages/Docker.jsx+++ b/frontend/src/pages/Docker.jsx@@ -14,7 +14,7 @@ import { MetricCard } from '@/components/ds';import {Box, Layers, HardDrive, Network as NetworkIcon, Search, X, RefreshCw,Trash2, Play, Square, RotateCw, Terminal as TerminalLucide, FileText,- Activity, Clock3, Copy, Database, Gauge, Package, Server as ServerIcon, ArrowUpDown,+ Activity, Clock3, Copy, Database, Gauge, Package, Server as ServerIcon, ArrowUpDown, Lock,} from 'lucide-react';// Server context for Docker operations@@ -93,6 +93,17 @@ const getContainerState = (container) => {const isContainerRunning = (container) => getContainerState(container) === 'running';+// ServerKit's own infrastructure containers run the panel itself, so we don't+// expose lifecycle controls (start/stop/restart/remove) for them — the backend+// rejects those calls anyway. Trust the backend `protected` flag when present;+// fall back to a name check for shapes (e.g. remote agents) that omit it.+const SELF_CONTAINER_HINTS = ['serverkit-frontend', 'serverkit_frontend', 'serverkit-backend', 'serverkit_backend'];+const isProtectedContainer = (container) => {+ if (container?.protected === true) return true;+ const name = getContainerName(container).toLowerCase().replace(/\//g, '');+ return SELF_CONTAINER_HINTS.some(hint => name.includes(hint));+};+const getContainerStatusLabel = (container) => {if (isContainerRunning(container)) return 'Running';const state = getContainerState(container);@@ -925,6 +936,7 @@ const ContainersTab = ({ onStatsChange }) => {const containerId = getContainerId(container);const stats = parseStats(containerStats[containerId]);const isRunning = isContainerRunning(container);+ const isProtected = isProtectedContainer(container);const ports = formatPorts(container.ports);const isSelected = getContainerId(selectedContainer) === containerId;return (@@ -987,7 +999,11 @@ const ContainersTab = ({ onStatsChange }) => {<TerminalLucide size={13} /></button>)}- {isRunning ? (+ {isProtected ? (+ <span className="dx-row-protected" title="ServerKit system container — managed by the panel, lifecycle controls are disabled">+ <Lock size={11} /> System+ </span>+ ) : isRunning ? (<><button className="dx-row-action" onClick={() => handleAction(containerId, 'restart')} title="Restart"><RotateCw size={13} />@@ -1136,6 +1152,7 @@ const ContainerInspector = ({ container, stats, onAction, onOpenLogs, onOpenExec}const isRunning = isContainerRunning(container);+ const isProtected = isProtectedContainer(container);const ports = formatPorts(container.ports);const envVars = details?.Config?.Env || [];const mounts = details?.Mounts || [];@@ -1190,7 +1207,11 @@ const ContainerInspector = ({ container, stats, onAction, onOpenLogs, onOpenExec<TerminalLucide size={13} /> Exec</button>)}- {isRunning ? (+ {isProtected ? (+ <span className="dx-action-protected" title="ServerKit system container — managed by the panel, lifecycle controls are disabled">+ <Lock size={13} /> System container+ </span>+ ) : isRunning ? (<><button className="dx-action-btn" onClick={() => onAction(containerId, 'restart')}><RotateCw size={13} /> Restartdiff --git a/frontend/src/pages/Projects.jsx b/frontend/src/pages/Projects.jsxindex 687b3fb9..3fe6018e 100644--- a/frontend/src/pages/Projects.jsx+++ b/frontend/src/pages/Projects.jsx@@ -4,7 +4,7 @@ import { FolderKanban, Plus, Layers, Boxes } from 'lucide-react';import api from '../services/api';import { useToast } from '../contexts/ToastContext';import EmptyState from '../components/EmptyState';-import { PageTopbar } from '@/components/ds';+import { useTopbarActions } from '@/hooks/useTopbarActions';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';@@ -41,19 +41,14 @@ const Projects = () => {loadProjects();}, [loadProjects]);- return (- <div className="projects-page">- <PageTopbar- icon={<FolderKanban size={20} />}- title="Projects"- meta={projects.length ? `${projects.length} project${projects.length === 1 ? '' : 's'}` : null}- actions={- <Button onClick={() => setShowCreate(true)}>- <Plus size={16} /> New Project- </Button>- }- />+ useTopbarActions(() => (+ <Button onClick={() => setShowCreate(true)}>+ <Plus size={16} /> New Project+ </Button>+ ), []);+ return (+ <div className="sk-tabgroup__inner projects-page"><div className="projects-page__body">{loading ? (<EmptyState loading title="Loading projects" />diff --git a/frontend/src/pages/SharedVariables.jsx b/frontend/src/pages/SharedVariables.jsxindex 54bcb862..595e1ae2 100644--- a/frontend/src/pages/SharedVariables.jsx+++ b/frontend/src/pages/SharedVariables.jsx@@ -9,7 +9,7 @@ const SharedVariables = () => {const workspaceId = localStorage.getItem('active_workspace_id') || 'default';return (- <div className="page-container shared-variables-page">+ <div className="sk-tabgroup__inner shared-variables-page"><SharedVariableGroups scopeType="workspace" scopeId={workspaceId} /></div>);diff --git a/frontend/src/pages/Workspaces.jsx b/frontend/src/pages/Workspaces.jsxindex abcd3fcd..eb69f5b9 100644--- a/frontend/src/pages/Workspaces.jsx+++ b/frontend/src/pages/Workspaces.jsx@@ -5,7 +5,8 @@ import { useToast } from '../contexts/ToastContext';import Spinner from '../components/Spinner';import EmptyState from '../components/EmptyState';import { LayoutGrid, Plus, ChevronRight, Search } from 'lucide-react';-import { PageTopbar, Pill, SegControl, ServiceTile } from '@/components/ds';+import { Pill, SegControl, ServiceTile } from '@/components/ds';+import { useTopbarActions } from '@/hooks/useTopbarActions';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Textarea } from '@/components/ui/textarea';@@ -49,6 +50,13 @@ const Workspaces = () => {useEffect(() => { loadWorkspaces(); }, [loadWorkspaces]);+ useTopbarActions(() => (+ <Button size="sm" onClick={() => setShowCreateModal(true)}>+ <Plus size={16} />+ New Workspace+ </Button>+ ), []);+const handleCreate = async () => {try {await api.createWorkspace(form);@@ -61,7 +69,7 @@ const Workspaces = () => {}};- if (loading) return <div className="page-container workspaces-page"><Spinner /></div>;+ if (loading) return <div className="sk-tabgroup__inner workspaces-page"><Spinner /></div>;const q = search.trim().toLowerCase();const shownWorkspaces = workspaces.filter(ws => {@@ -75,19 +83,7 @@ const Workspaces = () => {const activeCount = workspaces.filter(ws => ws.status === 'active').length;return (- <div className="page-container workspaces-page">- <PageTopbar- icon={<LayoutGrid size={18} />}- title="Workspaces"- meta={`${workspaces.length} workspace${workspaces.length !== 1 ? 's' : ''}`}- actions={(- <Button size="sm" onClick={() => setShowCreateModal(true)}>- <Plus size={16} />- New Workspace- </Button>- )}- />-+ <div className="sk-tabgroup__inner workspaces-page">{workspaces.length === 0 ? (<EmptyStateicon={LayoutGrid}diff --git a/frontend/src/styles/pages/_docker.scss b/frontend/src/styles/pages/_docker.scssindex a52b9a49..1d27528f 100644--- a/frontend/src/styles/pages/_docker.scss+++ b/frontend/src/styles/pages/_docker.scss@@ -1498,6 +1498,36 @@}}+// "System container" markers shown in place of lifecycle controls for+// ServerKit's own containers — read-only, never interactive.+.dx-row-protected {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ height: 28px;+ padding: 0 $space-2;+ border: 1px dashed $border-default;+ border-radius: $radius-sm;+ color: $text-tertiary;+ font-size: $font-size-xs;+ white-space: nowrap;+ cursor: default;+}++.dx-action-protected {+ min-height: 30px;+ display: inline-flex;+ align-items: center;+ gap: $space-2;+ padding: 0 $space-3;+ border: 1px dashed $border-default;+ border-radius: $radius-sm;+ color: $text-tertiary;+ font-size: $font-size-xs;+ white-space: nowrap;+ cursor: default;+}+.dx-inspector {display: flex;flex-direction: column;diff --git a/frontend/src/styles/pages/_projects.scss b/frontend/src/styles/pages/_projects.scssindex 190e4033..6204e091 100644--- a/frontend/src/styles/pages/_projects.scss+++ b/frontend/src/styles/pages/_projects.scss@@ -9,8 +9,10 @@flex-direction: column;min-height: 100%;+ // Outer padding/centering is supplied by the enclosing .sk-tabgroup__inner+ // (the page is a child of the Organization TabGroupLayout) — the body only+ // owns its internal stacking.&__body {- padding: $space-6;display: flex;flex-direction: column;gap: $space-6;diff --git a/frontend/src/styles/pages/_workspaces.scss b/frontend/src/styles/pages/_workspaces.scssindex db1532b5..625f76f8 100644--- a/frontend/src/styles/pages/_workspaces.scss+++ b/frontend/src/styles/pages/_workspaces.scss@@ -5,7 +5,9 @@.workspaces-page {// Dense table list reuses the WordPress .wp-list + .sk-dtable primitives.- .wp-list { padding: $space-4; }+ // Outer padding/centering comes from the enclosing .sk-tabgroup__inner+ // (Organization tab group), so the list itself stays flush.+ .wp-list { padding: 0; }// ── modals: mono eyebrow headings + soft separators ─────.modal-body {