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
fix(agent): fail-closed agent registration + surface stuck-command errors
Juan Denisa01ccc4aee90
diff --git a/backend/app/agent_gateway.py b/backend/app/agent_gateway.pyindex 145a2668..00027dba 100644--- a/backend/app/agent_gateway.py+++ b/backend/app/agent_gateway.py@@ -158,6 +158,16 @@ class AgentNamespace(Namespace):agent_version=agent_version)+ # register_agent returns None when the DB write failed and it rolled+ # back the in-memory state — don't tell the agent it's authenticated.+ if not session_token:+ emit('auth_fail', {+ 'type': 'auth_fail',+ 'error': 'Registration failed'+ })+ disconnect()+ return+# Calculate token expiry (1 hour)expires = int((time.time() + 3600) * 1000)diff --git a/backend/app/api/agent_poll.py b/backend/app/api/agent_poll.pyindex bd3a687b..0919c6f2 100644--- a/backend/app/api/agent_poll.py+++ b/backend/app/api/agent_poll.py@@ -90,6 +90,11 @@ def connect():transport='poll',)+ # None means the DB write failed and register_agent rolled back the+ # in-memory state — surface a 5xx rather than a session the panel can't back.+ if not session_token:+ return jsonify({'success': False, 'error': 'Registration failed'}), 500+return jsonify({'success': True,'session_token': session_token,diff --git a/backend/app/services/agent_registry.py b/backend/app/services/agent_registry.pyindex dd32c296..a074848f 100644--- a/backend/app/services/agent_registry.py+++ b/backend/app/services/agent_registry.py@@ -255,7 +255,7 @@ class AgentRegistry:ip_address: str,agent_version: str = None,transport: str = 'ws'- ) -> str:+ ) -> Optional[str]:"""Register a newly connected agent.@@ -264,7 +264,9 @@ class AgentRegistry:ngrok, cf quick tunnels) corrupt frames. The two share storageand the command-routing path differs only in send_command.- Returns: session_token+ Returns: session_token on success, or None if the DB write failed+ (in which case the in-memory registration is rolled back and the+ caller must NOT treat the agent as connected)."""session_token = secrets.token_urlsafe(32)@@ -361,9 +363,22 @@ class AgentRegistry:except Exception as e:logger.error("Error delivering queued commands: %s", e)- except Exception as e:+ except Exception:logger.exception("Error registering agent")db.session.rollback()+ # The DB row/session didn't persist, so don't leave this agent in+ # the in-memory registry advertising itself as connected. That+ # desync would make the gateway emit auth_ok and have command+ # routing target an agent with no backing session row. Remove our+ # entry (guarded on identity, in case a concurrent reconnect has+ # already replaced it) and signal failure so the caller emits+ # auth_fail instead of auth_ok. A stale 'online' server row with no+ # in-memory agent is self-corrected by the heartbeat reaper.+ with self._lock:+ if self._agents.get(server_id) is agent:+ self._agents.pop(server_id, None)+ self._socket_to_server.pop(socket_id, None)+ return Nonereturn session_token@@ -612,8 +627,14 @@ class AgentRegistry:command_record.result = result.get('data')command_record.error = result.get('error')db.session.commit()- except Exception as e:+ except Exception:db.session.rollback()+ # Don't swallow silently: if this final write fails the command+ # row is left stuck in 'running', which is invisible without a log.+ logger.exception(+ "Failed to finalize command record %s (left in 'running')",+ command_id,+ )return resultdiff --git a/backend/tests/test_agent_registry_security.py b/backend/tests/test_agent_registry_security.pyindex d24cd1f7..5e91859e 100644--- a/backend/tests/test_agent_registry_security.py+++ b/backend/tests/test_agent_registry_security.py@@ -287,3 +287,32 @@ def test_failed_signature_does_not_consume_nonce(app, monkeypatch):)assert ok is not Noneassert consumed == [(s.id, nonce)], "valid request should consume the nonce exactly once"+++# --------------------------------------------------------------------------+# register_agent must fail closed on a DB error: return None and roll back the+# in-memory registration so the gateway can't report a connected agent with no+# backing session row.+# --------------------------------------------------------------------------++def test_register_agent_returns_none_and_rolls_back_on_db_failure(app, clean_registry, monkeypatch):+ import app.services.agent_registry as reg++ s = Server(name="t", agent_id="agent-dbfail")+ _db.session.add(s)+ _db.session.commit()+ sid = s.id++ # Blow up AgentSession construction to simulate a DB-layer failure that+ # happens AFTER the in-memory registration has been installed.+ class _Boom:+ def __init__(self, *a, **k):+ raise RuntimeError("simulated db failure")++ monkeypatch.setattr(reg, "AgentSession", _Boom)++ token = agent_registry.register_agent(sid, "socket-dbfail", "1.2.3.4", "1.0.0")++ assert token is None+ assert agent_registry.is_agent_connected(sid) is False+ assert agent_registry.get_agent(sid) is None