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.

feat(connect): tell Cloud every id we hold for each agent

Juan Deniseeeba465badd
diff --git a/backend/app/services/connect_client.py b/backend/app/services/connect_client.py
index 1a507be4..412e3043 100644
--- a/backend/app/services/connect_client.py
+++ b/backend/app/services/connect_client.py
@@ -137,31 +137,51 @@ def _panel_machine_id(fallback: str) -> str:
def _gather_hosts() -> list:
"""One host entry (kind 'agent') per agent-backed Server this panel manages.
- Server rows carry no machine_id/fingerprint for their agents, so only
- agent_id and hostname are reported. Without a Flask app context (or with
- the DB down) the honest answer is an empty list.
+ Each entry carries every identifier we hold for that host: the agent's own
+ id, and — from the pairing record the agent enrolled with — its machine id
+ and key fingerprint. Cloud counts a host once per organisation however many
+ panels report it, and it can only do that if it can recognise the same
+ machine twice. Reporting agent_id alone is what let one agent under two
+ panels take two slots.
+
+ Without a Flask app context (or with the DB down) the honest answer is an
+ empty list.
"""
try:
from flask import has_app_context
if not has_app_context():
return []
+ from app.models.pending_agent import PendingAgent
from app.models.server import Server
servers = (
Server.query
.filter(Server.agent_id.isnot(None))
- .with_entities(Server.agent_id, Server.hostname, Server.name)
+ .with_entities(Server.id, Server.agent_id, Server.hostname, Server.name)
.all()
)
- return [
- {
+ if not servers:
+ return []
+ # The enrolment row is where the agent's own machine id and key
+ # fingerprint live; it is keyed by the server it was claimed onto.
+ identities = {}
+ for row in (PendingAgent.query
+ .filter(PendingAgent.claimed_server_id.in_([s.id for s in servers]))
+ .with_entities(PendingAgent.claimed_server_id,
+ PendingAgent.machine_id,
+ PendingAgent.pubkey_fpr)
+ .all()):
+ identities[row.claimed_server_id] = (row.machine_id, row.pubkey_fpr)
+ out = []
+ for s in servers:
+ machine_id, fingerprint = identities.get(s.id, (None, None))
+ out.append({
'agent_id': s.agent_id,
- 'machine_id': None,
- 'fingerprint': None,
+ 'machine_id': machine_id,
+ 'fingerprint': (fingerprint or '').lower() or None,
'hostname': s.hostname or s.name,
'kind': 'agent',
- }
- for s in servers
- ]
+ })
+ return out
except Exception as exc: # never block pairing on host enumeration
logger.warning('Could not enumerate managed agents: %s', exc)
return []
diff --git a/backend/tests/test_connect_hosts.py b/backend/tests/test_connect_hosts.py
new file mode 100644
index 00000000..1c236e1f
--- /dev/null
+++ b/backend/tests/test_connect_hosts.py
@@ -0,0 +1,64 @@
+"""What this panel tells ServerKit Cloud it manages.
+
+Cloud counts a host once per organisation however many panels report it, and
+it can only do that if it can recognise the same machine twice. Reporting an
+agent's own id and nothing else is what let one agent under two panels take
+two server slots, so every identifier this panel holds goes in the report.
+"""
+from datetime import datetime, timedelta
+
+from app import db
+from app.models.pending_agent import PendingAgent
+from app.models.server import Server
+from app.services import connect_client
+
+
+def _enrolment(server_id, *, machine_id, pubkey='ab' * 32):
+ """A claimed enrolment, the row an agent's identity actually lives in."""
+ now = datetime.utcnow()
+ return PendingAgent(
+ enrollment_id=f'enr-{server_id}',
+ enrollment_secret_hash=PendingAgent.hash_enrollment_secret('s3cret'),
+ pubkey=pubkey,
+ pubkey_fpr=PendingAgent.fingerprint(pubkey),
+ pair_code='ABCD-2345',
+ pair_code_expires_at=now + timedelta(minutes=10),
+ passphrase_hash=PendingAgent.hash_passphrase('hunter2'),
+ machine_id=machine_id,
+ expires_at=now + timedelta(hours=1),
+ claimed_at=now,
+ claimed_server_id=server_id,
+ )
+
+
+def test_a_reported_agent_carries_every_id_this_panel_holds(app):
+ with app.app_context():
+ server = Server(name='worker-1', hostname='worker-1.example.com',
+ agent_id='agent-hosts-1')
+ db.session.add(server)
+ db.session.commit()
+ db.session.add(_enrolment(server.id, machine_id='mach-worker-1'))
+ db.session.commit()
+
+ entry = next(h for h in connect_client._gather_hosts()
+ if h['agent_id'] == 'agent-hosts-1')
+ assert entry['machine_id'] == 'mach-worker-1'
+ assert entry['fingerprint'] == PendingAgent.fingerprint('ab' * 32).lower()
+ assert entry['hostname'] == 'worker-1.example.com'
+ assert entry['kind'] == 'agent'
+
+
+def test_an_agent_with_no_enrolment_row_is_still_reported(app):
+ """Honest about what we do not know: the entry goes out with the ids we
+ have, rather than being dropped. A missing host is a server Cloud cannot
+ show at all."""
+ with app.app_context():
+ server = Server(name='worker-2', agent_id='agent-hosts-2')
+ db.session.add(server)
+ db.session.commit()
+
+ entry = next(h for h in connect_client._gather_hosts()
+ if h['agent_id'] == 'agent-hosts-2')
+ assert entry['machine_id'] is None
+ assert entry['fingerprint'] is None
+ assert entry['hostname'] == 'worker-2'