diff --git a/app_gateway/forms.py b/app_gateway/forms.py index 2a02258..7efde9a 100644 --- a/app_gateway/forms.py +++ b/app_gateway/forms.py @@ -41,6 +41,13 @@ class ApplicationForm(forms.ModelForm): if self.cluster_enabled: self.fields['workers'].queryset = Worker.objects.order_by('name') self.fields['workers'].help_text = _('Select specific workers, or leave empty when serving on all cluster workers.') + if not self.instance.pk: + self.initial.setdefault('all_workers', True) + if not ClusterSettings.primary_serves_clients(): + self.fields['serve_on_primary'].help_text = _( + 'WireGuard is disabled on the primary server in the cluster settings, so it does not publish ' + 'applications until it is enabled again.' + ) cluster_rows = [ HTML(f'
{_("Cluster")}

{_("Servers that publish this application.")}

'), Div( diff --git a/app_gateway/models.py b/app_gateway/models.py index 3eccde2..946b183 100644 --- a/app_gateway/models.py +++ b/app_gateway/models.py @@ -94,7 +94,8 @@ class Application(models.Model): if not ClusterSettings.cluster_enabled(): return worker is None if worker is None: - return self.serve_on_primary + # Only WireGuard WebAdmin is published while the primary server does not serve clients + return self.serve_on_primary and (self.name == RESERVED_APP_NAME or ClusterSettings.primary_serves_clients()) return self.all_workers or self.workers.filter(pk=worker.pk).exists() class Meta: diff --git a/cluster/forms.py b/cluster/forms.py index c45b5dd..a732991 100644 --- a/cluster/forms.py +++ b/cluster/forms.py @@ -130,6 +130,12 @@ class ClusterSettingsForm(forms.ModelForm): cleaned_data = super().clean() cluster_enabled = cleaned_data.get('enabled') + if not cleaned_data.get('primary_enable_wireguard') and cleaned_data.get('cluster_mode') in DISTRIBUTED_MODES: + self.add_error('primary_enable_wireguard', _( + 'The primary server can only be disabled in mirror mode. In distributed mode, move its instances ' + 'to workers instead.' + )) + if cluster_enabled and not settings.WIREGUARD_STATUS_CACHE_ENABLED: raise ValidationError(_("Cluster mode requires WireGuard status cache to be enabled.")) diff --git a/cluster/management/__init__.py b/cluster/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/cluster/management/commands/__init__.py b/cluster/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/cluster/management/commands/primary_wireguard_enabled.py b/cluster/management/commands/primary_wireguard_enabled.py new file mode 100644 index 0000000..bf93076 --- /dev/null +++ b/cluster/management/commands/primary_wireguard_enabled.py @@ -0,0 +1,11 @@ +from django.core.management.base import BaseCommand, CommandError + +from cluster.models import ClusterSettings + + +class Command(BaseCommand): + help = 'Exit with status 1 when WireGuard is disabled on the primary server in the cluster settings' + + def handle(self, *args, **options): + if not ClusterSettings.primary_serves_clients(): + raise CommandError('WireGuard is disabled on the primary server in the cluster settings', returncode=1) diff --git a/cluster/models.py b/cluster/models.py index ad6095b..11b4474 100644 --- a/cluster/models.py +++ b/cluster/models.py @@ -31,6 +31,16 @@ class ClusterSettings(models.Model): def cluster_enabled(cls): return cls.objects.filter(name='cluster_settings', enabled=True).exists() + @classmethod + def primary_serves_clients(cls): + """ + False when the primary server neither runs WireGuard nor publishes App Gateway applications, which is only + possible in mirror mode: the workers serve every client. + """ + return not cls.objects.filter( + name='cluster_settings', enabled=True, primary_enable_wireguard=False + ).exclude(cluster_mode__in=DISTRIBUTED_MODES).exists() + @classmethod def is_distributed(cls): """Each WireGuard instance runs on a single server. Only applies while the cluster is enabled.""" diff --git a/cluster/tests.py b/cluster/tests.py index f5ed782..3319c09 100644 --- a/cluster/tests.py +++ b/cluster/tests.py @@ -5,6 +5,8 @@ import tempfile from unittest.mock import patch from django.contrib.auth.models import User +from django.core.management import call_command +from django.core.management.base import CommandError from django.test import TestCase, override_settings from django.utils import timezone @@ -12,7 +14,8 @@ from api.models import WireguardStatusCache from api.views import func_concatenate_cluster_wireguard_status_cache from app_gateway import caddy_config_export from app_gateway.caddy_config_export import certificate_file_name, export_caddy_config -from app_gateway.models import Application, ApplicationHost, DnsChallengeCredential +from app_gateway.forms import ApplicationForm +from app_gateway.models import Application, ApplicationHost, DnsChallengeCredential, RESERVED_APP_NAME from cluster import sync from cluster.forms import ClusterSettingsForm from cluster.models import ClusterSettings, Worker, WorkerStatus @@ -663,3 +666,126 @@ class AgentServiceCheckTests(TestCase): self.assertTrue(self.cluster_worker.tcp_service_is_running(address)) listener.close() self.assertFalse(self.cluster_worker.tcp_service_is_running(address)) + + +class PrimaryDisabledTests(ClusterTestMixin, TestCase): + """In mirror mode the primary server can leave every client to the workers, except WireGuard WebAdmin.""" + + def setUp(self): + super().setUp() + credential = DnsChallengeCredential.objects.create( + display_name='Cloudflare', provider='cloudflare', credentials={'api_token': 'x' * 40} + ) + self.webadmin = Application.objects.get(name=RESERVED_APP_NAME) + self.primary_app = Application.objects.create(display_name='Primary App', upstream='http://10.0.0.10:8080') + ApplicationHost.objects.create(application=self.primary_app, hostname='primary-app.example.test') + self.shared_app = Application.objects.create( + display_name='Shared App', upstream='http://10.0.0.20:8080', all_workers=True + ) + ApplicationHost.objects.create( + application=self.shared_app, hostname='shared.example.test', certificate_type='dns_challenge', + dns_credential=credential, + ) + self.instance = create_instance(0) + + def set_primary(self, enabled, cluster_mode='mirror'): + ClusterSettings.objects.filter(name='cluster_settings').update( + primary_enable_wireguard=enabled, cluster_mode=cluster_mode + ) + + def login(self): + user = User.objects.create_user(username='cluster-admin', password='unused-test-password') + UserAcl.objects.create(user=user, user_level=50) + self.client.force_login(user) + + def test_primary_can_only_be_disabled_in_mirror_mode(self): + cluster_settings = ClusterSettings.objects.get(name='cluster_settings') + data = {'enabled': True, 'primary_enable_wireguard': False, 'worker_display': 'name'} + + form = ClusterSettingsForm(data=dict(data, cluster_mode='distributed'), instance=cluster_settings) + self.assertFalse(form.is_valid()) + self.assertIn('primary_enable_wireguard', form.errors) + + self.assertTrue(ClusterSettingsForm(data=dict(data, cluster_mode='mirror'), instance=cluster_settings).is_valid()) + + def test_primary_serves_clients_unless_disabled_in_an_enabled_mirror_cluster(self): + self.assertTrue(ClusterSettings.primary_serves_clients()) + self.set_primary(False) + self.assertFalse(ClusterSettings.primary_serves_clients()) + self.set_primary(False, cluster_mode='distributed') + self.assertTrue(ClusterSettings.primary_serves_clients()) + self.set_primary(False) + ClusterSettings.objects.filter(name='cluster_settings').update(enabled=False) + self.assertTrue(ClusterSettings.primary_serves_clients()) + + def test_disabled_primary_only_publishes_webadmin_and_keeps_worker_certificates(self): + self.set_primary(False) + self.assertTrue(self.webadmin.is_served_by(None)) + self.assertFalse(self.primary_app.is_served_by(None)) + self.assertTrue(self.shared_app.is_served_by(self.worker)) + + export_caddy_config(self.export_dir) + with open(os.path.join(self.export_dir, 'applications.json'), encoding='utf-8') as applications_file: + self.assertEqual(json.load(applications_file)['entries'], []) + with open(os.path.join(self.export_dir, 'tls.json'), encoding='utf-8') as tls_file: + primary_hosts = json.load(tls_file)['hosts'] + self.assertNotIn('primary-app.example.test', primary_hosts) + self.assertTrue(primary_hosts['shared.example.test']['certificate_only']) + self.assertTrue(primary_hosts['shared.example.test']['export_certificate']) + + worker_applications = json.loads(sync.build_section('gateway', self.worker).files['applications.json']) + self.assertEqual([entry['id'] for entry in worker_applications['entries']], ['shared-app']) + + self.set_primary(True) + self.assertTrue(self.primary_app.is_served_by(None)) + + def test_changing_the_primary_marks_instances_pending_and_exports_the_gateway(self): + self.login() + data = {'enabled': 'on', 'cluster_mode': 'mirror', 'worker_display': 'name'} + WireGuardInstance.objects.update(pending_changes=False) + with patch('cluster.views.auto_apply_caddy_config') as auto_apply: + self.client.post('/cluster/settings/', data) + self.instance.refresh_from_db() + self.assertTrue(self.instance.pending_changes) + self.assertEqual(auto_apply.call_count, 1) + + WireGuardInstance.objects.update(pending_changes=False) + self.client.post('/cluster/settings/', dict(data, worker_display='location')) + self.instance.refresh_from_db() + self.assertFalse(self.instance.pending_changes) + self.assertEqual(auto_apply.call_count, 1) + + def test_applying_the_configuration_stops_the_interfaces_of_a_disabled_primary(self): + self.set_primary(False) + self.login() + WireGuardInstance.objects.update(pending_changes=True) + commands = [] + + def run(command, **kwargs): + commands.append(command) + return type('Result', (), {'returncode': 0, 'stdout': 'wg0 wg1\n', 'stderr': ''})() + + with patch('wireguard_tools.views.subprocess.run', run), \ + patch('wireguard_tools.views.os.path.isfile', lambda path: path.endswith('/wg0.conf')): + self.client.get('/tools/restart_wireguard/?action=dismiss_warning') + + self.assertIn(['wg-quick', 'down', 'wg0'], commands) + self.assertIn(['ip', 'link', 'delete', 'wg1'], commands) + self.assertFalse([command for command in commands if 'up' in command]) + self.assertFalse(WireGuardInstance.objects.filter(pending_changes=True).exists()) + + def test_startup_command_reports_a_disabled_primary(self): + call_command('primary_wireguard_enabled') + self.set_primary(False) + with self.assertRaises(CommandError): + call_command('primary_wireguard_enabled') + + def test_new_applications_are_served_everywhere_by_default(self): + form = ApplicationForm() + self.assertTrue(form['serve_on_primary'].value()) + self.assertTrue(form['all_workers'].value()) + self.assertFalse(ApplicationForm(instance=self.primary_app)['all_workers'].value()) + self.assertEqual(form.fields['serve_on_primary'].help_text, '') + + self.set_primary(False) + self.assertNotEqual(ApplicationForm().fields['serve_on_primary'].help_text, '') diff --git a/cluster/views.py b/cluster/views.py index 6fb0890..f99d5c3 100644 --- a/cluster/views.py +++ b/cluster/views.py @@ -8,6 +8,7 @@ from django.utils.dateparse import parse_datetime from django.utils.translation import gettext_lazy as _ from api.models import WireguardStatusCache +from app_gateway.caddy_config_export import auto_apply_caddy_config from app_gateway.setup_defaults import get_webadmin_hostnames from user_manager.models import UserAcl from wireguard.models import WireGuardInstance @@ -216,10 +217,15 @@ def cluster_settings(request): cluster_settings, cluster_settings_created = ClusterSettings.objects.get_or_create(name='cluster_settings') was_distributed = ClusterSettings.is_distributed() + primary_served_clients = ClusterSettings.primary_serves_clients() form = ClusterSettingsForm(request.POST or None, instance=cluster_settings) if form.is_valid(): cluster_settings = form.save() messages.success(request, _('Cluster settings updated successfully.')) + if ClusterSettings.primary_serves_clients() != primary_served_clients: + # The primary server starts or stops its interfaces when the configuration is applied + WireGuardInstance.objects.update(pending_changes=True) + auto_apply_caddy_config(request) if ClusterSettings.is_distributed() != was_distributed: # Where each instance runs may have changed: workers synchronize the new files right away and the # primary server moves its interfaces when the configuration is applied @@ -235,7 +241,7 @@ def cluster_settings(request):

When disabled, workers are refused and shut down their WireGuard interfaces, and App Gateway applications are only published by this primary server. Requires the WireGuard status cache.

Primary Enable WireGuard
-

Lists this primary server as an option when downloading peer configurations and VPN invites.

+

Mirror mode only. When disabled, this primary server stops its WireGuard interfaces once the configuration is applied, is no longer offered when downloading peer configurations and VPN invites, and only publishes WireGuard WebAdmin in the App Gateway. Workers keep receiving the configuration, and the primary server keeps managing the certificates used by them. Make sure you can reach WireGuard WebAdmin without the VPN of this server before disabling it.

Cluster Mode

Mirror: every worker receives the same WireGuard instances, peers, firewall and DNS configuration. Peers can connect to any server.

diff --git a/init.sh b/init.sh index 7faa9e6..5bcadad 100644 --- a/init.sh +++ b/init.sh @@ -16,13 +16,18 @@ python manage.py collectstatic --noinput # Export WireGuard, firewall and Caddy configs before bringing up interfaces python manage.py export_configs -# Starts each WireGuard configuration file found in /etc/wireguard +# Starts each WireGuard configuration file found in /etc/wireguard, unless the cluster settings disable WireGuard +# on the primary server shopt -s nullglob config_files=(/etc/wireguard/*.conf) if [ ${#config_files[@]} -gt 0 ]; then - for f in "${config_files[@]}"; do - wg-quick up "$(basename "${f}" .conf)" - done + if python manage.py primary_wireguard_enabled; then + for f in "${config_files[@]}"; do + wg-quick up "$(basename "${f}" .conf)" + done + else + echo "WireGuard is disabled on the primary server, interfaces not started." + fi fi if [[ "${DEV_MODE,,}" == "true" ]]; then echo "" diff --git a/wireguard_tools/views.py b/wireguard_tools/views.py index 062651a..cefa0f2 100644 --- a/wireguard_tools/views.py +++ b/wireguard_tools/views.py @@ -337,6 +337,23 @@ def restart_wireguard_interfaces(request): else: interface_count += 1 + if not ClusterSettings.primary_serves_clients(): + if not (user_acl.enable_reload if mode == 'reload' else user_acl.enable_restart): + return render(request, 'access_denied.html', {'page_title': 'Access Denied'}) + # WireGuard is disabled on the primary server in mirror mode: only the cluster workers run the instances + for interface_name in running_interfaces: + if re.fullmatch(r'wg[0-9]+', interface_name) and os.path.isfile(os.path.join(config_dir, f'{interface_name}.conf')): + stop_result = subprocess.run(['wg-quick', 'down', interface_name], capture_output=True, text=True) + if stop_result.returncode != 0: + messages.warning(request, _("Error stopping") + f" {interface_name}|{stop_result.stderr}") + messages.info(request, _( + "WireGuard disabled on the primary server|The interfaces of this server are stopped. Cluster workers " + "keep serving the peers." + )) + if request.GET.get('action') == 'dismiss_warning': + WireGuardInstance.objects.filter(pending_changes=True).update(pending_changes=False) + return redirect("/status/") + for filename in os.listdir(config_dir): if filename.endswith(".conf"): interface_name = filename[:-5]