mirror of
https://github.com/eduardogsilva/wireguard_webadmin.git
synced 2026-11-27 07:06:03 +01:00
Add tests for cluster agent responses and gateway shutdown
This commit is contained in:
@@ -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='<html>login</html>', 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))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -142,7 +142,7 @@
|
||||
{% endblocktrans %}</p>
|
||||
<div class="position-relative">
|
||||
<button type="button" class="btn btn-xs btn-outline-secondary position-absolute copy-button" style="top: 6px; right: 6px;" data-target="#worker-download" title="{% trans 'Copy' %}"><i class="far fa-copy"></i></button>
|
||||
<pre id="worker-download" class="p-2 pr-5" style="white-space: pre-wrap;">wget -O <span class="worker-compose-file">cluster_node.yml</span> https://raw.githubusercontent.com/eduardogsilva/wireguard_webadmin/main/<span class="worker-compose-file">cluster_node.yml</span></pre>
|
||||
<pre id="worker-download" class="p-2 pr-5" style="white-space: pre-wrap;">wget -O docker-compose.yml https://raw.githubusercontent.com/eduardogsilva/wireguard_webadmin/main/<span class="worker-compose-file">cluster_node.yml</span></pre>
|
||||
</div>
|
||||
|
||||
<p class="mb-1"><strong>2.</strong> {% blocktrans trimmed %}
|
||||
@@ -158,7 +158,7 @@ TIMEZONE={{ time_zone }}</pre>
|
||||
<p class="mb-1"><strong>3.</strong> {% trans 'Start the worker:' %}</p>
|
||||
<div class="position-relative">
|
||||
<button type="button" class="btn btn-xs btn-outline-secondary position-absolute copy-button" style="top: 6px; right: 6px;" data-target="#worker-up" title="{% trans 'Copy' %}"><i class="far fa-copy"></i></button>
|
||||
<pre id="worker-up" class="p-2 pr-5">docker compose -f <span class="worker-compose-file">cluster_node.yml</span> up -d</pre>
|
||||
<pre id="worker-up" class="p-2 pr-5">docker compose up -d</pre>
|
||||
</div>
|
||||
|
||||
<ul class="text-muted mb-0">
|
||||
|
||||
@@ -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"
|
||||
|
||||
Reference in New Issue
Block a user