From 1c3e162b5c800bb9fcee7599675389e606109833 Mon Sep 17 00:00:00 2001
From: Eduardo Silva
Date: Mon, 23 Nov 2026 13:15:16 -0300
Subject: [PATCH] Add tests for cluster agent responses and gateway shutdown
---
cluster/tests.py | 138 ++++++++++++++++++++++
containers/cluster_node/cluster_worker.py | 41 +++++--
templates/cluster/worker_details.html | 4 +-
wireguard_webadmin/settings.py | 2 +-
4 files changed, 171 insertions(+), 14 deletions(-)
diff --git a/cluster/tests.py b/cluster/tests.py
index 6726174..f5ed782 100644
--- a/cluster/tests.py
+++ b/cluster/tests.py
@@ -1,5 +1,6 @@
import json
import os
+import socket
import tempfile
from unittest.mock import patch
@@ -525,3 +526,140 @@ class AgentGatewaySessionsTests(TestCase):
self.agent.apply_gateway({'files': dict(files, **{'revoked_sessions.json': '{"sessions": []}'})})
with open(os.path.join(self.gateway_dir, 'revoked_sessions.json'), encoding='utf-8') as revoked_file:
self.assertEqual(revoked_file.read(), '{"sessions": []}')
+
+
+class FakeResponse:
+ def __init__(self, status_code, data=None, text='', redirected=False):
+ self.status_code = status_code
+ self.data = data
+ self.text = text
+ self.headers = {'Content-Type': 'application/json' if data is not None else 'text/html'}
+ self.history = ['redirect'] if redirected else []
+ self.url = 'https://primary.example.com/auth-gateway/login'
+
+ def json(self):
+ if self.data is None:
+ raise ValueError('not JSON')
+ return self.data
+
+
+class AgentPrimaryResponsesTests(TestCase):
+ """The agent follows the answers of the cluster API and ignores anything else, e.g. a login page."""
+
+ GATEWAY_FILES = {
+ 'applications.json': json.dumps({'entries': [{'id': 'app', 'hosts': ['app.example.com']}]}),
+ 'auth_policies.json': '{}',
+ 'routes.json': json.dumps({'entries': {'app': {'routes': []}}}),
+ 'tls.json': '{}',
+ }
+
+ @classmethod
+ def setUpClass(cls):
+ super().setUpClass()
+ cls.cluster_worker = load_cluster_worker()
+
+ def setUp(self):
+ temp_dir = tempfile.TemporaryDirectory()
+ self.addCleanup(temp_dir.cleanup)
+ self.gateway_dir = temp_dir.name
+ for name, value in (('GATEWAY_DIR', self.gateway_dir), ('gateway_enabled', lambda: True)):
+ patcher = patch.object(self.cluster_worker, name, value)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.manifest_response = FakeResponse(200, {'sections': {'gateway': 'hash-1'}})
+ self.agent = self.new_agent()
+
+ def new_agent(self):
+ agent = self.cluster_worker.ClusterNodeAgent()
+ agent.request = self.answer
+ agent.wireguard_shutdowns = 0
+
+ def shutdown_wireguard():
+ agent.wireguard_shutdowns += 1
+
+ agent.shutdown_wireguard = shutdown_wireguard
+ return agent
+
+ def answer(self, method, path, **kwargs):
+ if path == 'manifest/':
+ return self.manifest_response
+ if path == 'section/gateway/':
+ return FakeResponse(200, {'hash': 'hash-1', 'files': self.GATEWAY_FILES})
+ return FakeResponse(200, {'status': 'success'})
+
+ def refuse(self):
+ self.manifest_response = FakeResponse(400, {'status': 'error', 'message': 'worker_disabled'})
+
+ def accept(self):
+ self.manifest_response = FakeResponse(200, {'sections': {'gateway': 'hash-1'}})
+
+ def published_applications(self):
+ with open(os.path.join(self.gateway_dir, 'applications.json'), encoding='utf-8') as applications_file:
+ return [application['id'] for application in json.load(applications_file)['entries']]
+
+ def test_refused_worker_stops_serving_applications_until_accepted_again(self):
+ self.assertTrue(self.agent.sync_configuration())
+ self.assertEqual(self.published_applications(), ['app'])
+
+ self.refuse()
+ self.assertTrue(self.agent.sync_configuration())
+ self.assertEqual(self.published_applications(), [])
+ with open(os.path.join(self.gateway_dir, 'routes.json'), encoding='utf-8') as routes_file:
+ self.assertEqual(json.load(routes_file), {'entries': {}})
+ self.assertEqual(self.agent.wireguard_shutdowns, 1)
+
+ # The same section hash is applied again once the worker is accepted
+ self.accept()
+ self.assertTrue(self.agent.sync_configuration())
+ self.assertEqual(self.published_applications(), ['app'])
+
+ def test_applications_are_removed_only_once_while_refused(self):
+ self.agent.sync_configuration()
+ self.refuse()
+ self.agent.sync_configuration()
+ with patch.object(self.cluster_worker, 'write_file') as write_file:
+ self.agent.sync_configuration()
+ write_file.assert_not_called()
+
+ def test_refusal_after_a_restart_removes_applications_of_the_previous_run(self):
+ self.agent.sync_configuration()
+ restarted_agent = self.new_agent()
+ self.refuse()
+ restarted_agent.sync_configuration()
+ self.assertEqual(self.published_applications(), [])
+
+ def test_answers_that_are_not_json_keep_the_worker_running(self):
+ self.agent.sync_configuration()
+ for response in (
+ FakeResponse(200, text='login', redirected=True),
+ FakeResponse(403, text='Forbidden'),
+ FakeResponse(400, text='Bad Request'),
+ ):
+ self.manifest_response = response
+ with self.assertLogs(level='ERROR'):
+ self.assertTrue(self.agent.sync_configuration())
+ self.assertEqual(self.agent.wireguard_shutdowns, 0)
+ self.assertEqual(self.published_applications(), ['app'])
+
+ def test_token_rejected_by_the_cluster_api_stops_the_worker(self):
+ self.agent.sync_configuration()
+ self.manifest_response = FakeResponse(403, {'status': 'error', 'message': 'Worker not found'})
+ self.assertFalse(self.agent.sync_configuration())
+ self.assertEqual(self.agent.wireguard_shutdowns, 1)
+ self.assertEqual(self.published_applications(), [])
+
+
+class AgentServiceCheckTests(TestCase):
+ @classmethod
+ def setUpClass(cls):
+ super().setUpClass()
+ cls.cluster_worker = load_cluster_worker()
+
+ def test_service_is_running_while_its_port_accepts_connections(self):
+ listener = socket.socket()
+ listener.bind(('127.0.0.1', 0))
+ listener.listen()
+ address = listener.getsockname()
+ self.assertTrue(self.cluster_worker.tcp_service_is_running(address))
+ listener.close()
+ self.assertFalse(self.cluster_worker.tcp_service_is_running(address))
diff --git a/containers/cluster_node/cluster_worker.py b/containers/cluster_node/cluster_worker.py
index db4103d..8756ad0 100644
--- a/containers/cluster_node/cluster_worker.py
+++ b/containers/cluster_node/cluster_worker.py
@@ -19,7 +19,7 @@ logger = logging.getLogger(__name__)
MASTER_SERVER_ADDRESS = os.environ.get('MASTER_SERVER_ADDRESS', '')
TOKEN = os.environ.get('TOKEN', '')
-WORKER_VERSION = 14
+WORKER_VERSION = 15
REQUEST_TIMEOUT = 30
MANIFEST_INTERVAL = 60
DEFAULT_STATS_INTERVAL = 60
@@ -37,8 +37,9 @@ GATEWAY_OPTIONAL_FILES = ('revoked_sessions.json',)
# Active sessions published by the auth-gateway
GATEWAY_SESSIONS_FILE = os.path.join(GATEWAY_DIR, 'state', 'sessions.json')
CERTIFICATE_FILE_PATTERN = re.compile(r'^[a-f0-9]{64}\.(crt|key)$')
-CADDY_ADMIN_URL = 'http://127.0.0.1:2019/config/'
-AUTH_GATEWAY_URL = 'http://cluster-node-auth-gateway:9091/'
+# Services are checked by opening a TCP connection, which leaves no entry in their access logs
+CADDY_ADMIN_ADDRESS = ('127.0.0.1', 2019)
+AUTH_GATEWAY_ADDRESS = ('cluster-node-auth-gateway', 9091)
INTERNAL_CA_NAME = 'Caddy Local Authority'
FIREWALL_CHAINS = (
('nat', 'WGWADM_POSTROUTING'),
@@ -156,11 +157,11 @@ def gateway_enabled():
return os.path.isdir(GATEWAY_DIR) and os.path.isdir(CERTIFICATES_DIR)
-def http_service_is_running(url):
+def tcp_service_is_running(address):
try:
- requests.get(url, timeout=3)
- return True
- except requests.RequestException:
+ with socket.create_connection(address, timeout=3):
+ return True
+ except OSError:
return False
@@ -243,6 +244,8 @@ class ClusterNodeAgent:
self.applied_hashes = {}
self.stats_interval = DEFAULT_STATS_INTERVAL
self.wireguard_active = False
+ # Applications left in the gateway directory by an earlier run are only removed when the worker is refused
+ self.gateway_active = True
# Hash of the last gateway sessions accepted by the primary server: they are only sent when they change
self.sent_sessions_hash = None
@@ -381,6 +384,7 @@ class ClusterNodeAgent:
for filename in GATEWAY_FILES + GATEWAY_OPTIONAL_FILES:
if filename in section['files']:
write_file(os.path.join(GATEWAY_DIR, filename), section['files'][filename], mode=0o644)
+ self.gateway_active = True
SECTION_HANDLERS = {
'firewall': apply_firewall,
@@ -405,6 +409,21 @@ class ClusterNodeAgent:
self.applied_hashes.pop('firewall', None)
self.wireguard_active = False
+ def shutdown_gateway(self):
+ """Stop publishing applications, so a refused worker does not keep serving a configuration it no longer
+ receives. The next gateway section restores them."""
+ if not self.gateway_active or not gateway_enabled():
+ return
+ logger.warning('Removing App Gateway applications')
+ write_file(os.path.join(GATEWAY_DIR, 'applications.json'), json.dumps({'entries': []}), mode=0o644)
+ write_file(os.path.join(GATEWAY_DIR, 'routes.json'), json.dumps({'entries': {}}), mode=0o644)
+ self.applied_hashes.pop('gateway', None)
+ self.gateway_active = False
+
+ def shutdown_services(self):
+ self.shutdown_wireguard()
+ self.shutdown_gateway()
+
def sync_configuration(self):
response = self.request('GET', 'manifest/')
if response is None:
@@ -418,11 +437,11 @@ class ClusterNodeAgent:
return True
if response.status_code == 403:
logger.error('Token rejected by the primary server. Stopping.')
- self.shutdown_wireguard()
+ self.shutdown_services()
return False
if response.status_code == 400:
logger.warning('Primary server refused this worker: %s', data.get('message', ''))
- self.shutdown_wireguard()
+ self.shutdown_services()
return True
manifest = data.get('sections', {})
@@ -457,8 +476,8 @@ class ClusterNodeAgent:
def services_status():
services = {'dnsmasq': 'running' if dns_is_running() else 'stopped'}
if gateway_enabled():
- services['caddy'] = 'running' if http_service_is_running(CADDY_ADMIN_URL) else 'stopped'
- services['auth_gateway'] = 'running' if http_service_is_running(AUTH_GATEWAY_URL) else 'stopped'
+ services['caddy'] = 'running' if tcp_service_is_running(CADDY_ADMIN_ADDRESS) else 'stopped'
+ services['auth_gateway'] = 'running' if tcp_service_is_running(AUTH_GATEWAY_ADDRESS) else 'stopped'
return services
@staticmethod
diff --git a/templates/cluster/worker_details.html b/templates/cluster/worker_details.html
index 9d0c326..3eb50aa 100644
--- a/templates/cluster/worker_details.html
+++ b/templates/cluster/worker_details.html
@@ -142,7 +142,7 @@
{% endblocktrans %}
-
wget -O cluster_node.yml https://raw.githubusercontent.com/eduardogsilva/wireguard_webadmin/main/cluster_node.yml
+
wget -O docker-compose.yml https://raw.githubusercontent.com/eduardogsilva/wireguard_webadmin/main/cluster_node.yml
2. {% blocktrans trimmed %}
@@ -158,7 +158,7 @@ TIMEZONE={{ time_zone }}
3. {% trans 'Start the worker:' %}
-
docker compose -f cluster_node.yml up -d
+
docker compose up -d
diff --git a/wireguard_webadmin/settings.py b/wireguard_webadmin/settings.py
index 9df2151..de53a03 100644
--- a/wireguard_webadmin/settings.py
+++ b/wireguard_webadmin/settings.py
@@ -176,7 +176,7 @@ DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
WIREGUARD_WEBADMIN_VERSION = 9982
-CLUSTER_WORKER_CURRENT_VERSION = 14
+CLUSTER_WORKER_CURRENT_VERSION = 15
CLUSTER_WORKER_MINIMUM_VERSION = 12
CADDY_ENABLED = os.getenv("CADDY_ENABLED", "false").lower() == "true"