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
feat(plugins): let extensions run commands on the fleet
Juan Denis047e69501aa5
diff --git a/backend/app/plugins_sdk/__init__.py b/backend/app/plugins_sdk/__init__.pyindex a2a23c8e..fe066c29 100644--- a/backend/app/plugins_sdk/__init__.py+++ b/backend/app/plugins_sdk/__init__.py@@ -106,6 +106,7 @@ _LAZY_SURFACES = {'store': ('app.plugins_sdk.store_sdk', 'store'),'doctor': ('app.plugins_sdk.doctor_sdk', 'doctor'),'backups': ('app.plugins_sdk.backups_sdk', 'backups'),+ 'agents': ('app.plugins_sdk.agents_sdk', 'agents'),}_lazy_cache = {}@@ -150,6 +151,7 @@ __all__ = ['store','doctor','backups',+ 'agents','permissions','require_permission','panel_version',diff --git a/backend/app/plugins_sdk/agents_sdk.py b/backend/app/plugins_sdk/agents_sdk.pynew file mode 100644index 00000000..bb776069--- /dev/null+++ b/backend/app/plugins_sdk/agents_sdk.py@@ -0,0 +1,145 @@+"""Plugin-facing SDK for running commands on managed servers.++ from app.plugins_sdk import agents++ fleet = agents.for_plugin('serverkit-gui')+ shot = fleet.run(server_id, 'gui:screenshot', {'display': ':0'},+ requires='gui.screenshot')++Without this, an extension was effectively local-panel-only: everything it+could do stopped at the machine the panel runs on, which is at odds with a+product built around a fleet.++**This is where ``agent.command:<action>`` finally means something.** The+manifest permission has existed as a declaration — surfaced at install time for+consent — with nothing enforcing it, because plugins called the agent registry+directly. Going through the SDK checks it before dispatch, so a plugin can only+run the actions it asked the operator for, by name.++The panel's own guarantees still apply underneath and are not re-implemented+here: the per-server ACL decides whether that server permits the action at all,+and every command is recorded as a ServerCommand row — pass ``user_id`` so it+is attributable to a person rather than to "the panel".++``run()`` returns the agent's payload and raises :class:`AgentCommandError` for+anything else, with ``.code`` carrying why (``AGENT_OFFLINE``,+``PERMISSION_DENIED``, ``TIMEOUT``, ``UNSUPPORTED``, ...). It also unwraps the+double envelope: a transport-successful reply can still carry a handler failure+inside, which is easy to miss and reads as success.+"""++import logging++logger = logging.getLogger(__name__)++#: Longer than the registry's own 30s default on purpose. An agent on the HTTP+#: long-poll fallback can sit up to ~25s before it even sees the command, which+#: leaves a 30s budget almost no room to run anything.+DEFAULT_TIMEOUT = 45.0+++class AgentCommandError(RuntimeError):+ """A command that did not reach the agent, or did not succeed there."""++ def __init__(self, message, code=None, data=None):+ super().__init__(message)+ self.code = code or 'AGENT_ERROR'+ self.data = data+++class BoundAgents:+ """The fleet as seen by one plugin. Get it from ``agents.for_plugin()``."""++ def __init__(self, slug):+ if not slug or not isinstance(slug, str):+ raise ValueError('an agent surface needs a plugin slug')+ self.slug = slug++ # ------------------------------------------------------------------ read+ def online(self):+ """Server ids with a live agent connection."""+ return list(_registry().get_connected_servers())++ def is_online(self, server_id):+ """True if *server_id* has a live agent connection."""+ return bool(_registry().is_agent_connected(server_id))++ def capabilities(self, server_id):+ """What the agent on *server_id* reports it can do (``{}`` if unknown)."""+ return _registry().get_capabilities(server_id) or {}++ def has_capability(self, server_id, capability):+ """True if the agent on *server_id* reports *capability*."""+ return bool(_registry().has_capability(server_id, capability))++ # ------------------------------------------------------------------- run+ def run(self, server_id, action, params=None, timeout=DEFAULT_TIMEOUT,+ user_id=None, requires=None):+ """Run *action* on *server_id* and return the agent's payload.++ Raises :class:`AgentCommandError` if the command didn't run or didn't+ succeed. Declare ``agent.command:<action>`` in your manifest first —+ verbatim, so ``gui:screenshot`` is ``agent.command:gui:screenshot``.++ Pass *requires* to check the agent reports a capability before+ dispatching, so an old agent fails with a clear reason instead of an+ unknown-action error from the far side.+ """+ if not server_id:+ raise AgentCommandError('No server given', code='NO_SERVER')+ if not action:+ raise AgentCommandError('No action given', code='NO_ACTION')++ # The gate the manifest has been promising all along.+ from app.plugins_sdk import permissions+ permissions.require(self.slug, f'agent.command:{action}')++ registry = _registry()+ if not registry.is_agent_connected(server_id):+ raise AgentCommandError(+ f'No agent connected for server {server_id}', code='AGENT_OFFLINE')+ if requires and not registry.has_capability(server_id, requires):+ raise AgentCommandError(+ f"The agent on {server_id} does not support '{requires}'",+ code='UNSUPPORTED')++ result = registry.send_command(+ server_id=server_id, action=action, params=params or {},+ timeout=float(timeout), user_id=user_id,+ ) or {}++ if not result.get('success'):+ raise AgentCommandError(+ result.get('error') or f'Agent command failed: {action}',+ code=result.get('code'), data=result.get('data'))++ data = result.get('data')+ if isinstance(data, dict) and data.get('success') is False:+ # Transport succeeded, the handler on the far side did not. Easy to+ # miss, and it reads as success to anyone checking only the outer+ # envelope.+ raise AgentCommandError(+ data.get('error') or f'Agent command failed: {action}',+ code=data.get('code') or 'HANDLER_ERROR', data=data)+ return data+++class AgentsSdk:+ """Stable fleet surface for plugins."""++ #: Raised by :meth:`BoundAgents.run`; exposed so a plugin can catch it+ #: without importing a host module path.+ CommandError = AgentCommandError+ DEFAULT_TIMEOUT = DEFAULT_TIMEOUT++ def for_plugin(self, slug):+ """The fleet surface for *slug*, gated by that plugin's permissions."""+ return BoundAgents(slug)+++def _registry():+ from app.services.agent_registry import agent_registry+ return agent_registry+++agents = AgentsSdk()diff --git a/backend/tests/test_plugin_agents_sdk.py b/backend/tests/test_plugin_agents_sdk.pynew file mode 100644index 00000000..e4f13063--- /dev/null+++ b/backend/tests/test_plugin_agents_sdk.py@@ -0,0 +1,170 @@+"""Running agent commands from a plugin (plugins_sdk.agents).++Two things this pins down:++* An extension can reach the fleet at all. Before it, everything a plugin could+ do stopped at the machine the panel runs on.+* ``agent.command:<action>`` is now enforced. The manifest permission existed as+ a declaration shown at install time, with nothing checking it — plugins called+ the agent registry directly. Going through the SDK makes the consent dialog+ mean what it says.+"""++import pytest++from app import db+from app.plugins_sdk import permissions+from app.plugins_sdk.agents_sdk import AgentCommandError, agents+from app.services import agent_registry as agent_registry_module++SERVER = 'server-uuid-1'+++def installed(app):+ """An installed plugin declaring one agent-command permission."""+ from app.models.plugin import InstalledPlugin++ plugin = InstalledPlugin(slug='serverkit-demo', name='serverkit-demo',+ display_name='Demo', version='1.0.0',+ status=InstalledPlugin.STATUS_ACTIVE)+ plugin.manifest = {'permissions': ['agent.command:gui:screenshot']}+ db.session.add(plugin)+ db.session.commit()+ return agents.for_plugin('serverkit-demo')+++def fleet(monkeypatch):+ """A connected agent whose responses each test can steer."""+ registry = agent_registry_module.agent_registry+ state = {'sent': [], 'reply': {'success': True, 'data': {'png': 'base64...'}},+ 'connected': True, 'capabilities': {'gui.screenshot': True}}++ def _send(server_id, action, params=None, timeout=None, user_id=None):+ state['sent'].append({'server_id': server_id, 'action': action,+ 'params': params, 'timeout': timeout,+ 'user_id': user_id})+ return state['reply']++ monkeypatch.setattr(registry, 'send_command', _send)+ monkeypatch.setattr(registry, 'is_agent_connected',+ lambda sid: state['connected'])+ monkeypatch.setattr(registry, 'get_capabilities',+ lambda sid: state['capabilities'])+ monkeypatch.setattr(registry, 'has_capability',+ lambda sid, cap: bool(state['capabilities'].get(cap)))+ monkeypatch.setattr(registry, 'get_connected_servers',+ lambda: [SERVER] if state['connected'] else [])+ return state+++class TestPermissionGate:+ def test_a_declared_action_is_allowed(self, app, installed, fleet):+ assert installed.run(SERVER, 'gui:screenshot') == {'png': 'base64...'}++ def test_an_undeclared_action_is_refused_before_dispatch(self, app, installed, fleet):+ with pytest.raises(permissions.PermissionDenied):+ installed.run(SERVER, 'file:write', {'path': '/etc/passwd'})+ # Refused, not merely reported: nothing reached the agent.+ assert fleet['sent'] == []++ def test_the_permission_is_matched_verbatim(self, app, installed, fleet):+ # 'agent.command:gui:screenshot' must not also authorise 'gui:record'+ # just because it shares a prefix.+ with pytest.raises(permissions.PermissionDenied):+ installed.run(SERVER, 'gui:record')++ def test_an_uninstalled_plugin_has_no_permissions(self, app, fleet):+ with pytest.raises(permissions.PermissionDenied):+ agents.for_plugin('never-installed').run(SERVER, 'gui:screenshot')+++class TestDispatch:+ def test_passes_through_params_and_attribution(self, app, installed, fleet):+ installed.run(SERVER, 'gui:screenshot', {'display': ':0'}, user_id=42)++ sent = fleet['sent'][0]+ assert sent['params'] == {'display': ':0'}+ # user_id is what makes the ServerCommand audit row name a person.+ assert sent['user_id'] == 42++ def test_default_timeout_leaves_room_for_a_polling_agent(self, app, installed, fleet):+ installed.run(SERVER, 'gui:screenshot')+ # A poll-transport agent can sit ~25s before it sees the command.+ assert fleet['sent'][0]['timeout'] >= 45.0++ def test_offline_agent_is_refused_without_dispatching(self, app, installed, fleet):+ fleet['connected'] = False+ with pytest.raises(AgentCommandError) as excinfo:+ installed.run(SERVER, 'gui:screenshot')+ assert excinfo.value.code == 'AGENT_OFFLINE'+ assert fleet['sent'] == []++ def test_a_missing_capability_is_refused_with_a_reason(self, app, installed, fleet):+ fleet['capabilities'] = {}+ with pytest.raises(AgentCommandError) as excinfo:+ installed.run(SERVER, 'gui:screenshot', requires='gui.screenshot')+ # Better than an unknown-action error from the far side.+ assert excinfo.value.code == 'UNSUPPORTED'+ assert fleet['sent'] == []++ def test_missing_arguments_are_refused(self, app, installed, fleet):+ with pytest.raises(AgentCommandError):+ installed.run('', 'gui:screenshot')+ with pytest.raises(AgentCommandError):+ installed.run(SERVER, '')+++class TestFailures:+ def test_a_failed_command_raises_with_its_code(self, app, installed, fleet):+ fleet['reply'] = {'success': False, 'error': 'Command timeout',+ 'code': 'TIMEOUT'}+ with pytest.raises(AgentCommandError) as excinfo:+ installed.run(SERVER, 'gui:screenshot')+ assert excinfo.value.code == 'TIMEOUT'+ assert 'Command timeout' in str(excinfo.value)++ def test_a_handler_failure_inside_a_successful_reply_still_raises(+ self, app, installed, fleet):+ # The double envelope: transport succeeded, the handler on the far side+ # did not. Checking only the outer 'success' reads this as a win.+ fleet['reply'] = {'success': True,+ 'data': {'success': False, 'error': 'no display'}}+ with pytest.raises(AgentCommandError) as excinfo:+ installed.run(SERVER, 'gui:screenshot')+ assert 'no display' in str(excinfo.value)++ def test_permission_denied_from_the_server_acl_surfaces(self, app, installed, fleet):+ # The per-server ACL is a separate gate from the manifest permission,+ # and the plugin should be able to tell them apart by code.+ fleet['reply'] = {'success': False, 'error': 'Permission denied for action',+ 'code': 'PERMISSION_DENIED'}+ with pytest.raises(AgentCommandError) as excinfo:+ installed.run(SERVER, 'gui:screenshot')+ assert excinfo.value.code == 'PERMISSION_DENIED'++ def test_an_empty_reply_is_a_failure_not_a_success(self, app, installed, fleet):+ fleet['reply'] = None+ with pytest.raises(AgentCommandError):+ installed.run(SERVER, 'gui:screenshot')+++class TestReads:+ def test_online_and_capabilities(self, app, installed, fleet):+ assert installed.online() == [SERVER]+ assert installed.is_online(SERVER) is True+ assert installed.capabilities(SERVER) == {'gui.screenshot': True}+ assert installed.has_capability(SERVER, 'gui.screenshot') is True++ fleet['connected'] = False+ assert installed.online() == []+ assert installed.is_online(SERVER) is False+++def test_sdk_is_reachable_from_the_package(app):+ from app import plugins_sdk++ assert plugins_sdk.agents.CommandError is AgentCommandError+ with pytest.raises(ValueError):+ plugins_sdk.agents.for_plugin('')