Merge main into feat-add-invite-api and adapt the invite API

Resolve the conflicts with the cluster and endpoint changes and align the
new peer_invite route with the other API v2 routes: instance access through
validate_api_key, peer selection by uuid or public key, endpoint peers
refused, email invites only when enabled, existing invites renewed and the
send_email mock pointing to the view module.
This commit is contained in:
Eduardo Silva
2026-11-24 11:23:47 -03:00
261 changed files with 34572 additions and 9800 deletions
+10 -3
View File
@@ -27,9 +27,8 @@ local_settings.py
*.log
media/
*.pot
*.pyc
*__pycache__/
__pycache__/
**/*.pyc
**/__pycache__/
*.pyd
*.pyo
.venv
@@ -42,3 +41,11 @@ venv.bak/
wireguard_webadmin/production_settings.py
containers/caddy/config_files/
CLAUDE.md
.claude/
**/.DS_Store
# Not needed inside the main image
.git
containers
docs
screenshots
+4 -3
View File
@@ -27,9 +27,8 @@ local_settings.py
*.log
media/
*.pot
*.pyc
*__pycache__/
__pycache__/
**/*.pyc
**/__pycache__/
*.pyd
*.pyo
.venv
@@ -42,3 +41,5 @@ venv.bak/
wireguard_webadmin/production_settings.py
containers/caddy/config_files/
CLAUDE.md
.claude/
**/.DS_Store
+3 -10
View File
@@ -1,25 +1,18 @@
# Build stage: install build dependencies and Python packages
FROM python:3.12-bookworm AS builder
FROM python:3.14-slim AS builder
WORKDIR /app
# Install build dependencies required for compiling C extensions
RUN apt-get update && apt-get install -y --no-install-recommends \
gcc \
build-essential \
librrd-dev \
&& rm -rf /var/lib/apt/lists/*
# Copy requirements and install Python packages to a separate directory
COPY requirements.txt /app/
RUN pip install --prefix=/install --no-cache-dir -r requirements.txt
# Final stage: runtime image
FROM python:3.12-slim
FROM python:3.14-slim
WORKDIR /app
# Install necessary runtime packages
RUN apt-get update && apt-get install -y --no-install-recommends \
wireguard \
wireguard-tools \
iptables \
iproute2 \
net-tools \
+4 -4
View File
@@ -1,12 +1,12 @@
from django.shortcuts import render, Http404, redirect
from django.contrib.auth.models import User
from django.contrib import auth
from django.contrib import messages
from django.contrib.auth.models import User
from django.http import Http404
from django.shortcuts import render, redirect
from api.views import get_api_key
from .forms import CreateUserForm, LoginForm
from django.http import HttpResponse
from user_manager.models import UserAcl
from .forms import CreateUserForm, LoginForm
def view_create_first_user(request):
+15 -1
View File
@@ -141,6 +141,7 @@ def peer_info(request):
'public_key': str(peer.public_key),
'uuid': str(peer.uuid),
'private_key_exists': bool(peer.private_key),
'endpoint': peer.endpoint,
'is_route_policy_restricted': peer.is_route_policy_restricted,
}
return JsonResponse(data)
@@ -358,7 +359,7 @@ def func_concatenate_cluster_wireguard_status_cache() -> None:
.first()
)
if master_cache and isinstance(master_cache.data, dict):
cache_entries.append({"source_name": "master", "source_uuid": "", "data": master_cache.data,})
cache_entries.append({"source_name": "master", "source_label": "", "source_uuid": "", "data": master_cache.data,})
worker_statuses = (WorkerStatus.objects.filter(
worker__enabled=True, wireguard_status_updated__gt=timezone.now() - timedelta(minutes=10)
@@ -368,6 +369,7 @@ def func_concatenate_cluster_wireguard_status_cache() -> None:
cache_entries.append(
{
"source_name": f"worker_{ws.worker.name}",
"source_label": ws.worker.name,
"source_uuid": str(ws.worker.uuid),
"data": ws.wireguard_status or {},
}
@@ -375,6 +377,7 @@ def func_concatenate_cluster_wireguard_status_cache() -> None:
for entry in cache_entries:
source_name = entry["source_name"]
source_label = entry["source_label"]
source_uuid = entry["source_uuid"]
data = entry.get("data") or {}
@@ -393,6 +396,7 @@ def func_concatenate_cluster_wireguard_status_cache() -> None:
peer_info_copy = dict(peer_info)
peer_info_copy["source_name"] = source_name
peer_info_copy["source_label"] = source_label
peer_info_copy["source_uuid"] = source_uuid
if peer_key not in combined_data[interface]:
@@ -401,11 +405,21 @@ def func_concatenate_cluster_wireguard_status_cache() -> None:
existing_peer = combined_data[interface][peer_key]
# Each server keeps its own counters, so the peer traffic is the sum of all sources
existing_transfer = existing_peer.get("transfer") or {}
new_transfer = peer_info_copy.get("transfer") or {}
combined_transfer = {
"tx": int(existing_transfer.get("tx", 0) or 0) + int(new_transfer.get("tx", 0) or 0),
"rx": int(existing_transfer.get("rx", 0) or 0) + int(new_transfer.get("rx", 0) or 0),
}
new_hs = _latest_handshake_as_int(peer_info_copy)
old_hs = _latest_handshake_as_int(existing_peer)
# Handshake, endpoint and source come from the server where the peer connected last
if new_hs > old_hs:
combined_data[interface][peer_key] = peer_info_copy
combined_data[interface][peer_key]["transfer"] = combined_transfer
processing_time_ms = int((time.monotonic() - start_time) * 1000)
WireguardStatusCache.objects.create(data=combined_data, processing_time_ms=processing_time_ms, cache_type="cluster")
+5
View File
@@ -13,6 +13,7 @@ class ApiKeyForm(forms.ModelForm):
fields = [
'name',
'allowed_instances',
'manage_cluster',
#'allow_restart',
#'allow_reload',
#'allow_export',
@@ -54,6 +55,10 @@ class ApiKeyForm(forms.ModelForm):
# Column('allow_export', css_class='form-group col-md-4 mb-0'),
# css_class='form-row'
#),
Row(
Column('manage_cluster', css_class='form-group col-md-12 mb-0'),
css_class='form-row'
),
Row(
Column('enabled', css_class='form-group col-md-12 mb-0'),
css_class='form-row'
@@ -0,0 +1,18 @@
# Generated by Django 5.2.19 on 2026-11-23 17:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api_v2', '0002_alter_apikey_allow_export_alter_apikey_allow_reload_and_more'),
]
operations = [
migrations.AddField(
model_name='apikey',
name='manage_cluster',
field=models.BooleanField(default=False, help_text='Allows enabling and disabling cluster workers and WireGuard on the primary server.', verbose_name='Manage Cluster'),
),
]
+4
View File
@@ -13,6 +13,10 @@ class ApiKey(models.Model):
allow_restart = models.BooleanField(default=True, verbose_name=_("Allow Restart"))
allow_reload = models.BooleanField(default=True, verbose_name=_("Allow Reload"))
allow_export = models.BooleanField(default=True, verbose_name=_("Allow Export"))
manage_cluster = models.BooleanField(
default=False, verbose_name=_("Manage Cluster"),
help_text=_("Allows enabling and disabling cluster workers and WireGuard on the primary server."),
)
enabled = models.BooleanField(default=True, verbose_name=_("Enabled"))
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
+279 -163
View File
@@ -1,13 +1,17 @@
import json
from datetime import timedelta
from unittest.mock import patch
from django.test import TestCase
from django.test import TestCase, override_settings
from django.utils import timezone
from api_v2.models import ApiKey
from dns.models import DNSSettings, StaticHost
from vpn_invite.models import InviteSettings, PeerInvite
from cluster.models import ClusterSettings, Worker
from cluster.tests import create_instance
from dns.models import DNSSettings, StaticHost
from wireguard.models import Peer, WireGuardInstance
from wireguard_tools.models import EmailSettings
class ApiV2ManageDnsRecordTests(TestCase):
def setUp(self):
@@ -66,6 +70,7 @@ class ApiV2ManageDnsRecordTests(TestCase):
StaticHost.objects.create(hostname="app.example.com", ip_address="10.20.30.40")
DNSSettings.objects.create(name="dns_settings", pending_changes=True)
with self.captureOnCommitCallbacks(execute=True):
response = self.client.put(
self.url,
data=json.dumps({
@@ -87,6 +92,26 @@ class ApiV2ManageDnsRecordTests(TestCase):
def test_put_upserts_missing_record_as_create(self, mock_export):
mock_export.side_effect = self._fake_export_dns_configuration
with self.captureOnCommitCallbacks(execute=True):
response = self.client.put(
self.url,
data=json.dumps({
"hostname": "new.example.com",
"ip_address": "10.20.30.50",
"skip_reload": False,
"create_if_missing": True,
}),
content_type="application/json",
HTTP_TOKEN=str(self.api_key.token),
)
self.assertEqual(response.status_code, 201)
self.assertTrue(StaticHost.objects.filter(hostname="new.example.com").exists())
mock_export.assert_called_once()
@patch("api_v2.views_api.export_dns_configuration")
def test_put_missing_record_without_create_if_missing_returns_404(self, mock_export):
with self.captureOnCommitCallbacks(execute=True):
response = self.client.put(
self.url,
data=json.dumps({
@@ -98,9 +123,9 @@ class ApiV2ManageDnsRecordTests(TestCase):
HTTP_TOKEN=str(self.api_key.token),
)
self.assertEqual(response.status_code, 201)
self.assertTrue(StaticHost.objects.filter(hostname="new.example.com").exists())
mock_export.assert_called_once()
self.assertEqual(response.status_code, 404)
self.assertFalse(StaticHost.objects.filter(hostname="new.example.com").exists())
mock_export.assert_not_called()
@patch("api_v2.views_api.export_dns_configuration")
def test_delete_deletes_record_and_does_not_require_ip(self, mock_export):
@@ -120,179 +145,270 @@ class ApiV2ManageDnsRecordTests(TestCase):
self.assertFalse(StaticHost.objects.filter(hostname="del.example.com").exists())
mock_export.assert_not_called()
class ApiV2PeerInviteTests(TestCase):
@override_settings(WIREGUARD_STATUS_CACHE_ENABLED=True, CADDY_ENABLED=True)
class ApiV2ManageClusterTests(TestCase):
status_url = "/api/v2/manage_cluster/status/"
manage_url = "/api/v2/manage_cluster/manage_status/"
def setUp(self):
self.api_key = ApiKey.objects.create(name="invite-test-key", enabled=True)
self.wireguard_instance = WireGuardInstance.objects.create(
instance_id=0,
name="wg0",
address="10.0.0.1",
netmask=24,
listen_port=51820,
public_key="public_key",
private_key="private_key"
)
self.api_key.allowed_instances.add(self.wireguard_instance)
ClusterSettings.objects.update_or_create(name="cluster_settings", defaults={"enabled": True})
self.api_key = ApiKey.objects.create(name="cluster-key", manage_cluster=True)
self.node_a = Worker.objects.create(name="node-a")
self.node_b = Worker.objects.create(name="node-b", enabled=False)
self.instance = create_instance(0)
WireGuardInstance.objects.update(pending_changes=False)
self.peer = Peer.objects.create(
wireguard_instance=self.wireguard_instance,
name="Test Peer",
public_key="peer_public_key",
private_key="peer_private_key"
self.calls = []
self.stop_errors = []
for name, value in (
("running_wireguard_interfaces", lambda: ["wg0"]),
("start_primary_interfaces", self.record("start")),
("stop_primary_interfaces", self.record("stop")),
("apply_caddy_config", self.record("export")),
):
patcher = patch(f"api_v2.views_api.{name}", value)
patcher.start()
self.addCleanup(patcher.stop)
def record(self, name):
def call():
self.calls.append(name)
return list(self.stop_errors) if name == "stop" else []
return call
def manage(self, payload, api_key=None, method="put"):
return getattr(self.client, method)(
self.manage_url, data=json.dumps(payload), content_type="application/json",
HTTP_TOKEN=str((api_key or self.api_key).token),
)
# Create invite settings
InviteSettings.objects.create(
name='default_settings',
invite_url='https://vpn.example.com/invite/',
invite_expiration=30,
required_user_level=50,
invite_email_enabled=True
)
def assert_unchanged(self):
self.assertTrue(Worker.objects.get(pk=self.node_a.pk).enabled)
self.assertFalse(Worker.objects.get(pk=self.node_b.pk).enabled)
self.assertTrue(ClusterSettings.objects.get(name="cluster_settings").primary_enable_wireguard)
self.assertEqual(self.calls, [])
# Create email settings
EmailSettings.objects.create(
name='email_settings',
enabled=True,
smtp_host='smtp.example.com',
smtp_port=587,
smtp_username='user',
smtp_password='password',
smtp_from_address='vpn@example.com',
smtp_encryption='tls'
)
self.url = "/api/v2/peer_invite/"
def test_create_invite_without_email(self):
response = self.client.post(
self.url,
data=json.dumps({
"instance": "wg0",
"peer_uuid": str(self.peer.uuid)
}),
content_type="application/json",
HTTP_TOKEN=str(self.api_key.token),
)
def test_api_key_needs_manage_cluster(self):
plain_key = ApiKey.objects.create(name="plain-key")
self.assertEqual(self.client.get(self.status_url).status_code, 403)
self.assertEqual(self.client.get(self.status_url, HTTP_TOKEN=str(plain_key.token)).status_code, 403)
response = self.manage({"workers": {str(self.node_a.uuid): False}}, api_key=plain_key)
self.assertEqual(response.status_code, 403)
self.assertIn("not allowed to manage the cluster", response.json()["error_message"])
self.assert_unchanged()
def test_status_lists_cluster_and_workers_by_uuid(self):
response = self.client.get(self.status_url, HTTP_TOKEN=str(self.api_key.token))
self.assertEqual(response.status_code, 200)
body = response.json()
self.assertEqual(body["status"], "success")
self.assertEqual(body["message"], "Invitation created successfully.")
self.assertIn("invite_data", body)
self.assertIn("url", body["invite_data"])
self.assertIn("password", body["invite_data"])
self.assertIn("expiration", body["invite_data"])
self.assertEqual(body["cluster"], {
"enabled": True, "mode": "mirror", "primary_wireguard": True, "primary_running_interfaces": ["wg0"],
})
self.assertEqual(body["workers"][str(self.node_a.uuid)]["name"], "node-a")
self.assertFalse(body["workers"][str(self.node_b.uuid)]["enabled"])
self.assertIsNone(body["workers"][str(self.node_b.uuid)]["sync_state"])
# Verify invite was created
def test_workers_and_primary_change_in_a_single_request(self):
response = self.manage({
"workers": {str(self.node_a.uuid): False, str(self.node_b.uuid): True}, "primary_wireguard": False,
})
self.assertEqual(response.status_code, 200)
body = response.json()
self.assertEqual(body["workers"][str(self.node_a.uuid)], {"name": "node-a", "enabled": False, "changed": True})
self.assertEqual(body["workers"][str(self.node_b.uuid)], {"name": "node-b", "enabled": True, "changed": True})
self.assertEqual(body["primary_wireguard"], {"enabled": False, "changed": True})
self.assertTrue(body["apply"]["success"])
self.assertFalse(Worker.objects.get(pk=self.node_a.pk).enabled)
self.assertTrue(Worker.objects.get(pk=self.node_b.pk).enabled)
self.assertFalse(ClusterSettings.primary_serves_clients())
self.assertEqual(self.calls, ["export", "stop"])
self.instance.refresh_from_db()
self.assertFalse(self.instance.pending_changes)
# The same request again changes nothing
self.calls.clear()
body = self.manage({"workers": {str(self.node_a.uuid): False}, "primary_wireguard": False}).json()
self.assertFalse(body["workers"][str(self.node_a.uuid)]["changed"])
self.assertFalse(body["primary_wireguard"]["changed"])
self.assertEqual(self.calls, [])
def test_enabling_the_primary_starts_its_interfaces(self):
ClusterSettings.objects.filter(name="cluster_settings").update(primary_enable_wireguard=False)
response = self.manage({"primary_wireguard": True}, method="post")
self.assertEqual(response.status_code, 200)
self.assertEqual(self.calls, ["export", "start"])
self.assertTrue(ClusterSettings.primary_serves_clients())
def test_skip_reload_only_marks_the_instances_pending(self):
response = self.manage({"primary_wireguard": False, "skip_reload": True})
self.assertEqual(response.status_code, 200)
self.assertEqual(self.calls, [])
self.instance.refresh_from_db()
self.assertTrue(self.instance.pending_changes)
def test_worker_changes_do_not_touch_the_primary_interfaces(self):
response = self.manage({"workers": {str(self.node_a.uuid): False}})
self.assertEqual(response.status_code, 200)
self.assertNotIn("primary_wireguard", response.json())
self.assertEqual(self.calls, [])
def test_invalid_requests_change_nothing(self):
for payload in (
{},
{"workers": {}},
{"workers": {"00000000-0000-0000-0000-000000000000": False}, "primary_wireguard": False},
{"workers": {"node-a": False}},
{"workers": {str(self.node_a.uuid): "no"}},
{"workers": {str(self.node_b.uuid): True}, "primary_wireguard": 0},
):
response = self.manage(payload)
self.assertEqual(response.status_code, 400, payload)
self.assert_unchanged()
def test_primary_follows_the_cluster_settings_form_rules(self):
ClusterSettings.objects.filter(name="cluster_settings").update(cluster_mode="distributed")
response = self.manage({"workers": {str(self.node_a.uuid): False}, "primary_wireguard": False})
self.assertEqual(response.status_code, 400)
self.assertIn("only be disabled in mirror mode", response.json()["error_message"])
self.assert_unchanged()
def test_changes_require_an_enabled_cluster(self):
ClusterSettings.objects.filter(name="cluster_settings").update(enabled=False)
response = self.manage({"workers": {str(self.node_a.uuid): False}})
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()["error_message"], "The cluster is not enabled.")
self.assert_unchanged()
def test_apply_failure_keeps_the_saved_changes_pending(self):
self.stop_errors = [("wg0", "device busy")]
response = self.manage({"primary_wireguard": False})
self.assertEqual(response.status_code, 500)
self.assertIn("saved but apply failed: wg0: device busy", response.json()["error_message"])
self.assertFalse(ClusterSettings.objects.get(name="cluster_settings").primary_enable_wireguard)
self.instance.refresh_from_db()
self.assertTrue(self.instance.pending_changes)
def test_other_methods_are_not_allowed(self):
response = self.client.delete(self.manage_url, HTTP_TOKEN=str(self.api_key.token))
self.assertEqual(response.status_code, 405)
response = self.client.put(self.status_url, HTTP_TOKEN=str(self.api_key.token))
self.assertEqual(response.status_code, 405)
class ApiV2PeerInviteTests(TestCase):
url = "/api/v2/peer_invite/"
def setUp(self):
self.instance = create_instance(0)
self.other_instance = create_instance(1)
self.api_key = ApiKey.objects.create(name="invite-test-key", enabled=True)
self.api_key.allowed_instances.add(self.instance)
self.peer = Peer.objects.create(
wireguard_instance=self.instance, name="Test Peer", public_key="peer-public", private_key="peer-private",
)
self.invite_settings = InviteSettings.objects.create(
name="default_settings", invite_url="https://vpn.example.com/invite/", invite_expiration=30,
)
def request(self, payload, api_key=None):
return self.client.post(
self.url, data=json.dumps(payload), content_type="application/json",
HTTP_TOKEN=str((api_key or self.api_key).token),
)
def test_creates_invite(self):
response = self.request({"instance": "wg0", "peer_uuid": str(self.peer.uuid)})
self.assertEqual(response.status_code, 200)
body = response.json()
self.assertEqual(body["message"], "Invite created.")
invite = PeerInvite.objects.get(peer=self.peer)
self.assertEqual(body["invite_data"]["uuid"], str(invite.uuid))
self.assertEqual(body["invite_data"]["url"], f"https://vpn.example.com/invite/?token={invite.uuid}&")
self.assertEqual(body["invite_data"]["password"], invite.invite_password)
def test_selects_peer_by_public_key(self):
response = self.request({"instance": "wg0", "peer_public_key": "peer-public"})
self.assertEqual(response.status_code, 200)
self.assertTrue(PeerInvite.objects.filter(peer=self.peer).exists())
def test_create_invite_with_invalid_peer_uuid(self):
response = self.client.post(
self.url,
data=json.dumps({
"instance": "wg0",
"peer_uuid": "00000000-0000-0000-0000-000000000000"
}),
content_type="application/json",
HTTP_TOKEN=str(self.api_key.token),
def test_existing_invite_is_renewed(self):
self.request({"instance": "wg0", "peer_uuid": str(self.peer.uuid)})
invite = PeerInvite.objects.get(peer=self.peer)
PeerInvite.objects.filter(pk=invite.pk).update(
invite_expiration=invite.invite_expiration - timedelta(minutes=20)
)
self.assertEqual(response.status_code, 404)
body = response.json()
self.assertEqual(body["status"], "error")
self.assertEqual(body["error_message"], "Peer not found.")
def test_create_invite_without_peer_uuid(self):
response = self.client.post(
self.url,
data=json.dumps({
"instance": "wg0"
}),
content_type="application/json",
HTTP_TOKEN=str(self.api_key.token),
)
self.assertEqual(response.status_code, 400)
body = response.json()
self.assertEqual(body["status"], "error")
self.assertEqual(body["error_message"], "peer_uuid is required.")
def test_create_invite_with_invalid_instance(self):
response = self.client.post(
self.url,
data=json.dumps({
"instance": "wg999",
"peer_uuid": str(self.peer.uuid)
}),
content_type="application/json",
HTTP_TOKEN=str(self.api_key.token),
)
self.assertEqual(response.status_code, 400)
body = response.json()
self.assertEqual(body["status"], "error")
self.assertEqual(body["error_message"], "Invalid or missing WireGuard instance.")
@patch("wgwadmlibrary.tools.send_email")
def test_create_invite_with_email(self, mock_send_email):
mock_send_email.return_value = ('success', 'Email sent successfully.')
response = self.client.post(
self.url,
data=json.dumps({
"instance": "wg0",
"peer_uuid": str(self.peer.uuid),
"email": "user@example.com"
}),
content_type="application/json",
HTTP_TOKEN=str(self.api_key.token),
)
response = self.request({"instance": "wg0", "peer_uuid": str(self.peer.uuid)})
self.assertEqual(response.status_code, 200)
body = response.json()
self.assertEqual(body["status"], "success")
self.assertEqual(body["message"], "Invitation created and email sent successfully.")
self.assertIn("invite_data", body)
# Verify email was sent
mock_send_email.assert_called_once()
@patch("wgwadmlibrary.tools.send_email")
def test_create_invite_with_email_failure(self, mock_send_email):
mock_send_email.return_value = ('error', 'SMTP server not available')
response = self.client.post(
self.url,
data=json.dumps({
"instance": "wg0",
"peer_uuid": str(self.peer.uuid),
"email": "user@example.com"
}),
content_type="application/json",
HTTP_TOKEN=str(self.api_key.token),
)
self.assertEqual(response.json()["message"], "Existing invite renewed.")
renewed = PeerInvite.objects.get(peer=self.peer)
self.assertEqual(renewed.uuid, invite.uuid)
self.assertGreater(renewed.invite_expiration, timezone.now() + timedelta(minutes=25))
def test_missing_peer_selector(self):
response = self.request({"instance": "wg0"})
self.assertEqual(response.status_code, 400)
body = response.json()
self.assertEqual(body["status"], "error")
self.assertIn("email failed", body["error_message"])
self.assertIn("invite_data", body)
self.assertEqual(response.json()["error_message"], "Missing peer selector (peer_uuid or peer_public_key).")
def test_create_invite_without_invite_settings(self):
InviteSettings.objects.all().delete()
response = self.client.post(
self.url,
data=json.dumps({
"instance": "wg0",
"peer_uuid": str(self.peer.uuid)
}),
content_type="application/json",
HTTP_TOKEN=str(self.api_key.token),
)
def test_unknown_peer(self):
for peer_uuid in ("00000000-0000-0000-0000-000000000000", "not-a-uuid"):
response = self.request({"instance": "wg0", "peer_uuid": peer_uuid})
self.assertEqual(response.status_code, 404)
self.assertEqual(response.json()["error_message"], "Peer not found.")
def test_invalid_instance(self):
response = self.request({"instance": "wg999", "peer_uuid": str(self.peer.uuid)})
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()["error_message"], "Invalid or missing WireGuard instance.")
def test_peer_of_another_instance_is_not_found(self):
unrestricted_key = ApiKey.objects.create(name="unrestricted-key", enabled=True)
response = self.request({"instance": "wg1", "peer_uuid": str(self.peer.uuid)}, api_key=unrestricted_key)
self.assertEqual(response.status_code, 404)
self.assertFalse(PeerInvite.objects.exists())
def test_api_key_without_access_to_the_instance(self):
other_peer = Peer.objects.create(
wireguard_instance=self.other_instance, name="Other Peer", public_key="other-public", private_key="other-private",
)
response = self.request({"instance": "wg1", "peer_uuid": str(other_peer.uuid)})
self.assertEqual(response.status_code, 403)
self.assertFalse(PeerInvite.objects.exists())
def test_peer_with_endpoint_is_refused(self):
Peer.objects.filter(pk=self.peer.pk).update(endpoint="remote.example.com:51820")
response = self.request({"instance": "wg0", "peer_uuid": str(self.peer.uuid)})
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()["error_message"], "Peers with an endpoint have no client configuration to share.")
self.assertFalse(PeerInvite.objects.exists())
@patch("api_v2.views_api.send_email")
def test_email_disabled_in_invite_settings(self, mock_send_email):
InviteSettings.objects.filter(pk=self.invite_settings.pk).update(invite_email_enabled=False)
response = self.request({"instance": "wg0", "peer_uuid": str(self.peer.uuid), "email": "user@example.com"})
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()["error_message"], "Email invites are disabled in the VPN invite settings.")
self.assertFalse(PeerInvite.objects.exists())
mock_send_email.assert_not_called()
@patch("api_v2.views_api.send_email")
def test_sends_invite_by_email(self, mock_send_email):
mock_send_email.return_value = ("success", "Email sent successfully.")
response = self.request({"instance": "wg0", "peer_uuid": str(self.peer.uuid), "email": "user@example.com"})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["message"], "Invite created. Email sent to user@example.com.")
invite_data = response.json()["invite_data"]
mock_send_email.assert_called_once_with("user@example.com", invite_data["email_subject"], invite_data["email_body"])
@patch("api_v2.views_api.send_email")
def test_email_failure_keeps_the_invite(self, mock_send_email):
mock_send_email.return_value = ("error", "SMTP server not available")
response = self.request({"instance": "wg0", "peer_uuid": str(self.peer.uuid), "email": "user@example.com"})
self.assertEqual(response.status_code, 500)
body = response.json()
self.assertEqual(body["status"], "error")
self.assertEqual(body["error_message"], "VPN Invite not configured.")
self.assertEqual(body["error_message"], "Invite created, but the email could not be sent: SMTP server not available")
self.assertEqual(body["invite_data"]["uuid"], str(PeerInvite.objects.get(peer=self.peer).uuid))
def test_other_methods_are_not_allowed(self):
response = self.client.get(self.url, HTTP_TOKEN=str(self.api_key.token))
self.assertEqual(response.status_code, 405)
+4
View File
@@ -1,6 +1,8 @@
from django.urls import path
from .views_api import (
api_v2_manage_cluster_manage_status,
api_v2_manage_cluster_status,
api_v2_manage_dns_record,
api_v2_manage_peer,
api_v2_peer_detail,
@@ -16,4 +18,6 @@ urlpatterns = [
path('peer_detail/', api_v2_peer_detail, name='api_v2_peer_detail'),
path('peer_invite/', api_v2_peer_invite, name='api_v2_peer_invite'),
path('wireguard_status/', api_v2_wireguard_status, name='api_v2_wireguard_status'),
path('manage_cluster/status/', api_v2_manage_cluster_status, name='api_v2_manage_cluster_status'),
path('manage_cluster/manage_status/', api_v2_manage_cluster_manage_status, name='api_v2_manage_cluster_manage_status'),
]
+406 -91
View File
@@ -1,25 +1,35 @@
import ipaddress
import json
import re
from datetime import timedelta
from functools import wraps
from typing import List, Optional, Tuple
from django import forms
from django.conf import settings as django_settings
from django.core.exceptions import ValidationError
from django.db import transaction
from django.http import JsonResponse
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from api.views import func_get_wireguard_status
from app_gateway.caddy_config_export import apply_caddy_config
from cluster.forms import ClusterSettingsForm
from cluster.models import ClusterSettings, Worker, WorkerStatus
from cluster.sync import get_worker_sync_state
from dns.models import DNSSettings, StaticHost
from dns.views import export_dns_configuration
from routing_templates.models import RoutingTemplate
from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance
from wireguard_peer.functions import func_create_new_peer
from wireguard_tools.functions import func_reload_wireguard_interface
from wireguard_tools.views import export_wireguard_configuration
from wireguard_peer.forms import normalize_endpoint
from wireguard_peer.functions import find_network_in_other_instance, func_create_new_peer
from wireguard_tools.functions import (
func_reload_wireguard_interface, running_wireguard_interfaces, start_primary_interfaces, stop_primary_interfaces,
)
from vpn_invite.models import InviteSettings, PeerInvite
from wgwadmlibrary.tools import create_peer_invite, get_peer_invite_data, send_email, user_has_access_to_peer
from wgwadmlibrary.tools import create_peer_invite, get_peer_invite_data, send_email
from wireguard_tools.views import export_wireguard_configuration
from .models import ApiKey
@@ -225,6 +235,8 @@ def _validate_dns_hostname(hostname: str) -> Tuple[Optional[str], Optional[str]]
"example": ["192.168.1.0/24"],
"description": "Client routes (priority>=1). Will be synced. Not allowed when allow_peer_custom_routes=True."},
{"name": "name", "in": "json", "type": "string", "required": False, "example": "John",
"description": "Peer name (create/update). Can be cleared by sending null/empty string."},
{"name": "public_key", "in": "json", "type": "string", "required": False,
"description": "Peer public key (create/update)."},
{"name": "pre_shared_key", "in": "json", "type": "string", "required": False,
@@ -237,6 +249,13 @@ def _validate_dns_hostname(hostname: str) -> Tuple[Optional[str], Optional[str]]
"description": "Suspend/unsuspend a peer (update)."},
{"name": "suspend_reason", "in": "json", "type": "string", "required": False,
"description": "Suspend reason (update). Can be cleared by sending null/empty string."},
{"name": "endpoint", "in": "json", "type": "string", "required": False, "example": "vpn.example.com:51820",
"description": "Address (host:port) of a remote WireGuard server that this server connects to (create/update). "
"Cleared by sending an empty string. A peer with an endpoint may use a main address outside "
"the instance network."},
{"name": "active_worker_uuid", "in": "json", "type": "string", "required": False,
"description": "Cluster worker that connects to the endpoint in the mirror mode (create/update). Null or "
"empty means the primary server."},
],
returns=[
{"status": 200, "body": {"status": "success", "message": "Peer updated successfully.", "peer_uuid": "...", "public_key": "...", "main_addresses": ["..."], "reload": {"success": True, "message": "..."}}},
@@ -261,6 +280,7 @@ def _validate_dns_hostname(hostname: str) -> Tuple[Optional[str], Optional[str]]
"json": {
"instance": "wg0",
"peer_uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"name": "John Notebook",
"suspended": True,
"suspend_reason": "Maintenance window",
"skip_reload": False
@@ -308,11 +328,36 @@ def api_v2_manage_peer(request):
announced_pairs, announced_error = _parse_ipv4_cidrs(payload.get("announced_networks"))
if announced_error:
return JsonResponse({"status": "error", "error_message": announced_error}, status=400)
for allowed_ip, netmask in announced_pairs or []:
other_network = find_network_in_other_instance(wireguard_instance, allowed_ip, netmask)
if other_network:
return JsonResponse({
"status": "error",
"error_message": f"Network {allowed_ip}/{netmask} is already used by a peer of "
f"wg{other_network.peer.wireguard_instance.instance_id}. A network can be routed to "
f"only one WireGuard instance.",
}, status=400)
client_route_pairs, client_route_error = _parse_ipv4_cidrs(payload.get("client_routes"))
if client_route_error:
return JsonResponse({"status": "error", "error_message": client_route_error}, status=400)
new_endpoint = None
if "endpoint" in payload:
try:
new_endpoint = normalize_endpoint(str(payload.get("endpoint") or ""))
except forms.ValidationError as error:
return JsonResponse({"status": "error", "error_message": f"Invalid endpoint: {error.messages[0]}"}, status=400)
new_active_worker = None
if payload.get("active_worker_uuid"):
try:
new_active_worker = Worker.objects.filter(uuid=payload.get("active_worker_uuid")).first()
except (ValidationError, ValueError):
new_active_worker = None
if not new_active_worker:
return JsonResponse({"status": "error", "error_message": "Invalid active_worker_uuid."}, status=400)
with transaction.atomic():
# CREATE
if request.method == "POST":
@@ -342,6 +387,9 @@ def api_v2_manage_peer(request):
create_overrides["persistent_keepalive"] = peer_persistent_keepalive
if peer_allowed_ip:
create_overrides["allowed_ip"] = str(peer_allowed_ip).strip()
if new_endpoint:
create_overrides["endpoint"] = new_endpoint
create_overrides["active_worker"] = new_active_worker
if routing_template is not None:
create_overrides["default_routing_template"] = routing_template
@@ -413,6 +461,12 @@ def api_v2_manage_peer(request):
new_suspended = payload.get("suspended")
new_suspend_reason = payload.get("suspend_reason") if "suspend_reason" in payload else None
if "name" in payload:
new_name = str(payload.get("name") or "").strip()
if len(new_name) > 100:
return JsonResponse({"status": "error", "error_message": "Invalid name. Maximum length is 100 characters."}, status=400)
peer_for_action.name = new_name
if new_public_key:
peer_for_action.public_key = new_public_key
@@ -437,6 +491,13 @@ def api_v2_manage_peer(request):
if "suspend_reason" in payload:
peer_for_action.suspend_reason = new_suspend_reason
if new_endpoint is not None:
peer_for_action.endpoint = new_endpoint
if "active_worker_uuid" in payload:
peer_for_action.active_worker = new_active_worker
if not peer_for_action.endpoint:
peer_for_action.active_worker = None
peer_for_action.save()
_sync_allowed_ips(peer_for_action, announced_pairs, config_file="server")
@@ -715,6 +776,7 @@ def api_v2_peer_list(request):
"suspend_reason": current_peer.suspend_reason or "",
"disabled_by_schedule": bool(current_peer.disabled_by_schedule),
"main_addresses": current_peer.main_addresses,
"endpoint": current_peer.endpoint,
})
return JsonResponse(
@@ -741,7 +803,7 @@ def api_v2_peer_list(request):
"description": "Peer public key selector."},
],
returns=[
{"status": 200, "body": {"status": "success", "peer": {"uuid": "...", "name": "...", "public_key": "...", "pre_shared_key": "...", "private_key": "...", "persistent_keepalive": 25, "routing_template_uuid": "...", "suspended": False, "suspend_reason": "...", "disabled_by_schedule": False, "enabled": True, "main_addresses": ["..."], "announced_networks": ["..."], "client_routes": ["..."], "instance": "...", "instance_uuid": "..."}}},
{"status": 200, "body": {"status": "success", "peer": {"uuid": "...", "name": "...", "public_key": "...", "pre_shared_key": "...", "private_key": "...", "persistent_keepalive": 25, "routing_template_uuid": "...", "suspended": False, "suspend_reason": "...", "disabled_by_schedule": False, "enabled": True, "main_addresses": ["..."], "announced_networks": ["..."], "client_routes": ["..."], "endpoint": "", "active_worker_uuid": "", "instance": "...", "instance_uuid": "..."}}},
{"status": 400, "body": {"status": "error", "error_message": "Missing peer selector (peer_uuid or peer_public_key)."}},
{"status": 404, "body": {"status": "error", "error_message": "Peer not found."}},
{"status": 403, "body": {"status": "error", "error_message": "Invalid API key."}},
@@ -817,6 +879,8 @@ def api_v2_peer_detail(request):
"main_addresses": current_peer.main_addresses,
"announced_networks": current_peer.announced_networks,
"client_routes": current_peer.client_routes,
"endpoint": current_peer.endpoint,
"active_worker_uuid": str(current_peer.active_worker.uuid) if current_peer.active_worker else "",
"instance": f"wg{wireguard_instance.instance_id}",
"instance_uuid": str(wireguard_instance.uuid),
}
@@ -824,6 +888,126 @@ def api_v2_peer_detail(request):
return JsonResponse({"status": "success", "peer": peer_data}, status=200)
@csrf_exempt
@api_doc(
summary="Create a VPN invite for a peer and optionally send it by email",
auth="Header token: <ApiKey.token>",
methods=["POST"],
params=[
{"name": "instance", "in": "json", "type": "string", "required": True, "example": "wg0",
"description": "Required. Target instance name in the format wg{instance_id} (e.g. wg0, wg1)."},
{"name": "peer_uuid", "in": "json", "type": "string", "required": False,
"description": "Peer UUID selector."},
{"name": "peer_public_key", "in": "json", "type": "string", "required": False,
"description": "Peer public key selector."},
{"name": "email", "in": "json", "type": "string", "required": False,
"description": "Optional. Sends the invite to this address. Requires email invites to be enabled in the VPN invite settings."},
],
returns=[
{"status": 200, "body": {"status": "success", "message": "Invite created.", "invite_data": {"url": "...", "password": "...", "expiration": "...", "email_subject": "...", "email_body": "...", "whatsapp_body": "...", "text_body": "...", "uuid": "..."}}},
{"status": 400, "body": {"status": "error", "error_message": "Peers with an endpoint have no client configuration to share."}},
{"status": 403, "body": {"status": "error", "error_message": "Invalid API key."}},
{"status": 404, "body": {"status": "error", "error_message": "Peer not found."}},
{"status": 500, "body": {"status": "error", "error_message": "Invite created, but the email could not be sent: ...", "invite_data": {"url": "..."}}},
],
examples={
"create_invite": {"method": "POST", "json": {"instance": "wg0", "peer_uuid": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"}},
"create_and_send_invite": {"method": "POST", "json": {"instance": "wg0", "peer_uuid": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "email": "user@example.com"}},
}
)
def api_v2_peer_invite(request):
if request.method != "POST":
return JsonResponse({"status": "error", "error_message": "Method not allowed."}, status=405)
try:
payload = json.loads(request.body.decode("utf-8")) if request.body else {}
except Exception:
return JsonResponse({"status": "error", "error_message": "Invalid JSON body."}, status=400)
if not isinstance(payload, dict):
return JsonResponse({"status": "error", "error_message": "Invalid JSON body."}, status=400)
try:
wireguard_instance = WireGuardInstance.objects.get(
instance_id=int(str(payload.get("instance")).replace("wg", ""))
)
except Exception:
wireguard_instance = None
if not wireguard_instance:
return JsonResponse({"status": "error", "error_message": "Invalid or missing WireGuard instance."}, status=400)
api_key, api_error = validate_api_key(request, wireguard_instance=wireguard_instance)
if not api_key:
return JsonResponse({"status": "error", "error_message": api_error}, status=403)
selector_peer_uuid = payload.get("peer_uuid")
selector_peer_public_key = payload.get("peer_public_key")
if not selector_peer_uuid and not selector_peer_public_key:
return JsonResponse(
{"status": "error", "error_message": "Missing peer selector (peer_uuid or peer_public_key)."},
status=400,
)
peers = Peer.objects.filter(wireguard_instance=wireguard_instance)
try:
if selector_peer_uuid:
peer = peers.filter(uuid=selector_peer_uuid).first()
else:
peer = peers.filter(public_key=selector_peer_public_key).first()
except ValidationError:
peer = None
if not peer:
return JsonResponse({"status": "error", "error_message": "Peer not found."}, status=404)
if peer.endpoint:
return JsonResponse(
{"status": "error", "error_message": "Peers with an endpoint have no client configuration to share."},
status=400,
)
invite_settings = InviteSettings.objects.filter(name='default_settings').first()
if not invite_settings:
return JsonResponse({"status": "error", "error_message": "VPN invite is not configured."}, status=400)
email = payload.get("email")
if email:
if not isinstance(email, str):
return JsonResponse({"status": "error", "error_message": "Invalid email address."}, status=400)
if not invite_settings.invite_email_enabled:
return JsonResponse(
{"status": "error", "error_message": "Email invites are disabled in the VPN invite settings."},
status=400,
)
PeerInvite.objects.filter(invite_expiration__lt=timezone.now()).delete()
peer_invite = PeerInvite.objects.filter(peer=peer).first()
if peer_invite:
# An existing invite is renewed, so the returned link is valid for the whole expiration period
peer_invite.invite_expiration = timezone.now() + timedelta(minutes=invite_settings.invite_expiration)
peer_invite.save()
message = "Existing invite renewed."
else:
peer_invite = create_peer_invite(peer, invite_settings)
message = "Invite created."
invite_data = get_peer_invite_data(peer_invite, invite_settings)
if email:
email_status, email_message = send_email(email, invite_data['email_subject'], invite_data['email_body'])
if email_status != 'success':
return JsonResponse(
{
"status": "error",
"error_message": f"Invite created, but the email could not be sent: {email_message}",
"invite_data": invite_data,
},
status=500,
)
message = f"{message} Email sent to {email}."
return JsonResponse({"status": "success", "message": message, "invite_data": invite_data}, status=200)
@csrf_exempt
@api_doc(
summary="Get WireGuard status (dump) for all interfaces/peers",
@@ -853,116 +1037,247 @@ def api_v2_wireguard_status(request):
data = func_get_wireguard_status()
return JsonResponse(data)
def _validate_cluster_api_key(request):
api_key, api_error = validate_api_key(request)
if not api_key:
return None, JsonResponse({"status": "error", "error_message": api_error}, status=403)
if not api_key.manage_cluster:
return None, JsonResponse(
{"status": "error", "error_message": "This API key is not allowed to manage the cluster."}, status=403
)
return api_key, None
def _worker_status_data(worker):
worker_status = WorkerStatus.objects.filter(worker=worker).first()
operational = worker.enabled and not worker.error_status and worker.is_online
return {
"name": worker.name,
"enabled": worker.enabled,
"online": worker.is_online,
"last_seen": worker_status.last_seen.isoformat() if worker_status else None,
"worker_version": worker_status.worker_version if worker_status else None,
"error_status": worker.error_status,
# Reported data of disabled, refused or offline workers is only the last known state
"sync_state": get_worker_sync_state(worker)["state"] if operational else None,
}
@csrf_exempt
@api_doc(
summary="Create and send VPN peer invitations",
auth="Header token: <ApiKey.token>",
methods=["POST"],
params=[
{"name": "instance", "in": "json", "type": "string", "required": True, "example": "wg0",
"description": "Target instance name in the format wg{instance_id} (e.g. wg0, wg1)."},
{"name": "peer_uuid", "in": "json", "type": "string", "required": True,
"description": "Peer UUID to create invitation for."},
{"name": "email", "in": "json", "type": "string", "required": False,
"description": "Email address to send the invitation to. If provided, the invitation will be sent automatically."},
],
summary="Cluster status: settings, WireGuard on the primary server and workers",
auth="Header token: <ApiKey.token> (the API key must have Manage Cluster enabled)",
methods=["GET", "POST"],
params=[],
returns=[
{"status": 200, "body": {"status": "success", "message": "Invitation created successfully.", "invite_data": {"url": "...", "password": "...", "expiration": "...", "email_subject": "...", "email_body": "...", "whatsapp_body": "...", "text_body": "...", "uuid": "..."}}},
{"status": 400, "body": {"status": "error", "error_message": "Invalid payload: ..."}},
{"status": 403, "body": {"status": "error", "error_message": "Invalid API key or permission denied."}},
{"status": 404, "body": {"status": "error", "error_message": "Peer not found."}},
{"status": 200, "body": {
"status": "success",
"cluster": {"enabled": True, "mode": "mirror", "primary_wireguard": True,
"primary_running_interfaces": ["wg0"]},
"workers": {"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx": {
"name": "node-a", "enabled": True, "online": True, "last_seen": "2026-01-01T12:00:00+00:00",
"worker_version": 15, "error_status": "", "sync_state": "synced"}},
}},
{"status": 403, "body": {"status": "error", "error_message": "This API key is not allowed to manage the cluster."}},
{"status": 405, "body": {"status": "error", "error_message": "Method not allowed."}},
],
examples={
"create_invite": {
"method": "POST",
"get_cluster_status": {
"method": "GET",
"json": {}
}
}
)
def api_v2_manage_cluster_status(request):
if request.method not in ("GET", "POST"):
return JsonResponse({"status": "error", "error_message": "Method not allowed."}, status=405)
api_key, error_response = _validate_cluster_api_key(request)
if error_response:
return error_response
cluster_settings, cluster_settings_created = ClusterSettings.objects.get_or_create(name='cluster_settings')
return JsonResponse({
"status": "success",
"cluster": {
"enabled": cluster_settings.enabled,
"mode": cluster_settings.cluster_mode,
"primary_wireguard": cluster_settings.primary_enable_wireguard,
"primary_running_interfaces": running_wireguard_interfaces(),
},
"workers": {str(worker.uuid): _worker_status_data(worker) for worker in Worker.objects.order_by('name')},
})
@csrf_exempt
@api_doc(
summary="Enable / disable cluster workers and WireGuard on the primary server in a single request",
auth="Header token: <ApiKey.token> (the API key must have Manage Cluster enabled)",
methods=["PUT", "POST"],
params=[
{"name": "workers", "in": "json", "type": "object", "required": False,
"example": {"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx": False},
"description": "Map of worker UUID to the desired state (true = enabled). Workers apply the change on "
"their next synchronization."},
{"name": "primary_wireguard", "in": "json", "type": "boolean", "required": False, "example": False,
"description": "Enables or disables WireGuard on the primary server. Disabling is only allowed in mirror "
"mode: the primary server stops its interfaces and only publishes WireGuard WebAdmin in the "
"App Gateway, while the workers serve the clients."},
{"name": "skip_reload", "in": "json", "type": "boolean", "required": False, "example": False,
"description": "If true, the WireGuard interfaces of the primary server are not started or stopped and "
"the instances are marked with pending_changes=True."},
],
returns=[
{"status": 200, "body": {
"status": "success", "message": "Cluster updated successfully.",
"workers": {"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx": {"name": "node-a", "enabled": False, "changed": True}},
"primary_wireguard": {"enabled": False, "changed": True},
"apply": {"success": True, "message": "..."},
}},
{"status": 400, "body": {"status": "error", "error_message": "The cluster is not enabled."}},
{"status": 403, "body": {"status": "error", "error_message": "This API key is not allowed to manage the cluster."}},
{"status": 405, "body": {"status": "error", "error_message": "Method not allowed."}},
{"status": 500, "body": {"status": "error", "error_message": "Cluster changes were saved but apply failed: ..."}},
],
examples={
"disable_worker_and_primary": {
"method": "PUT",
"json": {
"instance": "wg0",
"peer_uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
"workers": {"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx": False},
"primary_wireguard": False
}
},
"create_and_send_invite": {
"method": "POST",
"enable_workers": {
"method": "PUT",
"json": {
"instance": "wg0",
"peer_uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"email": "user@example.com"
"workers": {
"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx": True,
"yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy": True
}
}
}
}
)
def api_v2_peer_invite(request):
if request.method != "POST":
def api_v2_manage_cluster_manage_status(request):
if request.method not in ("PUT", "POST"):
return JsonResponse({"status": "error", "error_message": "Method not allowed."}, status=405)
try:
payload = json.loads(request.body.decode("utf-8")) if request.body else {}
except Exception:
return JsonResponse({"status": "error", "error_message": "Invalid JSON body."}, status=400)
if not isinstance(payload, dict):
return JsonResponse({"status": "error", "error_message": "Invalid JSON body."}, status=400)
# Validate API key
api_key, api_error = validate_api_key(request)
if not api_key:
return JsonResponse({"status": "error", "error_message": api_error}, status=403)
api_key, error_response = _validate_cluster_api_key(request)
if error_response:
return error_response
# Get and validate instance
cluster_settings, cluster_settings_created = ClusterSettings.objects.get_or_create(name='cluster_settings')
if not cluster_settings.enabled:
return JsonResponse({"status": "error", "error_message": "The cluster is not enabled."}, status=400)
requested_workers = payload.get("workers")
primary_wireguard = payload.get("primary_wireguard")
skip_reload = bool(payload.get("skip_reload", False))
if requested_workers is None and primary_wireguard is None:
return JsonResponse(
{"status": "error", "error_message": "Invalid payload: inform workers and/or primary_wireguard."}, status=400
)
# Everything is validated before any change is saved
workers = {}
if requested_workers is not None:
if not isinstance(requested_workers, dict) or not requested_workers:
return JsonResponse(
{"status": "error", "error_message": "Invalid payload: workers must map worker UUIDs to true or false."},
status=400
)
for worker_uuid, enabled in requested_workers.items():
if not isinstance(enabled, bool):
return JsonResponse(
{"status": "error", "error_message": f"Invalid payload: the state of worker {worker_uuid} must be true or false."},
status=400
)
try:
wireguard_instance = WireGuardInstance.objects.get(instance_id=int(payload.get("instance", "").replace("wg", "")))
except Exception:
wireguard_instance = None
worker = Worker.objects.get(uuid=worker_uuid)
except (Worker.DoesNotExist, ValidationError, ValueError):
return JsonResponse({"status": "error", "error_message": f"Worker not found: {worker_uuid}"}, status=400)
workers[worker] = enabled
if not wireguard_instance:
return JsonResponse({"status": "error", "error_message": "Invalid or missing WireGuard instance."}, status=400)
settings_form = None
# Validating the form already copies the new value to cluster_settings
previous_primary_wireguard = cluster_settings.primary_enable_wireguard
if primary_wireguard is not None:
if not isinstance(primary_wireguard, bool):
return JsonResponse(
{"status": "error", "error_message": "Invalid payload: primary_wireguard must be true or false."}, status=400
)
# Same rules as the cluster settings form
settings_form = ClusterSettingsForm(data={
"enabled": cluster_settings.enabled,
"primary_enable_wireguard": primary_wireguard,
"cluster_mode": cluster_settings.cluster_mode,
"worker_display": cluster_settings.worker_display,
}, instance=cluster_settings)
if not settings_form.is_valid():
errors = [str(error) for field_errors in settings_form.errors.values() for error in field_errors]
return JsonResponse({"status": "error", "error_message": " ".join(errors)}, status=400)
# Validate API key has access to this instance
if api_key.allowed_instances.exists():
if not api_key.allowed_instances.filter(uuid=wireguard_instance.uuid).exists():
return JsonResponse({"status": "error", "error_message": "This API key is not allowed to access the requested instance."}, status=403)
primary_served_clients = ClusterSettings.primary_serves_clients()
worker_results = {}
with transaction.atomic():
for worker, enabled in workers.items():
changed = worker.enabled != enabled
if changed:
worker.enabled = enabled
worker.save(update_fields=["enabled", "updated"])
worker_results[str(worker.uuid)] = {"name": worker.name, "enabled": enabled, "changed": changed}
# Get peer
peer_uuid = payload.get("peer_uuid")
if not peer_uuid:
return JsonResponse({"status": "error", "error_message": "peer_uuid is required."}, status=400)
primary_result = None
primary_changed = False
if settings_form is not None:
primary_changed = previous_primary_wireguard != primary_wireguard
settings_form.save()
primary_result = {"enabled": primary_wireguard, "changed": primary_changed}
if ClusterSettings.primary_serves_clients() != primary_served_clients:
WireGuardInstance.objects.update(pending_changes=True)
peer = Peer.objects.filter(uuid=peer_uuid, wireguard_instance=wireguard_instance).first()
if not peer:
return JsonResponse({"status": "error", "error_message": "Peer not found."}, status=404)
apply_success = True
if not primary_changed:
apply_message = "Workers apply the changes on their next synchronization."
elif skip_reload:
apply_message = "Changes saved. Apply skipped (pending_changes set to True)."
else:
try:
if django_settings.CADDY_ENABLED:
apply_caddy_config()
except Exception as error:
return JsonResponse(
{"status": "error", "error_message": f"Cluster changes were saved but apply failed: {error}"}, status=500
)
if ClusterSettings.primary_serves_clients():
errors = start_primary_interfaces()
apply_message = "WireGuard interfaces of the primary server started."
else:
errors = stop_primary_interfaces()
apply_message = "WireGuard interfaces of the primary server stopped."
if errors:
details = "; ".join(f"{interface_name}: {error}" for interface_name, error in errors)
return JsonResponse(
{"status": "error", "error_message": f"Cluster changes were saved but apply failed: {details}"},
status=500
)
WireGuardInstance.objects.update(pending_changes=False)
# Check if API key has access to this peer - API keys have access to all peers in allowed instances
# Clean up expired invites
PeerInvite.objects.filter(invite_expiration__lt=timezone.now()).delete()
# Get invite settings
invite_settings = InviteSettings.objects.filter(name='default_settings').first()
if not invite_settings:
return JsonResponse({"status": "error", "error_message": "VPN Invite not configured."}, status=400)
# Check user level - API keys are considered as admin level (50)
if invite_settings.required_user_level > 50:
return JsonResponse({"status": "error", "error_message": "Permission denied."}, status=403)
# Get or create peer invite
peer_invite = PeerInvite.objects.filter(peer=peer).first()
if not peer_invite:
peer_invite = create_peer_invite(peer, invite_settings)
# Prepare response data
data = {
'status': 'success',
'message': 'Invitation created successfully.',
'invite_data': get_peer_invite_data(peer_invite, invite_settings)
response_data = {
"status": "success",
"message": "Cluster updated successfully.",
"apply": {"success": apply_success, "message": apply_message},
}
# Send email if requested
email = payload.get("email")
if email:
status, message = send_email(email, data['invite_data']['email_subject'], data['invite_data']['email_body'])
if status != 'success':
return JsonResponse({
"status": "error",
"error_message": f"Invitation created but email failed: {message}",
"invite_data": data['invite_data']
}, status=400)
data['message'] = 'Invitation created and email sent successfully.'
return JsonResponse(data, status=200)
if worker_results:
response_data["workers"] = worker_results
if primary_result is not None:
response_data["primary_wireguard"] = primary_result
return JsonResponse(response_data)
+200 -17
View File
@@ -1,9 +1,16 @@
import hashlib
import json
import os
import shutil
from django.conf import settings
from django.contrib import messages
from django.utils.translation import gettext as _
from app_gateway.models import (
AccessPolicy, Application, ApplicationPolicy, RESERVED_APP_NAME
AccessPolicy, Application, ApplicationHost, ApplicationPolicy, RESERVED_APP_NAME
)
from cluster.models import Worker
from gatekeeper.models import (
AuthMethod, GatekeeperGroup, GatekeeperIPAddress, GatekeeperUser
)
@@ -14,11 +21,43 @@ POLICY_TYPE_MAP = {
'deny': 'deny',
}
# Written by the Caddy container of the primary server, read-only for Django
CERTIFICATE_EXPORT_DIR = '/caddy_cert_export'
ACME_CERTIFICATE_TYPES = ('http_challenge', 'dns_challenge')
def build_applications_data():
applications = Application.objects.exclude(name=RESERVED_APP_NAME).prefetch_related('hosts')
def get_served_applications(worker=None):
"""Applications published by the primary server (worker=None) or by a cluster worker."""
applications = Application.objects.prefetch_related('hosts', 'workers')
if worker is not None:
applications = applications.exclude(name=RESERVED_APP_NAME)
return [application for application in applications if application.is_served_by(worker)]
def certificate_file_name(certificate):
return hashlib.sha256(certificate.encode()).hexdigest()
def read_exported_certificate(hostname):
"""Return (certificate, private_key) exported for a hostname, or (None, None)."""
if '/' in hostname or hostname in ('', '.', '..'):
return None, None
certificate_dir = os.path.join(CERTIFICATE_EXPORT_DIR, hostname)
try:
with open(os.path.join(certificate_dir, 'certificate.crt'), 'r', encoding='utf-8') as certificate_file:
certificate = certificate_file.read()
with open(os.path.join(certificate_dir, 'certificate.key'), 'r', encoding='utf-8') as key_file:
private_key = key_file.read()
except OSError:
return None, None
return certificate, private_key
def build_applications_data(worker=None):
entries = []
for app in applications:
for app in get_served_applications(worker):
if app.name == RESERVED_APP_NAME:
continue
entry = {
'id': app.name,
'name': app.display_name or app.name,
@@ -65,7 +104,8 @@ def _build_auth_method_entry(method):
return entry
def build_auth_policies_data():
def build_auth_policies_data(worker=None):
# Policies, methods, groups and users are referenced by name, so every server receives all of them
auth_methods = {}
for method in AuthMethod.objects.all():
auth_methods[method.name] = _build_auth_method_entry(method)
@@ -100,13 +140,9 @@ def build_auth_policies_data():
}
def build_routes_data():
applications = (
Application.objects
.prefetch_related('routes__policy')
)
def build_routes_data(worker=None):
entries = {}
for app in applications:
for app in get_served_applications(worker):
try:
app_policy = ApplicationPolicy.objects.get(application=app)
default_policy = app_policy.default_policy.name
@@ -130,17 +166,164 @@ def build_routes_data():
return {'entries': entries}
def export_caddy_config(output_dir):
os.makedirs(output_dir, exist_ok=True)
def build_tls_data(worker=None):
"""
On the primary server every ACME certificate is issued, including the ones of applications that are only
served by cluster workers (certificate_only), and certificates used by workers are exported. Workers never
issue ACME certificates: they receive the exported certificate (certificate_file) or use the internal CA.
"""
hosts = {}
dns_credentials = {}
served_application_ids = {application.pk for application in get_served_applications(worker)}
file_map = {
application_hosts = ApplicationHost.objects.select_related('dns_credential', 'application').prefetch_related(
'application__workers'
)
for application_host in application_hosts:
application = application_host.application
hostname = application_host.hostname.lower()
is_acme = application_host.certificate_type in ACME_CERTIFICATE_TYPES
host_entry = {
'certificate_type': application_host.certificate_type,
'certificate_fallback': application_host.certificate_fallback,
}
if worker is not None:
if application.pk in served_application_ids:
# Workers issue their own self-signed certificates, so they also follow the renewal requests
if application_host.certificate_type == 'self_signed':
host_entry['certificate_generation'] = application_host.certificate_generation
hosts[hostname] = host_entry
continue
served_by_workers = application.name != RESERVED_APP_NAME and application.served_by_workers
if application.pk not in served_application_ids and not (served_by_workers and is_acme):
continue
host_entry['certificate_generation'] = application_host.certificate_generation
if served_by_workers and is_acme:
host_entry['export_certificate'] = True
if application.pk not in served_application_ids:
host_entry['certificate_only'] = True
dns_credential = application_host.dns_credential
if application_host.certificate_type == 'dns_challenge' and dns_credential:
host_entry['dns_credential'] = dns_credential.name
delegation_target = dns_credential.delegation_target(hostname)
if delegation_target:
host_entry['dns_challenge_override_domain'] = delegation_target
dns_credentials[dns_credential.name] = {
'provider': dns_credential.provider,
'credentials': dns_credential.credentials,
}
hosts[hostname] = host_entry
return {
'hosts': hosts,
'dns_credentials': dns_credentials,
}
CADDY_EXPORT_DIR = '/caddy_json_export/'
EXPORT_FILES = {
'applications.json': build_applications_data,
'auth_policies.json': build_auth_policies_data,
'routes.json': build_routes_data,
'tls.json': build_tls_data,
}
for filename, builder in file_map.items():
filepath = os.path.join(output_dir, filename)
# Cluster workers follow the configuration exported for them, so changes are only published by an export
WORKER_EXPORT_DIR_NAME = 'cluster'
def get_worker_export_dir(output_dir, worker):
return os.path.join(output_dir, WORKER_EXPORT_DIR_NAME, str(worker.uuid))
def _write_export_files(target_dir, worker=None):
os.makedirs(target_dir, exist_ok=True)
for filename, builder in EXPORT_FILES.items():
filepath = os.path.join(target_dir, filename)
with open(filepath, 'w', encoding='utf-8') as output_file:
json.dump(builder(), output_file, indent=2)
json.dump(builder(worker), output_file, indent=2)
output_file.write('\n')
def export_caddy_config(output_dir):
os.makedirs(output_dir, exist_ok=True)
workers = list(Worker.objects.all())
for worker in workers:
_write_export_files(get_worker_export_dir(output_dir, worker), worker)
workers_export_dir = os.path.join(output_dir, WORKER_EXPORT_DIR_NAME)
if os.path.isdir(workers_export_dir):
worker_uuids = {str(worker.uuid) for worker in workers}
for worker_dir_name in os.listdir(workers_export_dir):
if worker_dir_name not in worker_uuids:
shutil.rmtree(os.path.join(workers_export_dir, worker_dir_name), ignore_errors=True)
# The primary server is written last: its files are the ones Caddy and the auth-gateway watch
_write_export_files(output_dir)
def load_exported_files(target_dir):
"""Return {filename: data} from an export directory, or None when it is missing or incomplete."""
exported_files = {}
for filename in EXPORT_FILES:
try:
with open(os.path.join(target_dir, filename), 'r', encoding='utf-8') as exported_file:
exported_files[filename] = json.load(exported_file)
except (OSError, ValueError):
return None
return exported_files
def load_worker_export(worker, output_dir=None):
return load_exported_files(get_worker_export_dir(output_dir or CADDY_EXPORT_DIR, worker))
def add_certificate_files(tls_data):
"""Point the ACME hosts of a worker to the certificates currently exported by the primary server."""
for hostname, host_tls in tls_data.get('hosts', {}).items():
if host_tls.get('certificate_type') not in ACME_CERTIFICATE_TYPES:
continue
certificate, private_key = read_exported_certificate(hostname)
host_tls['certificate_file'] = certificate_file_name(certificate) if certificate and private_key else ''
return tls_data
def _export_differs(target_dir, worker=None):
exported_files = load_exported_files(target_dir)
if exported_files is None:
return True
# Round-trip through JSON so the comparison matches what export_caddy_config writes
for filename, builder in EXPORT_FILES.items():
if json.loads(json.dumps(builder(worker))) != exported_files[filename]:
return True
return False
def has_pending_export(output_dir):
"""Return True when the current configuration differs from the files last exported to output_dir."""
if _export_differs(output_dir):
return True
return any(_export_differs(get_worker_export_dir(output_dir, worker), worker) for worker in Worker.objects.all())
def caddy_export_pending():
return settings.CADDY_ENABLED and has_pending_export(CADDY_EXPORT_DIR)
def apply_caddy_config():
"""Export the configuration read by Caddy, the auth-gateway and the cluster workers."""
export_caddy_config(CADDY_EXPORT_DIR)
if settings.DEBUG:
export_caddy_config(os.path.join(settings.BASE_DIR, 'containers', 'caddy', 'config_files'))
def auto_apply_caddy_config(request):
if not settings.AUTO_APPLY or not settings.CADDY_ENABLED:
return False
apply_caddy_config()
messages.info(request, _('Gateway configuration applied automatically.'))
return True
+78
View File
@@ -0,0 +1,78 @@
import socket
import ssl
import subprocess
from datetime import datetime, timezone
# Caddy shares the network namespace of the WireGuard WebAdmin container
CADDY_TLS_ADDRESS = ('127.0.0.1', 443)
CONNECTION_TIMEOUT = 3
INTERNAL_CA_NAME = 'Caddy Local Authority'
def _parse_not_after(value):
return datetime.strptime(value, '%b %d %H:%M:%S %Y %Z').replace(tzinfo=timezone.utc)
def _issuer_name(issuer_fields):
issuer = dict(field[0] for field in issuer_fields)
return issuer.get('organizationName') or issuer.get('commonName') or ''
def _fetch_certificate(hostname, verify):
if verify:
context = ssl.create_default_context()
else:
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
with socket.create_connection(CADDY_TLS_ADDRESS, timeout=CONNECTION_TIMEOUT) as raw_socket:
with context.wrap_socket(raw_socket, server_hostname=hostname) as tls_socket:
if verify:
return tls_socket.getpeercert()
return tls_socket.getpeercert(binary_form=True)
def _describe_untrusted_certificate(certificate_der):
result = subprocess.run(
['openssl', 'x509', '-inform', 'DER', '-noout', '-issuer', '-enddate', '-nameopt', 'RFC2253'],
input=certificate_der, capture_output=True, timeout=CONNECTION_TIMEOUT,
)
issuer = ''
not_after = None
for line in result.stdout.decode(errors='replace').splitlines():
if line.startswith('issuer='):
issuer_parts = dict(
part.split('=', 1) for part in line[len('issuer='):].split(',') if '=' in part
)
issuer = issuer_parts.get('O') or issuer_parts.get('CN') or ''
if INTERNAL_CA_NAME in line:
issuer = INTERNAL_CA_NAME
elif line.startswith('notAfter='):
not_after = _parse_not_after(line[len('notAfter='):])
return issuer, not_after
def inspect_certificate(hostname):
"""
Return the status of the certificate Caddy serves for a hostname:
'trusted', 'untrusted' (served but not trusted, e.g. internal CA) or 'unavailable'.
"""
try:
certificate = _fetch_certificate(hostname, verify=True)
return {
'status': 'trusted',
'issuer': _issuer_name(certificate.get('issuer', ())),
'not_after': _parse_not_after(certificate['notAfter']),
}
except ssl.SSLCertVerificationError:
pass
except (OSError, ValueError):
return {'status': 'unavailable', 'issuer': '', 'not_after': None}
try:
certificate_der = _fetch_certificate(hostname, verify=False)
issuer, not_after = _describe_untrusted_certificate(certificate_der)
except (OSError, ValueError, subprocess.SubprocessError):
return {'status': 'unavailable', 'issuer': '', 'not_after': None}
return {'status': 'untrusted', 'issuer': issuer, 'not_after': not_after}
+22
View File
@@ -0,0 +1,22 @@
from django.utils.translation import gettext_lazy as _
# Every provider listed here must also be compiled into the Caddy image
# (see containers/caddy/Dockerfile-caddy). Field names must match the
# subdirectives accepted by the provider's Caddy DNS module, and the optional
# pattern should mirror the module's own validation, since an invalid value
# prevents Caddy from loading the configuration.
DNS_PROVIDERS = {
'cloudflare': {
'label': 'Cloudflare',
'fields': [
{
'name': 'api_token',
'label': _('API Token'),
'secret': True,
'pattern': r'^(cf(ut|at)_[A-Za-z0-9_-]{32,256}|[A-Za-z0-9_-]{35,50})$',
},
],
},
}
DNS_PROVIDER_CHOICES = [(provider, provider_data['label']) for provider, provider_data in DNS_PROVIDERS.items()]
+223 -4
View File
@@ -1,29 +1,65 @@
import re
from urllib.parse import urlparse
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, HTML, Div
from django import forms
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from app_gateway.dns_providers import DNS_PROVIDERS
from app_gateway.models import (
Application, ApplicationHost, AccessPolicy, ApplicationPolicy, ApplicationRoute
Application, ApplicationHost, AccessPolicy, ApplicationPolicy, ApplicationRoute, DnsChallengeCredential,
acme_challenge_base,
)
from app_gateway.setup_defaults import is_ip_address
from cluster.models import ClusterSettings, Worker
DOMAIN_PATTERN = re.compile(r'^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$')
class ApplicationForm(forms.ModelForm):
class Meta:
model = Application
fields = ['display_name', 'upstream', 'allow_invalid_cert']
fields = ['display_name', 'upstream', 'allow_invalid_cert', 'serve_on_primary', 'all_workers', 'workers']
labels = {
'display_name': _('Name'),
'upstream': _('Upstream'),
'allow_invalid_cert': _('Allow invalid/self-signed certificate'),
'serve_on_primary': _('Serve on the primary server'),
'all_workers': _('Serve on all cluster workers'),
'workers': _('Cluster workers'),
}
def __init__(self, *args, **kwargs):
cancel_url = kwargs.pop('cancel_url', '#')
super().__init__(*args, **kwargs)
self.fields['display_name'].required = True
self.cluster_enabled = ClusterSettings.cluster_enabled()
cluster_rows = []
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'<hr><h5>{_("Cluster")}</h5><p class="text-muted">{_("Servers that publish this application.")}</p>'),
Div(
Div('serve_on_primary', css_class='col-md-12'),
Div('all_workers', css_class='col-md-12'),
Div('workers', css_class='col-md-12'),
css_class='row'
),
]
else:
for field_name in ('serve_on_primary', 'all_workers', 'workers'):
del self.fields[field_name]
self.helper = FormHelper()
self.helper.layout = Layout(
@@ -36,6 +72,7 @@ class ApplicationForm(forms.ModelForm):
Div('allow_invalid_cert', css_class='col-md-12'),
css_class='row'
),
*cluster_rows,
Div(
Div(
Submit('submit', _('Save'), css_class='btn btn-primary'),
@@ -64,6 +101,24 @@ class ApplicationForm(forms.ModelForm):
self.add_error("upstream", _("Enter a valid upstream URL starting with http:// or https://"))
elif parsed.path not in ("", "/") or parsed.query or parsed.fragment:
self.add_error("upstream", _("Upstream must be a bare host address with no path, query or fragment. Use http://host or http://host:port"))
elif parsed.scheme == "http" and cleaned_data.get("allow_invalid_cert"):
self.add_error("allow_invalid_cert", _("This option is only available for https:// upstreams."))
if self.cluster_enabled:
all_workers = cleaned_data.get('all_workers')
selected_workers = cleaned_data.get('workers')
if all_workers and selected_workers:
self.add_error('workers', _('Leave this empty when the application is served on all cluster workers.'))
if not cleaned_data.get('serve_on_primary') and not all_workers and not selected_workers:
self.add_error(None, _('Select at least one server to publish this application.'))
served_by_workers = all_workers or bool(selected_workers)
if served_by_workers and self.instance.pk:
http_hosts = self.instance.hosts.filter(certificate_type='http_challenge').values_list('hostname', flat=True)
if http_hosts:
self.add_error(None, _(
'Applications served by cluster workers require DNS validation or self-signed certificates. '
'Change the certificate of these hosts first: %(hosts)s'
) % {'hosts': ', '.join(http_hosts)})
return cleaned_data
@@ -71,22 +126,62 @@ class ApplicationForm(forms.ModelForm):
class ApplicationHostForm(forms.ModelForm):
class Meta:
model = ApplicationHost
fields = ['hostname']
fields = ['hostname', 'certificate_type', 'dns_credential', 'certificate_fallback']
labels = {
'hostname': _('Hostname'),
'certificate_type': _('Certificate'),
'dns_credential': _('DNS Credential'),
'certificate_fallback': _('Use a self-signed certificate if the trusted certificate cannot be issued'),
}
def clean(self):
cleaned_data = super().clean()
hostname = (cleaned_data.get('hostname') or '').strip()
if hostname:
certificate_type = cleaned_data.get('certificate_type')
dns_credential = cleaned_data.get('dns_credential')
if hostname and not self.is_reserved:
if any(c in hostname for c in ('{', '}', '\n', '\r', '\x00', ' ')):
self.add_error('hostname', _('Hostname contains invalid characters.'))
webadmin_hostnames = [host.lower() for host in settings.ALLOWED_HOSTS]
if hostname.lower() in webadmin_hostnames:
self.add_error('hostname', _('This hostname is already used by WireGuard WebAdmin.'))
application = self.instance.application if self.instance.pk else self.application
if certificate_type == 'http_challenge' and application and application.served_by_workers:
self.add_error('certificate_type', _(
'This application is served by cluster workers. Use DNS validation or a self-signed certificate.'
))
if hostname and is_ip_address(hostname) and certificate_type != 'self_signed':
self.add_error('certificate_type', _('IP addresses can only use a self-signed certificate.'))
if certificate_type == 'dns_challenge':
if not dns_credential:
self.add_error('dns_credential', _('Select a DNS credential to use the DNS validation.'))
elif hostname and len(dns_credential.delegation_target(hostname) or '') > 253:
self.add_error('dns_credential', _(
'The challenge record of this hostname in the delegation domain exceeds the DNS name limit.'
))
elif dns_credential:
self.add_error('dns_credential', _('A DNS credential can only be used with the DNS validation.'))
# The fallback keeps WireGuard WebAdmin reachable when the ACME certificate cannot be issued
if self.is_reserved or certificate_type == 'self_signed':
cleaned_data['certificate_fallback'] = True
return cleaned_data
def __init__(self, *args, **kwargs):
cancel_url = kwargs.pop('cancel_url', '#')
self.is_reserved = kwargs.pop('is_reserved', False)
self.application = kwargs.pop('application', None)
super().__init__(*args, **kwargs)
self.fields['dns_credential'].required = False
if self.is_reserved:
self.fields['hostname'].disabled = True
self.fields['certificate_fallback'].disabled = True
self.helper = FormHelper()
self.helper.layout = Layout(
@@ -94,6 +189,16 @@ class ApplicationHostForm(forms.ModelForm):
Div('hostname', css_class='col-md-12'),
css_class='row'
),
Div(
Div('certificate_type', css_class='col-md-12'),
Div('dns_credential', css_class='col-md-12'),
Div(HTML('{% include "app_gateway/dns_delegation_alert.html" %}'), css_class='col-md-12'),
css_class='row'
),
Div(
Div('certificate_fallback', css_class='col-md-12'),
css_class='row'
),
Div(
Div(
Submit('submit', _('Save'), css_class='btn btn-primary'),
@@ -309,3 +414,117 @@ class ApplicationRouteForm(forms.ModelForm):
else:
cleaned_data['path_prefix'] = path_prefix
return cleaned_data
class DnsChallengeCredentialForm(forms.ModelForm):
class Meta:
model = DnsChallengeCredential
fields = ['display_name', 'provider', 'delegation_domain']
labels = {
'display_name': _('Name'),
'provider': _('Provider'),
'delegation_domain': _('Delegation domain'),
}
help_texts = {
'delegation_domain': _(
'Optional. Zone managed by this credential that receives the challenge records of other domains, '
'e.g. acme.example.net. Each host then needs a CNAME record pointing to this zone.'
),
}
def __init__(self, *args, **kwargs):
cancel_url = kwargs.pop('cancel_url', '#')
super().__init__(*args, **kwargs)
self.fields['display_name'].required = True
stored_credentials = self.instance.credentials if self.instance and self.instance.pk else {}
provider_rows = []
for provider, provider_data in DNS_PROVIDERS.items():
provider_fields = []
for provider_field in provider_data['fields']:
field_name = self.credential_field_name(provider, provider_field['name'])
stored_value = stored_credentials.get(provider_field['name'], '') if self.instance.provider == provider else ''
if provider_field.get('secret'):
help_text = ''
if stored_value:
help_text = _('Leave blank to keep the current value (ending in %(suffix)s).') % {
'suffix': stored_value[-4:]
}
self.fields[field_name] = forms.CharField(
label=provider_field['label'], required=False, help_text=help_text,
widget=forms.PasswordInput(render_value=False),
)
else:
self.fields[field_name] = forms.CharField(
label=provider_field['label'], required=False, initial=stored_value,
)
provider_fields.append(Div(field_name, css_class='col-md-12'))
provider_rows.append(Div(*provider_fields, css_class=f'row provider-group provider-{provider}'))
self.helper = FormHelper()
self.helper.layout = Layout(
Div(
Div('display_name', css_class='col-xl-6'),
Div('provider', css_class='col-xl-6'),
css_class='row'
),
*provider_rows,
Div(
Div('delegation_domain', css_class='col-md-12'),
css_class='row'
),
Div(
Div(
Submit('submit', _('Save'), css_class='btn btn-primary'),
HTML(f'<a href="{cancel_url}" class="btn btn-secondary">{_("Cancel")}</a>'),
css_class='col-md-12'
),
css_class='row'
)
)
@staticmethod
def credential_field_name(provider, field_name):
return f'{provider}_{field_name}'
def clean_delegation_domain(self):
delegation_domain = (self.cleaned_data.get('delegation_domain') or '').strip().lower().rstrip('.')
if delegation_domain and not DOMAIN_PATTERN.match(delegation_domain):
raise forms.ValidationError(_('Enter a valid domain, e.g. acme.example.net'))
if delegation_domain and self.instance.pk:
too_long = [
host.hostname for host in self.instance.hosts.all()
if len(f'{acme_challenge_base(host.hostname)}.{delegation_domain}') > 253
]
if too_long:
raise forms.ValidationError(_(
'The challenge record of these hosts would exceed the DNS name limit: %(hosts)s'
) % {'hosts': ', '.join(too_long)})
return delegation_domain
def clean(self):
cleaned_data = super().clean()
provider = cleaned_data.get('provider')
if provider not in DNS_PROVIDERS:
return cleaned_data
stored_credentials = {}
if self.instance and self.instance.pk and self.instance.provider == provider:
stored_credentials = self.instance.credentials
credentials = {}
for provider_field in DNS_PROVIDERS[provider]['fields']:
field_name = self.credential_field_name(provider, provider_field['name'])
value = (cleaned_data.get(field_name) or '').strip()
if not value and provider_field.get('secret'):
value = stored_credentials.get(provider_field['name'], '')
if not value:
self.add_error(field_name, _('This field is required.'))
elif any(c in value for c in ('\n', '\r', '\x00')):
self.add_error(field_name, _('This field contains invalid characters.'))
elif provider_field.get('pattern') and not re.match(provider_field['pattern'], value):
self.add_error(field_name, _('The value does not match the expected format for this provider.'))
credentials[provider_field['name']] = value
self.instance.credentials = credentials
return cleaned_data
View File
@@ -0,0 +1,126 @@
import sys
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from app_gateway.caddy_config_export import apply_caddy_config
from app_gateway.models import AccessPolicy, Application, ApplicationPolicy, RESERVED_APP_NAME
from app_gateway.setup_defaults import create_default_entries
class Command(BaseCommand):
help = 'Interactively set the WireGuard WebAdmin application to a public policy, removing auth-gateway authentication'
def handle(self, *args, **options):
if not sys.stdin.isatty():
raise CommandError(
'This command must be run interactively. '
'Use: docker exec -it wireguard-webadmin python manage.py disable_webadmin_gateway_auth'
)
create_default_entries()
public_policy = AccessPolicy.objects.filter(policy_type='public').order_by('created').first()
if not public_policy:
raise CommandError('No public access policy found.')
application = Application.objects.filter(name=RESERVED_APP_NAME).first()
if not application:
raise CommandError(f'Application "{RESERVED_APP_NAME}" not found.')
application_policy = ApplicationPolicy.objects.filter(application=application).select_related('default_policy').first()
current_policy = application_policy.default_policy if application_policy else None
change_default_policy = not current_policy or current_policy.id != public_policy.id
protected_routes = list(
application.routes.exclude(policy__policy_type='public').select_related('policy').order_by('order', 'path_prefix')
)
if not change_default_policy and not protected_routes:
self.stdout.write('WireGuard WebAdmin is already using a public policy. Nothing to do.')
return
self.stdout.write(self.style.WARNING(
'\nWARNING: this command removes the auth-gateway authentication from WireGuard WebAdmin.\n'
'The web interface will be reachable by anyone who can access this host, protected only by the Django login.\n'
'Use it only to recover access, and restore the application policy from the web interface right after.\n'
))
if change_default_policy:
self.stdout.write(f'Default policy: {current_policy} -> {public_policy}')
else:
self.stdout.write(f'Default policy is already public: {public_policy}')
selected_routes = []
if protected_routes:
self.stdout.write('\nProtected routes:')
for index, route in enumerate(protected_routes, start=1):
self.stdout.write(f' [{index}] {route.path_prefix} ({route.policy})')
selected_routes = self.ask_routes(protected_routes)
if not change_default_policy and not selected_routes:
self.stdout.write('No changes selected. Nothing to do.')
return
self.stdout.write('\nThe following changes will be applied:')
if change_default_policy:
self.stdout.write(f' Default policy: {current_policy} -> {public_policy}')
for route in selected_routes:
self.stdout.write(f' Route {route.path_prefix}: {route.policy} -> {public_policy}')
if self.ask('\nType "yes" to continue, or anything else to cancel: ').lower() != 'yes':
self.stdout.write('Operation cancelled. No changes were made.')
return
with transaction.atomic():
if change_default_policy:
ApplicationPolicy.objects.update_or_create(
application=application, defaults={'default_policy': public_policy}
)
for route in selected_routes:
route.policy = public_policy
route.save()
self.stdout.write(self.style.SUCCESS('Changes applied.'))
if settings.CADDY_ENABLED:
self.stdout.write('Exporting Caddy configuration...')
apply_caddy_config()
self.stdout.write(self.style.SUCCESS('Caddy configuration exported.'))
else:
self.stdout.write('Skipping Caddy configuration export (CADDY_ENABLED is not set).')
self.stdout.write(self.style.WARNING(
'Remember to restore the WireGuard WebAdmin application policy from the web interface once access is recovered.'
))
def ask(self, prompt):
try:
return input(prompt).strip()
except (EOFError, KeyboardInterrupt):
raise CommandError('\nOperation cancelled. No changes were made.')
def ask_routes(self, protected_routes):
while True:
answer = self.ask("Routes to set as public (comma separated numbers, 'all', or empty for none): ").lower()
if not answer:
return []
if answer == 'all':
return protected_routes
selected_routes = []
valid_answer = True
for item in answer.split(','):
item = item.strip()
if not item:
continue
if not item.isdigit() or not 1 <= int(item) <= len(protected_routes):
valid_answer = False
break
route = protected_routes[int(item) - 1]
if route not in selected_routes:
selected_routes.append(route)
if valid_answer and selected_routes:
return selected_routes
self.stdout.write(self.style.ERROR(f'Invalid selection: {answer}'))
@@ -0,0 +1,113 @@
import sys
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.db.models import F
from app_gateway.caddy_config_export import apply_caddy_config
from app_gateway.models import Application, ApplicationHost, RESERVED_APP_NAME
from app_gateway.setup_defaults import create_default_entries
CERTIFICATE_OPTIONS = (
('http_challenge', 'HTTP validation (default)'),
('self_signed', 'Self-signed'),
)
class Command(BaseCommand):
help = 'Interactively reset the certificate settings of the WireGuard WebAdmin hosts'
def handle(self, *args, **options):
if not sys.stdin.isatty():
raise CommandError(
'This command must be run interactively. '
'Use: docker exec -it wireguard-webadmin python manage.py reset_webadmin_certificate'
)
create_default_entries()
application = Application.objects.filter(name=RESERVED_APP_NAME).first()
if not application:
raise CommandError(f'Application "{RESERVED_APP_NAME}" not found.')
hosts = list(application.hosts.select_related('dns_credential').order_by('hostname'))
if not hosts:
raise CommandError('WireGuard WebAdmin has no hosts. Check SERVER_ADDRESS and EXTRA_ALLOWED_HOSTS.')
self.stdout.write('\nWireGuard WebAdmin hosts:')
for index, host in enumerate(hosts, start=1):
credential = f', credential: {host.dns_credential}' if host.dns_credential else ''
self.stdout.write(f' [{index}] {host.hostname} ({host.certificate_label}{credential})')
selected_hosts = self.ask_hosts(hosts)
self.stdout.write('\nNew certificate:')
for index, (certificate_type, label) in enumerate(CERTIFICATE_OPTIONS, start=1):
self.stdout.write(f' [{index}] {label}')
certificate_type, certificate_label = self.ask_certificate_type()
self.stdout.write('\nThe following changes will be applied:')
for host in selected_hosts:
self.stdout.write(f' {host.hostname}: {host.certificate_label} -> {certificate_label}')
self.stdout.write(
'The DNS credential is removed from these hosts and a new certificate is issued right away. '
'Until it is issued, the hosts are served with a self-signed certificate.'
)
if self.ask('\nType "yes" to continue, or anything else to cancel: ').lower() != 'yes':
self.stdout.write('Operation cancelled. No changes were made.')
return
with transaction.atomic():
ApplicationHost.objects.filter(pk__in=[host.pk for host in selected_hosts]).update(
certificate_type=certificate_type,
dns_credential=None,
certificate_fallback=True,
certificate_generation=F('certificate_generation') + 1,
)
self.stdout.write(self.style.SUCCESS('Changes applied.'))
if settings.CADDY_ENABLED:
self.stdout.write('Exporting Caddy configuration...')
apply_caddy_config()
self.stdout.write(self.style.SUCCESS('Caddy configuration exported.'))
else:
self.stdout.write('Skipping Caddy configuration export (CADDY_ENABLED is not set).')
def ask(self, prompt):
try:
return input(prompt).strip()
except (EOFError, KeyboardInterrupt):
raise CommandError('\nOperation cancelled. No changes were made.')
def ask_hosts(self, hosts):
while True:
answer = self.ask("Hosts to reset (comma separated numbers, or empty for all): ").lower()
if not answer or answer == 'all':
return hosts
selected_hosts = []
valid_answer = True
for item in answer.split(','):
item = item.strip()
if not item:
continue
if not item.isdigit() or not 1 <= int(item) <= len(hosts):
valid_answer = False
break
host = hosts[int(item) - 1]
if host not in selected_hosts:
selected_hosts.append(host)
if valid_answer and selected_hosts:
return selected_hosts
self.stdout.write(self.style.ERROR(f'Invalid selection: {answer}'))
def ask_certificate_type(self):
while True:
answer = self.ask('Certificate (number, or empty for HTTP validation): ')
if not answer:
return CERTIFICATE_OPTIONS[0]
if answer.isdigit() and 1 <= int(answer) <= len(CERTIFICATE_OPTIONS):
return CERTIFICATE_OPTIONS[int(answer) - 1]
self.stdout.write(self.style.ERROR(f'Invalid selection: {answer}'))
@@ -0,0 +1,44 @@
# Generated by Django 5.2.19 on 2026-11-17 18:30
import uuid
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_gateway', '0008_accesspolicy_display_name_applicationroute_display_name'),
]
operations = [
migrations.CreateModel(
name='DnsChallengeCredential',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.SlugField(max_length=64, unique=True)),
('display_name', models.CharField(blank=True, max_length=128)),
('provider', models.CharField(choices=[('cloudflare', 'Cloudflare')], max_length=32)),
('credentials', models.JSONField(default=dict)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
],
options={
'verbose_name': 'DNS Challenge Credential',
'verbose_name_plural': 'DNS Challenge Credentials',
'ordering': ['name'],
},
),
migrations.AddField(
model_name='applicationhost',
name='certificate_type',
field=models.CharField(choices=[('self_signed', 'Self-signed'), ('http_challenge', 'HTTP challenge'), ('dns_challenge', 'DNS challenge')], default='http_challenge', max_length=16),
),
migrations.AddField(
model_name='applicationhost',
name='dns_credential',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='hosts', to='app_gateway.dnschallengecredential'),
),
]
@@ -0,0 +1,25 @@
import ipaddress
from django.db import migrations
def set_self_signed_for_ip_hosts(apps, schema_editor):
ApplicationHost = apps.get_model('app_gateway', 'ApplicationHost')
for application_host in ApplicationHost.objects.all():
try:
ipaddress.ip_address(application_host.hostname.strip('[]'))
except ValueError:
continue
application_host.certificate_type = 'self_signed'
application_host.save(update_fields=['certificate_type'])
class Migration(migrations.Migration):
dependencies = [
('app_gateway', '0009_dns_challenge_credentials'),
]
operations = [
migrations.RunPython(set_self_signed_for_ip_hosts, migrations.RunPython.noop),
]
@@ -0,0 +1,23 @@
# Generated by Django 5.2.19 on 2026-11-18 20:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_gateway', '0010_set_self_signed_for_ip_hosts'),
]
operations = [
migrations.AddField(
model_name='applicationhost',
name='certificate_fallback',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='applicationhost',
name='certificate_generation',
field=models.PositiveIntegerField(default=0),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 5.2.19 on 2026-11-18 20:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_gateway', '0011_host_certificate_fallback_and_generation'),
]
operations = [
migrations.AlterField(
model_name='applicationhost',
name='certificate_type',
field=models.CharField(choices=[('http_challenge', 'Trusted certificate (HTTP validation)'), ('dns_challenge', 'Trusted certificate (DNS validation)'), ('self_signed', 'Self-signed certificate')], default='http_challenge', max_length=16),
),
]
@@ -0,0 +1,29 @@
# Generated by Django 5.2.19 on 2026-11-19 16:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_gateway', '0012_certificate_type_labels'),
('cluster', '0018_cluster_v2'),
]
operations = [
migrations.AddField(
model_name='application',
name='all_workers',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='application',
name='serve_on_primary',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='application',
name='workers',
field=models.ManyToManyField(blank=True, related_name='applications', to='cluster.worker'),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 5.2.19 on 2026-11-22 14:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_gateway', '0013_application_served_by'),
]
operations = [
migrations.AddField(
model_name='dnschallengecredential',
name='delegation_domain',
field=models.CharField(blank=True, max_length=253),
),
]
+98
View File
@@ -3,16 +3,73 @@ import uuid
from django.db import models
from django.utils.translation import gettext_lazy as _
from app_gateway.dns_providers import DNS_PROVIDER_CHOICES
from cluster.models import ClusterSettings
from gatekeeper.models import GatekeeperGroup, AuthMethod, _unique_slug
RESERVED_APP_NAME = 'wireguard_webadmin'
CERTIFICATE_TYPE_CHOICES = (
('http_challenge', _('Trusted certificate (HTTP validation)')),
('dns_challenge', _('Trusted certificate (DNS validation)')),
('self_signed', _('Self-signed certificate')),
)
ACME_CHALLENGE_LABEL = '_acme-challenge'
def acme_challenge_base(hostname):
"""Name validated by the DNS challenge: a wildcard certificate is validated on its parent domain."""
hostname = hostname.strip().lower().rstrip('.')
return hostname[2:] if hostname.startswith('*.') else hostname
class DnsChallengeCredential(models.Model):
name = models.SlugField(max_length=64, unique=True)
display_name = models.CharField(max_length=128, blank=True)
provider = models.CharField(max_length=32, choices=DNS_PROVIDER_CHOICES)
credentials = models.JSONField(default=dict)
# Zone the credential manages. When set, the challenge record of each host is a CNAME pointing to this zone.
delegation_domain = models.CharField(max_length=253, blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False)
def delegation_target(self, hostname):
"""
Name where the challenge record of the hostname is created, or None without delegation. Hostnames inside
the delegation domain are validated directly, since the credential already manages their zone.
"""
if not self.delegation_domain:
return None
base = acme_challenge_base(hostname)
if base == self.delegation_domain or base.endswith(f'.{self.delegation_domain}'):
return None
return f'{base}.{self.delegation_domain}'
def save(self, *args, **kwargs):
if self.display_name:
self.name = _unique_slug(DnsChallengeCredential, self.display_name, exclude_pk=self.pk)
super().save(*args, **kwargs)
def __str__(self):
return f"{self.display_name or self.name} ({self.get_provider_display()})"
class Meta:
ordering = ['name']
verbose_name = 'DNS Challenge Credential'
verbose_name_plural = 'DNS Challenge Credentials'
class Application(models.Model):
name = models.SlugField(max_length=64, unique=True)
display_name = models.CharField(max_length=128, blank=True)
upstream = models.CharField(max_length=255, help_text=_("Upstream address, e.g.: http://10.188.18.27:3000"))
allow_invalid_cert = models.BooleanField(default=False, help_text=_("Allow invalid or self-signed TLS certificates from the upstream"))
serve_on_primary = models.BooleanField(default=True)
all_workers = models.BooleanField(default=False)
workers = models.ManyToManyField('cluster.Worker', blank=True, related_name='applications')
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
@@ -28,6 +85,19 @@ class Application(models.Model):
def __str__(self):
return self.display_name or self.name
# Without an active cluster every application is served by the primary server only
@property
def served_by_workers(self):
return ClusterSettings.cluster_enabled() and (self.all_workers or self.workers.exists())
def is_served_by(self, worker):
if not ClusterSettings.cluster_enabled():
return worker is None
if worker is None:
# 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:
ordering = ['name']
@@ -35,6 +105,13 @@ class Application(models.Model):
class ApplicationHost(models.Model):
application = models.ForeignKey(Application, on_delete=models.CASCADE, related_name='hosts')
hostname = models.CharField(max_length=255, unique=True)
certificate_type = models.CharField(max_length=16, default='http_challenge', choices=CERTIFICATE_TYPE_CHOICES)
dns_credential = models.ForeignKey(
DnsChallengeCredential, on_delete=models.PROTECT, null=True, blank=True, related_name='hosts'
)
certificate_fallback = models.BooleanField(default=True)
# Incremented to request a new ACME attempt; exported so every Caddy instance applies it
certificate_generation = models.PositiveIntegerField(default=0)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
@@ -43,6 +120,27 @@ class ApplicationHost(models.Model):
def __str__(self):
return self.hostname
@property
def certificate_label(self):
"""Short description of how the certificate is issued, used in host lists."""
if self.certificate_type == 'self_signed':
return _('Self-signed')
if self.certificate_type == 'http_challenge':
return _('HTTP validation')
if self.dns_delegation_record:
return _('DNS validation (delegated)')
return _('DNS validation')
@property
def dns_delegation_record(self):
"""(name, target) of the CNAME required by a delegated DNS challenge, or None."""
if self.certificate_type != 'dns_challenge' or not self.dns_credential:
return None
target = self.dns_credential.delegation_target(self.hostname)
if not target:
return None
return f'{ACME_CHALLENGE_LABEL}.{acme_challenge_base(self.hostname)}', target
class Meta:
ordering = ['hostname']
+57 -10
View File
@@ -1,24 +1,69 @@
import ipaddress
import logging
from django.conf import settings
logger = logging.getLogger(__name__)
INTERNAL_WEBADMIN_HOSTNAME = 'wireguard-webadmin'
def is_ip_address(hostname):
try:
ipaddress.ip_address(hostname.strip('[]'))
except ValueError:
return False
return True
def get_webadmin_hostnames():
# Mirrors the host selection made by containers/caddy/export_wireguard_webadmin_config.py
hostnames = []
for hostname in settings.ALLOWED_HOSTS:
hostname = hostname.strip().lower()
if not hostname or hostname == INTERNAL_WEBADMIN_HOSTNAME or hostname in hostnames:
continue
if is_ip_address(hostname) or hostname == 'localhost' or hostname.endswith('.localhost'):
continue
hostnames.append(hostname)
return hostnames
def sync_webadmin_hosts(application):
from app_gateway.models import ApplicationHost
webadmin_hostnames = get_webadmin_hostnames()
removed_hosts = application.hosts.exclude(hostname__in=webadmin_hostnames)
for application_host in removed_hosts:
logger.info("Removed WireGuard WebAdmin host: %s", application_host.hostname)
removed_hosts.delete()
for hostname in webadmin_hostnames:
existing_host = ApplicationHost.objects.filter(hostname=hostname).select_related('application').first()
if existing_host:
if existing_host.application_id != application.id:
logger.warning(
"Hostname '%s' is used by WireGuard WebAdmin but is also assigned to application '%s'. "
"Remove it from that application to manage its certificate settings.",
hostname, existing_host.application
)
continue
ApplicationHost.objects.create(application=application, hostname=hostname)
logger.info("Added WireGuard WebAdmin host: %s", hostname)
def create_default_entries(**kwargs):
from app_gateway.models import AccessPolicy, Application, ApplicationPolicy, RESERVED_APP_NAME
# Default access policies
public_policy, created = AccessPolicy.objects.get_or_create(
policy_type='public',
defaults={'display_name': 'Public'},
)
if created:
public_policy = AccessPolicy.objects.filter(policy_type='public').order_by('created').first()
if not public_policy:
public_policy = AccessPolicy.objects.create(policy_type='public', display_name='Public')
logger.info("Created default AccessPolicy: Public")
deny_policy, created = AccessPolicy.objects.get_or_create(
policy_type='deny',
defaults={'display_name': 'Deny'},
)
if created:
if not AccessPolicy.objects.filter(policy_type='deny').exists():
AccessPolicy.objects.create(policy_type='deny', display_name='Deny')
logger.info("Created default AccessPolicy: Deny")
# Reserved wireguard_webadmin application
@@ -31,3 +76,5 @@ def create_default_entries(**kwargs):
if not ApplicationPolicy.objects.filter(application=app).exists():
ApplicationPolicy.objects.create(application=app, default_policy=public_policy)
logger.info("Assigned default policy 'Public' to application '%s'", RESERVED_APP_NAME)
sync_webadmin_hosts(app)
+670 -1
View File
@@ -1 +1,670 @@
# Create your tests here.
import contextlib
import hashlib
import importlib.util
import io
import json
import os
import tempfile
from pathlib import Path
from unittest.mock import patch
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.messages import get_messages
from django.test import TestCase, override_settings
from app_gateway.caddy_config_export import build_tls_data, export_caddy_config
from app_gateway.forms import ApplicationForm, ApplicationHostForm, DnsChallengeCredentialForm
from app_gateway.models import (
AccessPolicy, Application, ApplicationHost, ApplicationPolicy, ApplicationRoute, DnsChallengeCredential
)
from app_gateway.setup_defaults import create_default_entries
from cluster.models import ClusterSettings, Worker
from gatekeeper.models import (
AuthMethod, AuthMethodAllowedDomain, AuthMethodAllowedEmail, GatekeeperGroup, GatekeeperIPAddress, GatekeeperUser
)
from user_manager.models import UserAcl
AUTH_GATEWAY_FIXTURES_DIR = Path(settings.BASE_DIR) / 'containers' / 'auth-gateway' / 'tests' / 'fixtures' / 'config_files'
UPDATE_FIXTURES_ENV = 'UPDATE_AUTH_GATEWAY_FIXTURES'
# Argon2 hash of "fixture-password". Kept fixed so the exported files are reproducible.
FIXTURE_PASSWORD_HASH = '$argon2id$v=19$m=65536,t=3,p=4$bEzFGMfGGK4rdHKhmwwMqw$1J+Ss48IEK1Q4Vpy0RaS+FHIZOjhjhE4MK5C5pzDzHg'
FIXTURE_GLOBAL_TOTP_SECRET = 'JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP'
FIXTURE_USER_TOTP_SECRET = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ'
_WEBADMIN_EXPORT_PATH = Path(settings.BASE_DIR) / 'containers' / 'caddy' / 'export_wireguard_webadmin_config.py'
_WEBADMIN_EXPORT_SPEC = importlib.util.spec_from_file_location('caddy_export_wireguard_webadmin_config', _WEBADMIN_EXPORT_PATH)
_WEBADMIN_EXPORT_MODULE = importlib.util.module_from_spec(_WEBADMIN_EXPORT_SPEC)
_WEBADMIN_EXPORT_SPEC.loader.exec_module(_WEBADMIN_EXPORT_MODULE)
_PROCESS_CONFIG_PATH = Path(settings.BASE_DIR) / 'containers' / 'caddy' / 'process_config.py'
_PROCESS_CONFIG_SPEC = importlib.util.spec_from_file_location('caddy_process_config', _PROCESS_CONFIG_PATH)
process_config = importlib.util.module_from_spec(_PROCESS_CONFIG_SPEC)
_PROCESS_CONFIG_SPEC.loader.exec_module(process_config)
def create_auth_gateway_scenario():
local_password = AuthMethod.objects.create(display_name='Local Password', auth_type='local_password')
totp_global = AuthMethod.objects.create(display_name='TOTP Global', auth_type='totp', totp_secret=FIXTURE_GLOBAL_TOTP_SECRET)
ip_allowlist = AuthMethod.objects.create(display_name='IP Allowlist', auth_type='ip_address')
ip_empty = AuthMethod.objects.create(display_name='IP Empty', auth_type='ip_address')
oidc_company = AuthMethod.objects.create(
display_name='OIDC Company', auth_type='oidc', session_expiration_minutes=2880,
oidc_provider='https://idp.example.test', oidc_client_id='fixture-client', oidc_client_secret='fixture-client-secret',
)
for address, prefix_length, action in (
('10.10.0.1', None, 'allow'),
('10.20.0.0', 24, 'allow'),
('10.20.0.12', None, 'deny'),
('10.30.0.15', None, 'allow'),
):
GatekeeperIPAddress.objects.create(auth_method=ip_allowlist, address=address, prefix_length=prefix_length, action=action)
AuthMethodAllowedDomain.objects.create(auth_method=oidc_company, domain='example.test')
AuthMethodAllowedEmail.objects.create(auth_method=oidc_company, email='contractor@partner.example.test')
alice = GatekeeperUser.objects.create(username='alice', email='alice@example.test', password=FIXTURE_PASSWORD_HASH)
bob = GatekeeperUser.objects.create(username='bob', password=FIXTURE_PASSWORD_HASH, totp_secret=FIXTURE_USER_TOTP_SECRET)
staff_group = GatekeeperGroup.objects.create(display_name='Staff')
staff_group.users.add(alice, bob)
public_policy = AccessPolicy.objects.get(policy_type='public')
password_totp_policy = AccessPolicy.objects.create(display_name='Password TOTP', policy_type='protected')
password_totp_policy.groups.add(staff_group)
password_totp_policy.methods.add(local_password, totp_global)
staff_password_policy = AccessPolicy.objects.create(display_name='Staff Password', policy_type='protected')
staff_password_policy.groups.add(staff_group)
staff_password_policy.methods.add(local_password)
totp_only_policy = AccessPolicy.objects.create(display_name='TOTP Only', policy_type='protected')
totp_only_policy.methods.add(totp_global)
trusted_ips_policy = AccessPolicy.objects.create(display_name='Trusted IPs', policy_type='protected')
trusted_ips_policy.methods.add(ip_allowlist)
empty_ip_list_policy = AccessPolicy.objects.create(display_name='Empty IP List', policy_type='protected')
empty_ip_list_policy.methods.add(ip_empty)
oidc_company_policy = AccessPolicy.objects.create(display_name='OIDC Company', policy_type='protected')
oidc_company_policy.methods.add(oidc_company)
dashboard = Application.objects.create(display_name='Dashboard', upstream='http://10.0.0.10:3000')
ApplicationHost.objects.create(application=dashboard, hostname='dashboard.example.test')
ApplicationPolicy.objects.create(application=dashboard, default_policy=staff_password_policy)
ApplicationRoute.objects.create(application=dashboard, display_name='Admin', path_prefix='/admin', policy=password_totp_policy, order=0)
ApplicationRoute.objects.create(application=dashboard, display_name='API', path_prefix='/api', policy=trusted_ips_policy, order=1)
media = Application.objects.create(display_name='Media', upstream='http://10.0.0.11:32400')
ApplicationHost.objects.create(application=media, hostname='media.example.test')
ApplicationHost.objects.create(application=media, hostname='media2.example.test')
ApplicationPolicy.objects.create(application=media, default_policy=public_policy)
hypervisor = Application.objects.create(display_name='Hypervisor', upstream='https://10.0.0.12:8006', allow_invalid_cert=True)
ApplicationHost.objects.create(application=hypervisor, hostname='hypervisor.example.test')
ApplicationPolicy.objects.create(application=hypervisor, default_policy=trusted_ips_policy)
files = Application.objects.create(display_name='Files', upstream='http://10.0.0.13:8080')
ApplicationPolicy.objects.create(application=files, default_policy=totp_only_policy)
Application.objects.create(display_name='Café', upstream='http://10.0.0.14:8000')
sso = Application.objects.create(display_name='SSO', upstream='http://10.0.0.15:8000')
ApplicationHost.objects.create(application=sso, hostname='sso.example.test')
ApplicationPolicy.objects.create(application=sso, default_policy=oidc_company_policy)
def export_auth_gateway_fixtures(output_dir):
export_caddy_config(output_dir)
fixture_environment = {'SERVER_ADDRESS': 'webadmin.example.test', 'EXTRA_ALLOWED_HOSTS': 'webadmin2.example.test,10.0.0.1'}
with patch.dict(os.environ, fixture_environment), contextlib.redirect_stdout(io.StringIO()):
webadmin_config = _WEBADMIN_EXPORT_MODULE.build_config(_WEBADMIN_EXPORT_MODULE.collect_hosts())
_WEBADMIN_EXPORT_MODULE._write_config(os.path.join(output_dir, 'wireguard_webadmin.json'), webadmin_config)
# Same hosts used for wireguard_webadmin.json, so the WireGuard WebAdmin hosts do not depend on the local .env
FIXTURE_ALLOWED_HOSTS = ['wireguard-webadmin', 'webadmin.example.test', 'webadmin2.example.test', '10.0.0.1']
@override_settings(ALLOWED_HOSTS=FIXTURE_ALLOWED_HOSTS)
class AuthGatewayFixturesTests(TestCase):
maxDiff = None
def setUp(self):
create_default_entries()
create_auth_gateway_scenario()
def test_auth_gateway_fixtures_match_exporter(self):
if os.environ.get(UPDATE_FIXTURES_ENV) == '1':
export_auth_gateway_fixtures(AUTH_GATEWAY_FIXTURES_DIR)
return
with tempfile.TemporaryDirectory() as output_dir:
export_auth_gateway_fixtures(output_dir)
generated_files = sorted(path.name for path in Path(output_dir).glob('*.json'))
fixture_files = sorted(path.name for path in AUTH_GATEWAY_FIXTURES_DIR.glob('*.json'))
self.assertEqual(generated_files, fixture_files)
for filename in generated_files:
generated_data = json.loads((Path(output_dir) / filename).read_text(encoding='utf-8'))
fixture_data = json.loads((AUTH_GATEWAY_FIXTURES_DIR / filename).read_text(encoding='utf-8'))
self.assertEqual(
generated_data, fixture_data,
f"{filename} is out of date. Regenerate it with: "
f"{UPDATE_FIXTURES_ENV}=1 python manage.py test app_gateway"
)
CLOUDFLARE_TOKEN = 'cfut_' + 'a' * 40
def caddy_app(app_id, hosts):
return {'id': app_id, 'hosts': hosts, 'upstream': 'http://10.0.0.10:8080'}
def site_block(caddyfile, host):
"""Return the lines of the site block that starts with the given host."""
lines = caddyfile.splitlines()
start = next(index for index, line in enumerate(lines) if line.startswith(host) and line.endswith('{'))
end = next(index for index in range(start + 1, len(lines)) if lines[index] == '}')
return lines[start:end + 1]
class CaddyfileTlsTests(TestCase):
tls_data = {
'hosts': {
'http.example.test': {'certificate_type': 'http_challenge'},
'strict.example.test': {'certificate_type': 'http_challenge', 'certificate_fallback': False},
'dns.example.test': {'certificate_type': 'dns_challenge', 'dns_credential': 'cloudflare'},
'internal.example.test': {'certificate_type': 'self_signed'},
'worker-only.example.test': {'certificate_type': 'dns_challenge', 'dns_credential': 'cloudflare',
'certificate_only': True, 'export_certificate': True},
},
'dns_credentials': {'cloudflare': {'provider': 'cloudflare', 'credentials': {'api_token': CLOUDFLARE_TOKEN}}},
}
def build(self, apps, tls_data=None):
return process_config.build_caddyfile(apps, None, None, tls_data or self.tls_data)
def test_hosts_are_grouped_by_certificate_settings(self):
caddyfile = self.build([caddy_app('app', [
'http.example.test', 'strict.example.test', 'dns.example.test', 'internal.example.test', 'unknown.example.test'
])])
self.assertEqual(
site_block(caddyfile, 'http.example.test')[:5],
['http.example.test, unknown.example.test {', ' tls {', ' issuer acme', ' issuer internal', ' }'],
)
self.assertEqual(site_block(caddyfile, 'strict.example.test')[:4], ['strict.example.test {', ' tls {', ' issuer acme', ' }'])
self.assertEqual(site_block(caddyfile, 'internal.example.test')[1], ' tls internal')
dns_block = '\n'.join(site_block(caddyfile, 'dns.example.test'))
self.assertIn(f'api_token "{CLOUDFLARE_TOKEN}"', dns_block)
self.assertIn('propagation_delay 30s', dns_block)
self.assertIn('propagation_timeout -1', dns_block)
self.assertIn('issuer internal', dns_block)
def test_dns_challenge_can_be_disabled_after_invalid_configuration(self):
with patch.object(process_config, 'DISABLE_DNS_CHALLENGE', True):
caddyfile = self.build([caddy_app('app', ['dns.example.test'])])
self.assertNotIn('dns cloudflare', caddyfile)
self.assertIn('issuer acme', '\n'.join(site_block(caddyfile, 'dns.example.test')))
def test_primary_keeps_certificates_of_worker_only_hosts(self):
caddyfile = self.build([caddy_app('app', ['http.example.test'])])
worker_only_block = site_block(caddyfile, 'worker-only.example.test')
self.assertIn(' respond 404', worker_only_block)
self.assertIn(' dns cloudflare {', worker_only_block)
def test_cluster_node_never_requests_acme_certificates(self):
node_tls = {'hosts': {
'ready.example.test': {'certificate_type': 'dns_challenge', 'certificate_file': 'a' * 64},
'waiting.example.test': {'certificate_type': 'dns_challenge', 'certificate_file': ''},
'strict.example.test': {'certificate_type': 'dns_challenge', 'certificate_fallback': False, 'certificate_file': ''},
'internal.example.test': {'certificate_type': 'self_signed'},
}, 'dns_credentials': {}}
apps = [caddy_app('app', list(node_tls['hosts']))]
with patch.object(process_config, 'CLUSTER_NODE', True), \
patch.object(process_config, 'NODE_CERTIFICATES_DIR', '/caddy_certificates'):
caddyfile = self.build(apps, node_tls)
self.assertNotIn('issuer acme', caddyfile)
self.assertNotIn('strict.example.test', caddyfile)
certificate_path = '/caddy_certificates/' + 'a' * 64
self.assertEqual(site_block(caddyfile, 'ready.example.test')[1], f' tls {certificate_path}.crt {certificate_path}.key')
self.assertEqual(site_block(caddyfile, 'waiting.example.test')[0], 'waiting.example.test, internal.example.test {')
self.assertEqual(site_block(caddyfile, 'waiting.example.test')[1], ' tls internal')
class CaddyTlsStateTests(TestCase):
"""Fallback certificates are removed and Caddy is restarted only when the certificate settings change."""
def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory()
self.addCleanup(self.temp_dir.cleanup)
self.certificates_dir = os.path.join(self.temp_dir.name, 'certificates')
self.json_dir = os.path.join(self.temp_dir.name, 'json')
self.export_dir = os.path.join(self.temp_dir.name, 'export')
for directory in (self.certificates_dir, self.json_dir, self.export_dir):
os.makedirs(directory)
for attribute, value in (
('CERTIFICATES_DIR', self.certificates_dir),
('TLS_STATE_PATH', os.path.join(self.temp_dir.name, 'tls_state.json')),
('TLS_STATE_PENDING_PATH', os.path.join(self.temp_dir.name, 'tls_state_pending.json')),
('JSON_DIR', self.json_dir),
('CERTIFICATE_EXPORT_DIR', self.export_dir),
):
patcher = patch.object(process_config, attribute, value)
patcher.start()
self.addCleanup(patcher.stop)
def store_certificate(self, issuer_dir_name, host, content='certificate'):
host_dir = os.path.join(self.certificates_dir, issuer_dir_name, host)
os.makedirs(host_dir, exist_ok=True)
for extension in ('crt', 'key'):
with open(os.path.join(host_dir, f'{host}.{extension}'), 'w', encoding='utf-8') as certificate_file:
certificate_file.write(f'{content}-{extension}')
return host_dir
def apply(self, host_tls):
apps = [caddy_app('app', ['app.example.test'])]
tls_data = {'hosts': {'app.example.test': host_tls}, 'dns_credentials': {}}
process_config._write_json(process_config.TLS_STATE_PENDING_PATH, process_config.build_tls_state(apps, tls_data))
output = io.StringIO()
with contextlib.redirect_stdout(output), contextlib.redirect_stderr(io.StringIO()):
process_config.sync_tls_state()
return output.getvalue().strip() == 'restart'
def test_first_run_never_restarts(self):
fallback_dir = self.store_certificate('local', 'app.example.test')
self.assertFalse(self.apply({'certificate_type': 'http_challenge'}))
self.assertTrue(os.path.isdir(fallback_dir))
def test_retry_removes_fallback_certificate(self):
self.apply({'certificate_type': 'http_challenge'})
fallback_dir = self.store_certificate('local', 'app.example.test')
self.assertTrue(self.apply({'certificate_type': 'http_challenge', 'certificate_generation': 1}))
self.assertFalse(os.path.isdir(fallback_dir))
def test_retry_keeps_valid_acme_certificate_without_restart(self):
self.apply({'certificate_type': 'http_challenge'})
acme_dir = self.store_certificate('acme-v02.api.letsencrypt.org-directory', 'app.example.test')
self.assertFalse(self.apply({'certificate_type': 'http_challenge', 'certificate_generation': 1}))
self.assertTrue(os.path.isdir(acme_dir))
def test_switching_to_self_signed_restarts_when_acme_certificate_is_cached(self):
self.apply({'certificate_type': 'http_challenge'})
self.store_certificate('acme-v02.api.letsencrypt.org-directory', 'app.example.test')
self.assertTrue(self.apply({'certificate_type': 'self_signed'}))
def test_unchanged_settings_do_not_restart(self):
self.apply({'certificate_type': 'http_challenge'})
self.store_certificate('local', 'app.example.test')
self.assertFalse(self.apply({'certificate_type': 'http_challenge'}))
def test_readded_host_with_leftover_fallback_is_retried(self):
self.apply({'certificate_type': 'http_challenge'})
fallback_dir = self.store_certificate('local', 'other.example.test')
apps = [caddy_app('app', ['app.example.test', 'other.example.test'])]
tls_data = {'hosts': {'app.example.test': {'certificate_type': 'http_challenge'},
'other.example.test': {'certificate_type': 'dns_challenge', 'dns_credential': 'cloudflare'}},
'dns_credentials': {'cloudflare': {'provider': 'cloudflare', 'credentials': {'api_token': CLOUDFLARE_TOKEN}}}}
process_config._write_json(process_config.TLS_STATE_PENDING_PATH, process_config.build_tls_state(apps, tls_data))
output = io.StringIO()
with contextlib.redirect_stdout(output), contextlib.redirect_stderr(io.StringIO()):
process_config.sync_tls_state()
self.assertEqual(output.getvalue().strip(), 'restart')
self.assertFalse(os.path.isdir(fallback_dir))
def test_new_host_without_cached_certificate_does_not_restart(self):
self.apply({'certificate_type': 'http_challenge'})
apps = [caddy_app('app', ['app.example.test', 'new.example.test'])]
tls_data = {'hosts': {'app.example.test': {'certificate_type': 'http_challenge'},
'new.example.test': {'certificate_type': 'http_challenge'}}, 'dns_credentials': {}}
process_config._write_json(process_config.TLS_STATE_PENDING_PATH, process_config.build_tls_state(apps, tls_data))
output = io.StringIO()
with contextlib.redirect_stdout(output), contextlib.redirect_stderr(io.StringIO()):
process_config.sync_tls_state()
self.assertEqual(output.getvalue().strip(), '')
def test_cluster_node_restarts_when_certificate_changes(self):
with patch.object(process_config, 'CLUSTER_NODE', True):
self.apply({'certificate_type': 'dns_challenge', 'certificate_file': ''})
fallback_dir = self.store_certificate('local', 'app.example.test')
self.assertTrue(self.apply({'certificate_type': 'dns_challenge', 'certificate_file': 'a' * 64}))
self.assertFalse(os.path.isdir(fallback_dir))
self.assertTrue(self.apply({'certificate_type': 'dns_challenge', 'certificate_file': 'b' * 64}))
def test_self_signed_renewal_issues_a_new_certificate(self):
self.apply({'certificate_type': 'self_signed'})
internal_dir = self.store_certificate('local', 'app.example.test')
self.assertFalse(self.apply({'certificate_type': 'self_signed'}))
self.assertTrue(os.path.isdir(internal_dir))
self.assertTrue(self.apply({'certificate_type': 'self_signed', 'certificate_generation': 1}))
self.assertFalse(os.path.isdir(internal_dir))
def test_switching_to_self_signed_keeps_the_internal_certificate(self):
self.apply({'certificate_type': 'http_challenge'})
internal_dir = self.store_certificate('local', 'app.example.test')
self.assertFalse(self.apply({'certificate_type': 'self_signed', 'certificate_generation': 1}))
self.assertTrue(os.path.isdir(internal_dir))
def test_cluster_node_renews_its_self_signed_certificate(self):
with patch.object(process_config, 'CLUSTER_NODE', True):
self.apply({'certificate_type': 'self_signed'})
internal_dir = self.store_certificate('local', 'app.example.test')
self.assertTrue(self.apply({'certificate_type': 'self_signed', 'certificate_generation': 1}))
self.assertFalse(os.path.isdir(internal_dir))
def test_only_acme_certificates_are_exported(self):
tls_data = {'hosts': {
'exported.example.test': {'certificate_type': 'dns_challenge', 'export_certificate': True},
'fallback.example.test': {'certificate_type': 'dns_challenge', 'export_certificate': True},
'local.example.test': {'certificate_type': 'dns_challenge'},
}}
with open(os.path.join(self.json_dir, 'tls.json'), 'w', encoding='utf-8') as tls_file:
json.dump(tls_data, tls_file)
self.store_certificate('acme-v02.api.letsencrypt.org-directory', 'exported.example.test', 'acme')
self.store_certificate('acme-v02.api.letsencrypt.org-directory', 'local.example.test', 'acme')
self.store_certificate('local', 'fallback.example.test', 'internal')
os.makedirs(os.path.join(self.export_dir, 'removed.example.test'))
with contextlib.redirect_stdout(io.StringIO()):
process_config.export_certificates()
self.assertEqual(sorted(os.listdir(self.export_dir)), ['exported.example.test'])
with open(os.path.join(self.export_dir, 'exported.example.test', 'certificate.crt'), encoding='utf-8') as certificate_file:
self.assertEqual(certificate_file.read(), 'acme-crt')
@override_settings(ALLOWED_HOSTS=FIXTURE_ALLOWED_HOSTS)
class ClusterApplicationFormTests(TestCase):
def setUp(self):
ClusterSettings.objects.update_or_create(name='cluster_settings', defaults={'enabled': True})
self.worker = Worker.objects.create(name='node-a')
self.application = Application.objects.create(display_name='Wiki', upstream='http://10.0.0.30:8080')
self.credential = DnsChallengeCredential.objects.create(
display_name='Cloudflare', provider='cloudflare', credentials={'api_token': CLOUDFLARE_TOKEN}
)
def test_application_with_http_validation_hosts_cannot_be_served_by_workers(self):
ApplicationHost.objects.create(application=self.application, hostname='wiki.example.test')
form = ApplicationForm(data={
'display_name': 'Wiki', 'upstream': 'http://10.0.0.30:8080', 'serve_on_primary': 'on',
'workers': [self.worker.pk],
}, instance=self.application)
self.assertFalse(form.is_valid())
self.assertIn('wiki.example.test', str(form.errors))
def test_all_workers_and_specific_workers_are_exclusive(self):
form = ApplicationForm(data={
'display_name': 'Wiki', 'upstream': 'http://10.0.0.30:8080', 'serve_on_primary': 'on',
'all_workers': 'on', 'workers': [self.worker.pk],
}, instance=self.application)
self.assertIn('workers', form.errors)
def test_application_must_be_published_somewhere(self):
form = ApplicationForm(data={'display_name': 'Wiki', 'upstream': 'http://10.0.0.30:8080'}, instance=self.application)
self.assertFalse(form.is_valid())
self.assertIn('__all__', form.errors)
def test_without_cluster_everything_is_served_by_the_primary(self):
self.application.serve_on_primary = False
self.application.save()
self.application.workers.add(self.worker)
ClusterSettings.objects.filter(name='cluster_settings').update(enabled=False)
self.assertTrue(self.application.is_served_by(None))
self.assertFalse(self.application.is_served_by(self.worker))
self.assertFalse(self.application.served_by_workers)
form = ApplicationForm(data={'display_name': 'Wiki', 'upstream': 'http://10.0.0.30:8080'}, instance=self.application)
self.assertTrue(form.is_valid(), form.errors)
self.assertNotIn('workers', form.fields)
def test_host_of_application_served_by_workers_requires_dns_or_self_signed(self):
self.application.workers.add(self.worker)
form = ApplicationHostForm(
data={'hostname': 'wiki.example.test', 'certificate_type': 'http_challenge', 'certificate_fallback': 'on'},
application=self.application,
)
self.assertIn('certificate_type', form.errors)
form = ApplicationHostForm(data={
'hostname': 'wiki.example.test', 'certificate_type': 'dns_challenge',
'dns_credential': self.credential.pk, 'certificate_fallback': 'on',
}, application=self.application)
self.assertTrue(form.is_valid(), form.errors)
@override_settings(ALLOWED_HOSTS=FIXTURE_ALLOWED_HOSTS + ['testserver'], CADDY_ENABLED=True, DEBUG=False)
class GatewayAutoApplyTests(TestCase):
def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory()
self.addCleanup(self.temp_dir.cleanup)
patcher = patch('app_gateway.caddy_config_export.CADDY_EXPORT_DIR', self.temp_dir.name)
patcher.start()
self.addCleanup(patcher.stop)
user = User.objects.create_user(username='gateway-admin', password='unused-test-password')
UserAcl.objects.create(user=user, user_level=50)
self.client.force_login(user)
def save_application(self):
return self.client.post('/app_gateway/application/manage/', {
'display_name': 'Auto Apply', 'upstream': 'http://10.0.0.40:8080',
})
@override_settings(AUTO_APPLY=True)
def test_saving_applies_configuration(self):
self.save_application()
with open(os.path.join(self.temp_dir.name, 'applications.json'), encoding='utf-8') as applications_file:
self.assertIn('auto-apply', [entry['id'] for entry in json.load(applications_file)['entries']])
@override_settings(AUTO_APPLY=False)
def test_disabled_auto_apply_keeps_changes_pending(self):
self.save_application()
self.assertFalse(os.path.exists(os.path.join(self.temp_dir.name, 'applications.json')))
DELEGATION_DOMAIN = 'acme.example.net'
# Long enough for its challenge record in the delegation domain to exceed the 253 characters of a DNS name
LONG_HOSTNAME = '.'.join(['a' * 63, 'b' * 63, 'c' * 63, 'd' * 45, 'test'])
class DnsDelegationTestMixin:
def setUp(self):
super().setUp()
self.application = Application.objects.create(display_name='Wiki', upstream='http://10.0.0.30:8080')
self.credential = DnsChallengeCredential.objects.create(
display_name='Delegated', provider='cloudflare', credentials={'api_token': CLOUDFLARE_TOKEN},
delegation_domain=DELEGATION_DOMAIN,
)
def add_host(self, hostname, certificate_type='dns_challenge', credential=None):
return ApplicationHost.objects.create(
application=self.application, hostname=hostname, certificate_type=certificate_type,
dns_credential=(credential or self.credential) if certificate_type == 'dns_challenge' else None,
)
class DnsDelegationModelTests(DnsDelegationTestMixin, TestCase):
def test_challenge_record_is_the_hostname_inside_the_delegation_domain(self):
self.assertEqual(self.credential.delegation_target('App.Example.com.'), 'app.example.com.acme.example.net')
self.assertEqual(self.credential.delegation_target('*.example.com'), 'example.com.acme.example.net')
def test_hostnames_inside_the_delegation_domain_are_validated_directly(self):
self.assertIsNone(self.credential.delegation_target('acme.example.net'))
self.assertIsNone(self.credential.delegation_target('app.acme.example.net'))
self.assertEqual(self.credential.delegation_target('app.example.net'), 'app.example.net.acme.example.net')
def test_credential_without_delegation_domain_is_not_delegated(self):
self.credential.delegation_domain = ''
self.assertIsNone(self.credential.delegation_target('app.example.com'))
def test_host_record_and_certificate_label(self):
delegated = self.add_host('app.example.com')
self.assertEqual(
delegated.dns_delegation_record, ('_acme-challenge.app.example.com', 'app.example.com.acme.example.net')
)
self.assertEqual(delegated.certificate_label, 'DNS validation (delegated)')
direct = self.add_host('app.acme.example.net')
self.assertIsNone(direct.dns_delegation_record)
self.assertEqual(direct.certificate_label, 'DNS validation')
http_host = self.add_host('http.example.com', certificate_type='http_challenge')
self.assertIsNone(http_host.dns_delegation_record)
self.assertEqual(http_host.certificate_label, 'HTTP validation')
class DnsDelegationExportTests(DnsDelegationTestMixin, TestCase):
def test_only_delegated_hosts_export_the_override_domain(self):
self.add_host('app.example.com')
self.add_host('app.acme.example.net')
hosts = build_tls_data()['hosts']
self.assertEqual(hosts['app.example.com']['dns_challenge_override_domain'], 'app.example.com.acme.example.net')
self.assertNotIn('dns_challenge_override_domain', hosts['app.acme.example.net'])
class DnsDelegationCaddyfileTests(TestCase):
credential = {'provider': 'cloudflare', 'credentials': {'api_token': CLOUDFLARE_TOKEN}}
def tls_data(self, overrides):
hosts = {}
for host, override_domain in overrides.items():
hosts[host] = {'certificate_type': 'dns_challenge', 'dns_credential': 'cloudflare'}
if override_domain is not None:
hosts[host]['dns_challenge_override_domain'] = override_domain
return {'hosts': hosts, 'dns_credentials': {'cloudflare': self.credential}}
def build(self, overrides):
apps = [caddy_app('app', list(overrides))]
return process_config.build_caddyfile(apps, None, None, self.tls_data(overrides))
def test_each_delegated_host_gets_its_own_override_domain(self):
caddyfile = self.build({
'a.example.com': 'a.example.com.acme.example.net',
'b.example.com': 'b.example.com.acme.example.net',
'c.example.com': None,
'd.example.com': None,
})
a_block = site_block(caddyfile, 'a.example.com')
self.assertEqual(a_block[0], 'a.example.com {')
self.assertIn(' dns_challenge_override_domain a.example.com.acme.example.net', a_block)
self.assertIn(' dns_challenge_override_domain b.example.com.acme.example.net', site_block(caddyfile, 'b.example.com'))
direct_block = site_block(caddyfile, 'c.example.com')
self.assertEqual(direct_block[0], 'c.example.com, d.example.com {')
self.assertNotIn('dns_challenge_override_domain', '\n'.join(direct_block))
def test_invalid_override_domain_is_not_written(self):
caddyfile = self.build({'a.example.com': 'bad"} name', 'b.example.com': None})
self.assertNotIn('dns_challenge_override_domain', caddyfile)
self.assertEqual(site_block(caddyfile, 'a.example.com')[0], 'a.example.com, b.example.com {')
def test_tls_state_of_hosts_without_delegation_is_unchanged(self):
apps = [caddy_app('app', ['a.example.com', 'b.example.com'])]
tls_state = process_config.build_tls_state(
apps, self.tls_data({'a.example.com': None, 'b.example.com': 'b.example.com.acme.example.net'})
)
credential_hash = hashlib.sha256(json.dumps(self.credential, sort_keys=True).encode()).hexdigest()
self.assertEqual(tls_state['a.example.com'][2], credential_hash)
self.assertNotEqual(tls_state['b.example.com'][2], credential_hash)
class DnsDelegationFormTests(DnsDelegationTestMixin, TestCase):
def credential_form(self, delegation_domain, instance=None):
return DnsChallengeCredentialForm(data={
'display_name': 'Delegated', 'provider': 'cloudflare', 'delegation_domain': delegation_domain,
}, instance=instance or self.credential)
def test_delegation_domain_is_normalized(self):
form = self.credential_form('Acme.Example.NET.')
self.assertTrue(form.is_valid(), form.errors)
self.assertEqual(form.cleaned_data['delegation_domain'], 'acme.example.net')
def test_invalid_delegation_domain_is_rejected(self):
for value in ('bad domain', 'nodot', '-x.example.net', 'x.example.net/path'):
self.assertIn('delegation_domain', self.credential_form(value).errors, value)
def test_delegation_domain_too_long_for_existing_hosts_is_rejected(self):
self.credential.delegation_domain = ''
self.credential.save()
self.add_host(LONG_HOSTNAME)
self.assertIn(LONG_HOSTNAME, str(self.credential_form(DELEGATION_DOMAIN).errors['delegation_domain']))
def test_host_whose_challenge_record_is_too_long_is_rejected(self):
form = ApplicationHostForm(data={
'hostname': LONG_HOSTNAME, 'certificate_type': 'dns_challenge', 'dns_credential': self.credential.pk,
'certificate_fallback': 'on',
}, application=self.application)
self.assertIn('dns_credential', form.errors)
@override_settings(ALLOWED_HOSTS=FIXTURE_ALLOWED_HOSTS + ['testserver'], CADDY_ENABLED=True, AUTO_APPLY=False)
class DnsDelegationViewTests(DnsDelegationTestMixin, TestCase):
def setUp(self):
super().setUp()
user = User.objects.create_user(username='gateway-admin', password='unused-test-password')
UserAcl.objects.create(user=user, user_level=50)
self.client.force_login(user)
def test_host_form_knows_the_delegated_credentials_and_current_record(self):
DnsChallengeCredential.objects.create(
display_name='Direct', provider='cloudflare', credentials={'api_token': CLOUDFLARE_TOKEN}
)
host = self.add_host('app.example.com')
response = self.client.get(f'/app_gateway/host/manage/?uuid={host.uuid}')
self.assertEqual(response.context['delegation_domains'], {str(self.credential.pk): DELEGATION_DOMAIN})
self.assertEqual(
response.context['initial_delegation_record'],
'_acme-challenge.app.example.com app.example.com.acme.example.net',
)
def test_changing_the_delegation_domain_warns_about_existing_hosts(self):
self.add_host('app.example.com')
response = self.client.post(f'/app_gateway/dns_credential/manage/?uuid={self.credential.uuid}', {
'display_name': 'Delegated', 'provider': 'cloudflare', 'delegation_domain': 'other.example.net',
})
self.credential.refresh_from_db()
self.assertEqual(self.credential.delegation_domain, 'other.example.net')
self.assertEqual(self.credential.credentials, {'api_token': CLOUDFLARE_TOKEN})
warnings = [message.message for message in get_messages(response.wsgi_request) if message.level_tag == 'warning']
self.assertEqual(len(warnings), 1)
self.assertIn('1 hosts', warnings[0])
@override_settings(ALLOWED_HOSTS=FIXTURE_ALLOWED_HOSTS + ['testserver'], CADDY_ENABLED=True, AUTO_APPLY=False)
class SelfSignedRenewalTests(TestCase):
def setUp(self):
temp_dir = tempfile.TemporaryDirectory()
self.addCleanup(temp_dir.cleanup)
patcher = patch('app_gateway.caddy_config_export.CADDY_EXPORT_DIR', temp_dir.name)
patcher.start()
self.addCleanup(patcher.stop)
ClusterSettings.objects.update_or_create(name='cluster_settings', defaults={'enabled': True})
self.worker = Worker.objects.create(name='node-a')
self.application = Application.objects.create(
display_name='Wiki', upstream='http://10.0.0.30:8080', all_workers=True
)
self.credential = DnsChallengeCredential.objects.create(
display_name='Cloudflare', provider='cloudflare', credentials={'api_token': CLOUDFLARE_TOKEN}
)
self.self_signed = ApplicationHost.objects.create(
application=self.application, hostname='internal.example.test', certificate_type='self_signed',
certificate_generation=3,
)
ApplicationHost.objects.create(
application=self.application, hostname='dns.example.test', certificate_type='dns_challenge',
dns_credential=self.credential, certificate_generation=5,
)
user = User.objects.create_user(username='gateway-admin', password='unused-test-password')
UserAcl.objects.create(user=user, user_level=50)
self.client.force_login(user)
def test_workers_follow_renewals_of_self_signed_certificates_only(self):
hosts = build_tls_data(self.worker)['hosts']
self.assertEqual(hosts['internal.example.test']['certificate_generation'], 3)
self.assertNotIn('certificate_generation', hosts['dns.example.test'])
def test_retry_requests_a_new_self_signed_certificate(self):
response = self.client.post(f'/app_gateway/host/retry_certificate/?uuid={self.self_signed.uuid}')
self.self_signed.refresh_from_db()
self.assertEqual(self.self_signed.certificate_generation, 4)
success = [message.message for message in get_messages(response.wsgi_request) if message.level_tag == 'success']
self.assertEqual(len(success), 1)
self.assertIn('self-signed', success[0])
+6
View File
@@ -10,10 +10,12 @@ urlpatterns = [
path('application/manage/', views.view_manage_application, name='manage_application'),
path('application/delete/', views.view_delete_application, name='delete_application'),
path('application/view/', views.view_application_details, name='view_application'),
path('application/certificate_status/', views.view_application_certificate_status, name='application_certificate_status'),
# Application Hosts
path('host/manage/', views.view_manage_application_host, name='manage_application_host'),
path('host/delete/', views.view_delete_application_host, name='delete_application_host'),
path('host/retry_certificate/', views.view_retry_application_host_certificate, name='retry_application_host_certificate'),
# Access Policies
path('policy/select-type/', views.view_select_policy_type, name='select_policy_type'),
@@ -28,6 +30,10 @@ urlpatterns = [
path('route/manage/', views.view_manage_application_route, name='manage_application_route'),
path('route/delete/', views.view_delete_application_route, name='delete_application_route'),
# DNS Challenge Credentials
path('dns_credential/manage/', views.view_manage_dns_credential, name='manage_dns_credential'),
path('dns_credential/delete/', views.view_delete_dns_credential, name='delete_dns_credential'),
# Config Export
path('export/caddy/', views.view_export_caddy_config, name='export_caddy_config'),
]
+258 -26
View File
@@ -1,24 +1,35 @@
import ipaddress
import os
from datetime import timedelta
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db.models import ProtectedError
from django.db.models import F, ProtectedError
from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from django.utils.formats import date_format
from django.utils.http import url_has_allowed_host_and_scheme
from django.utils.timezone import localtime
from django.utils.translation import gettext as _
from django.views.decorators.http import require_POST
from app_gateway.caddy_config_export import export_caddy_config
from app_gateway.caddy_config_export import (
ACME_CERTIFICATE_TYPES, CADDY_EXPORT_DIR, apply_caddy_config, auto_apply_caddy_config, caddy_export_pending,
load_exported_files, load_worker_export
)
from app_gateway.certificate_status import inspect_certificate
from app_gateway.forms import (
ApplicationForm, ApplicationHostForm, AccessPolicyForm,
ApplicationPolicyForm, ApplicationRouteForm
ApplicationPolicyForm, ApplicationRouteForm, DnsChallengeCredentialForm
)
from app_gateway.models import (
Application, ApplicationHost, AccessPolicy, ApplicationPolicy, ApplicationRoute, RESERVED_APP_NAME
Application, ApplicationHost, AccessPolicy, ApplicationPolicy, ApplicationRoute, DnsChallengeCredential,
RESERVED_APP_NAME
)
from app_gateway.setup_defaults import create_default_entries
from cluster.models import ClusterSettings, Worker
from user_manager.models import UserAcl
@@ -29,9 +40,10 @@ def view_app_gateway_list(request):
create_default_entries()
applications = Application.objects.all().order_by('name')
hosts = ApplicationHost.objects.all().order_by('hostname')
hosts = ApplicationHost.objects.select_related('application', 'dns_credential').order_by('hostname')
access_policies = AccessPolicy.objects.all().order_by('name')
app_policies = ApplicationPolicy.objects.all().order_by('application__name')
dns_credentials = DnsChallengeCredential.objects.all().order_by('name')
tab = request.GET.get('tab', 'applications')
@@ -40,8 +52,10 @@ def view_app_gateway_list(request):
'hosts': hosts,
'access_policies': access_policies,
'app_policies': app_policies,
'dns_credentials': dns_credentials,
'active_tab': tab,
'caddy_enabled': settings.CADDY_ENABLED,
'pending_export': caddy_export_pending(),
}
return render(request, 'app_gateway/app_gateway_list.html', context)
@@ -54,29 +68,113 @@ def view_application_details(request):
application_uuid = request.GET.get('uuid')
application = get_object_or_404(Application, uuid=application_uuid)
hosts = application.hosts.all().order_by('hostname')
hosts = application.hosts.select_related('dns_credential').order_by('hostname')
routes = application.routes.all().order_by('order', 'path_prefix')
is_reserved = application.name == RESERVED_APP_NAME
django_hostnames = []
if is_reserved:
for host in settings.ALLOWED_HOSTS:
try:
ipaddress.ip_address(host)
except ValueError:
django_hostnames.append(host)
context = {
'application': application,
'hosts': hosts,
'routes': routes,
'is_reserved': is_reserved,
'django_hostnames': django_hostnames,
'caddy_enabled': settings.CADDY_ENABLED,
'pending_export': caddy_export_pending(),
'page_title': _('Application Details'),
}
return render(request, 'app_gateway/application_details.html', context)
def worker_runs_gateway(worker):
# Workers running the App Gateway report the Caddy service; VPN-only workers do not serve applications
worker_status = getattr(worker, 'workerstatus', None)
return bool(worker_status and 'caddy' in (worker_status.services_status or {}))
def describe_certificate_status(certificate, certificate_type):
"""Badge information for a certificate inspected on the primary server or reported by a cluster worker."""
expiration = ''
if certificate.get('not_after'):
not_after = certificate['not_after']
if isinstance(not_after, str):
not_after = parse_datetime(not_after)
if not_after:
expiration = _('expires %(date)s') % {'date': date_format(localtime(not_after), 'SHORT_DATETIME_FORMAT')}
if certificate.get('status') == 'trusted':
return 'success', _('Trusted'), f"{certificate.get('issuer', '')}, {expiration}"
if certificate.get('status') == 'untrusted' and certificate_type == 'self_signed':
return 'secondary', _('Self-signed'), expiration
if certificate.get('status') == 'untrusted':
detail = _('The trusted certificate could not be issued yet, %(expiration)s') % {'expiration': expiration}
return 'warning', _('Using fallback'), detail
if certificate.get('status') == 'unknown':
return 'light', _('Unknown'), _('No recent report from this server.')
if certificate.get('status') == 'pending_export':
return 'info', _('Pending export'), _('Export the configuration to publish this host on this server.')
return 'danger', _('Unavailable'), _('No certificate is being served for this hostname.')
@login_required
def view_application_certificate_status(request):
if not UserAcl.objects.filter(user=request.user).filter(user_level__gte=20).exists():
return JsonResponse({'error': _('Access Denied')}, status=403)
application = get_object_or_404(Application, uuid=request.GET.get('uuid'))
if not settings.CADDY_ENABLED:
return JsonResponse({'caddy_enabled': False, 'hosts': {}})
workers = []
if application.name != RESERVED_APP_NAME and ClusterSettings.objects.filter(name='cluster_settings', enabled=True).exists():
workers = [
worker for worker in Worker.objects.filter(enabled=True).select_related('workerstatus').order_by('name')
if application.is_served_by(worker) and worker_runs_gateway(worker)
]
report_limit = timezone.now() - timedelta(minutes=10)
# Servers only publish what was exported, so hosts missing from their exported files are pending
primary_export = load_exported_files(CADDY_EXPORT_DIR) or {}
primary_exported_hosts = primary_export.get('tls.json', {}).get('hosts', {})
worker_exported_hosts = {}
for worker in workers:
worker_export = load_worker_export(worker) or {}
worker_exported_hosts[worker.pk] = worker_export.get('tls.json', {}).get('hosts', {})
hosts_status = {}
for application_host in application.hosts.all():
hostname = application_host.hostname.lower()
servers = []
# The primary server also manages ACME certificates of applications only served by workers
primary_handles_host = application.is_served_by(None) or (
application_host.certificate_type in ACME_CERTIFICATE_TYPES and application.served_by_workers
)
if primary_handles_host:
if hostname in primary_exported_hosts:
certificate = inspect_certificate(application_host.hostname)
else:
certificate = {'status': 'pending_export'}
servers.append((_('Primary Server'), certificate))
for worker in workers:
worker_status = getattr(worker, 'workerstatus', None)
if hostname not in worker_exported_hosts[worker.pk]:
certificate = {'status': 'pending_export'}
elif worker_status and worker_status.certificate_status_updated and worker_status.certificate_status_updated > report_limit:
certificate = worker_status.certificate_status.get(hostname, {'status': 'unavailable'})
else:
certificate = {'status': 'unknown'}
servers.append((worker.display_name, certificate))
hosts_status[str(application_host.uuid)] = []
for server_name, certificate in servers:
css_class, label, detail = describe_certificate_status(certificate, application_host.certificate_type)
hosts_status[str(application_host.uuid)].append({
'server': server_name if workers else '', 'css_class': css_class, 'label': label, 'detail': detail,
})
return JsonResponse({'caddy_enabled': True, 'hosts': hosts_status})
@login_required
def view_manage_application(request):
if not UserAcl.objects.filter(user=request.user).filter(user_level__gte=50).exists():
@@ -94,13 +192,17 @@ def view_manage_application(request):
application = None
title = _('Create Application')
if application:
cancel_url = reverse('view_application') + f'?uuid={application.uuid}'
else:
cancel_url = reverse('app_gateway_list') + '?tab=applications'
form = ApplicationForm(request.POST or None, instance=application, cancel_url=cancel_url)
if form.is_valid():
form.save()
application = form.save()
messages.success(request, _('Application saved successfully.'))
return redirect(cancel_url)
auto_apply_caddy_config(request)
return redirect(reverse('view_application') + f'?uuid={application.uuid}')
form_description = {
'size': 'col-lg-6',
@@ -140,6 +242,7 @@ def view_delete_application(request):
if request.method == 'POST':
application.delete()
messages.success(request, _('Application deleted successfully.'))
auto_apply_caddy_config(request)
return redirect(cancel_url)
context = {
@@ -170,24 +273,59 @@ def view_manage_application_host(request):
cancel_url = reverse('view_application') + f'?uuid={application.uuid}#hosts'
if application.name == RESERVED_APP_NAME:
is_reserved = application.name == RESERVED_APP_NAME
if is_reserved and not application_host:
messages.error(request, _('The WireGuard WebAdmin application cannot be modified.'))
return redirect(cancel_url)
form = ApplicationHostForm(request.POST or None, instance=application_host, cancel_url=cancel_url)
form = ApplicationHostForm(
request.POST or None, instance=application_host, cancel_url=cancel_url, is_reserved=is_reserved,
application=application,
)
if form.is_valid():
host = form.save(commit=False)
host.application = application
host.save()
messages.success(request, _('Application Host saved successfully.'))
auto_apply_caddy_config(request)
return redirect(cancel_url)
form_description_content = _('''
<h5>Certificate</h5>
<p>Defines how the TLS certificate for this hostname is issued.</p>
<ul>
<li><strong>Trusted certificate (HTTP validation)</strong>: Issued through ACME (e.g. Let's Encrypt) and validated over HTTP. The hostname must point to this server and ports 80/443 must be reachable from the internet.</li>
<li><strong>Trusted certificate (DNS validation)</strong>: Issued through ACME and validated with a DNS record created using the selected DNS credential. The server does not need to be reachable from the internet. When the credential uses a delegation domain, the hostname zone only needs a CNAME record pointing to it, shown when the credential is selected.</li>
<li><strong>Self-signed certificate</strong>: Issued by the internal Caddy CA. Browsers will show a security warning.</li>
</ul>
<p>When the fallback option is enabled and a trusted certificate cannot be issued, a self-signed certificate is used until the next successful attempt. Without the fallback, the connection fails until the certificate is issued.</p>
<p>Use <strong>Retry certificate</strong> in the host list to request a new attempt right away, for example after fixing the DNS or firewall.</p>
<p><strong>Important:</strong> the certificate is requested as soon as the configuration is applied. With HTTP validation, the hostname must already point to this server: failed attempts count towards the Let's Encrypt limit (5 per hour per hostname). If the DNS is not ready yet, use DNS validation.</p>
''')
if is_reserved:
form_description_content += _('''
<div class="alert alert-warning">
This hostname is used to access WireGuard WebAdmin. If the certificate cannot be issued,
your browser will show a security warning until the problem is fixed.
</div>
''')
initial_delegation_record = ''
if application_host and application_host.dns_delegation_record:
initial_delegation_record = ' '.join(application_host.dns_delegation_record)
context = {
'form': form,
'title': title,
'page_title': title,
'form_description': {'size': 'col-lg-6', 'content': form_description_content},
'delegation_domains': {
str(credential.pk): credential.delegation_domain
for credential in DnsChallengeCredential.objects.exclude(delegation_domain='')
},
'initial_delegation_record': initial_delegation_record,
}
return render(request, 'generic_form.html', context)
return render(request, 'app_gateway/application_host_form.html', context)
@login_required
@@ -207,6 +345,7 @@ def view_delete_application_host(request):
if request.method == 'POST':
application_host.delete()
messages.success(request, _('Application Host deleted successfully.'))
auto_apply_caddy_config(request)
return redirect(cancel_url)
context = {
@@ -251,6 +390,7 @@ def view_manage_access_policy(request):
if form.is_valid():
form.save()
messages.success(request, _('Access Policy saved successfully.'))
auto_apply_caddy_config(request)
return redirect(cancel_url)
if policy_type == 'public':
@@ -304,6 +444,7 @@ def view_delete_access_policy(request):
try:
access_policy.delete()
messages.success(request, _('Access Policy deleted successfully.'))
auto_apply_caddy_config(request)
except ProtectedError:
messages.error(request, _('Cannot delete this Access Policy because it is currently in use by an Application Route or Application Default Policy.'))
return redirect(cancel_url)
@@ -342,6 +483,7 @@ def view_manage_application_policy(request):
policy_config.application = application
policy_config.save()
messages.success(request, _('Application Default Policy saved successfully.'))
auto_apply_caddy_config(request)
return redirect(cancel_url)
context = {
@@ -365,6 +507,7 @@ def view_delete_application_policy(request):
if request.method == 'POST':
application_policy.delete()
messages.success(request, _('Application Default Policy deleted successfully.'))
auto_apply_caddy_config(request)
return redirect(cancel_url)
context = {
@@ -403,6 +546,7 @@ def view_manage_application_route(request):
route.application = application
route.save()
messages.success(request, _('Application Route saved successfully.'))
auto_apply_caddy_config(request)
return redirect(cancel_url)
form_description = {
@@ -441,6 +585,7 @@ def view_delete_application_route(request):
if request.method == 'POST':
application_route.delete()
messages.success(request, _('Application Route deleted successfully.'))
auto_apply_caddy_config(request)
return redirect(cancel_url)
context = {
@@ -455,6 +600,94 @@ def view_delete_application_route(request):
return render(request, 'generic_delete_confirmation.html', context)
@login_required
@require_POST
def view_retry_application_host_certificate(request):
if not UserAcl.objects.filter(user=request.user).filter(user_level__gte=50).exists():
return render(request, 'access_denied.html', {'page_title': _('Access Denied')})
application_host = get_object_or_404(ApplicationHost, uuid=request.GET.get('uuid'))
redirect_url = reverse('view_application') + f'?uuid={application_host.application.uuid}#hosts'
if not settings.CADDY_ENABLED:
messages.error(request, _('This action is not available because Caddy is not enabled.'))
return redirect(redirect_url)
ApplicationHost.objects.filter(pk=application_host.pk).update(certificate_generation=F('certificate_generation') + 1)
apply_caddy_config()
if application_host.certificate_type == 'self_signed':
message = _('A new self-signed certificate will be issued for %(hostname)s. The current configuration was exported.')
else:
message = _('A new certificate will be requested for %(hostname)s. The current configuration was exported.')
messages.success(request, message % {'hostname': application_host.hostname})
return redirect(redirect_url)
@login_required
def view_manage_dns_credential(request):
if not UserAcl.objects.filter(user=request.user).filter(user_level__gte=50).exists():
return render(request, 'access_denied.html', {'page_title': _('Access Denied')})
dns_credential_uuid = request.GET.get('uuid')
if dns_credential_uuid:
dns_credential = get_object_or_404(DnsChallengeCredential, uuid=dns_credential_uuid)
title = _('Edit DNS Credential')
else:
dns_credential = None
title = _('Add DNS Credential')
cancel_url = reverse('app_gateway_list') + '?tab=dns_credentials'
form = DnsChallengeCredentialForm(request.POST or None, instance=dns_credential, cancel_url=cancel_url)
if form.is_valid():
dns_credential = form.save()
messages.success(request, _('DNS Credential saved successfully.'))
host_count = dns_credential.hosts.filter(certificate_type='dns_challenge').count()
if 'delegation_domain' in form.changed_data and host_count:
messages.warning(request, _(
'Delegation domain changed|Update the challenge records of the %(count)s hosts using this '
'credential. The required records are shown in the host list of each application.'
) % {'count': host_count})
auto_apply_caddy_config(request)
return redirect(cancel_url)
context = {
'form': form,
'title': title,
'page_title': title,
}
return render(request, 'app_gateway/dns_credential_form.html', context)
@login_required
def view_delete_dns_credential(request):
if not UserAcl.objects.filter(user=request.user).filter(user_level__gte=50).exists():
return render(request, 'access_denied.html', {'page_title': _('Access Denied')})
dns_credential = get_object_or_404(DnsChallengeCredential, uuid=request.GET.get('uuid'))
cancel_url = reverse('app_gateway_list') + '?tab=dns_credentials'
if request.method == 'POST':
try:
dns_credential.delete()
messages.success(request, _('DNS Credential deleted successfully.'))
auto_apply_caddy_config(request)
except ProtectedError:
messages.error(request, _('Cannot delete this DNS Credential because it is currently in use by an Application Host.'))
return redirect(cancel_url)
context = {
'dns_credential': dns_credential,
'title': _('Delete DNS Credential'),
'cancel_url': cancel_url,
'text': _('Are you sure you want to delete the DNS credential "%(name)s"?') % {'name': dns_credential.display_name}
}
return render(request, 'generic_delete_confirmation.html', context)
@login_required
@require_POST
def view_export_caddy_config(request):
@@ -462,6 +695,9 @@ def view_export_caddy_config(request):
return render(request, 'access_denied.html', {'page_title': _('Access Denied')})
redirect_url = reverse('app_gateway_list') + '?tab=applications'
next_url = request.POST.get('next', '')
if next_url and url_has_allowed_host_and_scheme(next_url, allowed_hosts={request.get_host()}):
redirect_url = next_url
if not settings.CADDY_ENABLED:
messages.error(request, _(
@@ -470,10 +706,6 @@ def view_export_caddy_config(request):
))
return redirect(redirect_url)
export_caddy_config('/caddy_json_export/')
if settings.DEBUG:
export_caddy_config(os.path.join(settings.BASE_DIR, 'containers', 'caddy', 'config_files'))
apply_caddy_config()
messages.success(request, _('Configuration exported successfully.'))
return redirect(redirect_url)
+8
View File
@@ -114,6 +114,14 @@ fi
# ── .dockerignore ──
cat .gitignore > .dockerignore
cat >> .dockerignore <<'EOF'
# Not needed inside the main image
.git
containers
docs
screenshots
EOF
# ── Build and push ──
DEFAULT_PLATFORMS="linux/amd64,linux/arm64"
+5 -5
View File
@@ -5,18 +5,18 @@ from .models import ClusterSettings, Worker, WorkerStatus
@admin.register(ClusterSettings)
class ClusterSettingsAdmin(admin.ModelAdmin):
list_display = ('name', 'enabled', 'cluster_mode', 'restart_mode', 'config_version', 'created', 'updated')
list_filter = ('enabled', 'cluster_mode', 'restart_mode', 'primary_enable_wireguard')
list_display = ('name', 'enabled', 'cluster_mode', 'created', 'updated')
list_filter = ('enabled', 'cluster_mode', 'primary_enable_wireguard')
@admin.register(Worker)
class WorkerAdmin(admin.ModelAdmin):
list_display = ('name', 'enabled', 'ip_address', 'country', 'city', 'ip_lock', 'created', 'updated')
list_filter = ('enabled', 'ip_lock', 'country', 'force_reload', 'force_restart')
list_filter = ('enabled', 'ip_lock', 'country')
@admin.register(WorkerStatus)
class WorkerStatusAdmin(admin.ModelAdmin):
list_display = ('worker', 'last_seen', 'config_version', 'last_reload', 'last_restart')
list_filter = ('last_seen', 'last_reload', 'last_restart')
list_display = ('worker', 'last_seen', 'worker_version', 'wireguard_status_updated')
list_filter = ('last_seen',)
+135 -179
View File
@@ -1,220 +1,176 @@
import glob
import json
import os
from django.conf import settings
from django.http import JsonResponse, FileResponse
from django.core.exceptions import ValidationError
from django.http import JsonResponse
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.gzip import gzip_page
from django.views.decorators.http import require_GET, require_POST
from .models import ClusterSettings, Worker, WorkerStatus
from cluster.models import ClusterSettings, Worker, WorkerStatus
from cluster.sync import SECTION_NAMES, build_manifest, build_section
from gatekeeper.sessions import clean_gateway_sessions
REPORT_STATUS_FIELDS = ('status', 'message')
def get_ip_address(request):
ip_address = request.META.get('HTTP_X_FORWARDED_FOR')
if ip_address:
ip_address = ip_address.split(',')[0]
ip_address = ip_address.split(',')[0].strip()
else:
ip_address = request.META.get('REMOTE_ADDR')
return ip_address
def get_cluster_settings():
cluster_settings, created = ClusterSettings.objects.get_or_create(name='cluster_settings')
return {
'enabled': cluster_settings.enabled,
'primary_enable_wireguard': cluster_settings.primary_enable_wireguard,
'stats_sync_interval': settings.WIREGUARD_STATUS_CACHE_REFRESH_INTERVAL,
'cluster_mode': cluster_settings.cluster_mode,
'restart_mode': cluster_settings.restart_mode,
'config_version': cluster_settings.config_version,
'dns_version': cluster_settings.dns_version,
}
def _error_response(message, status):
return JsonResponse({'status': 'error', 'message': message}, status=status)
def get_worker(request):
success = True
ip_address = get_ip_address(request)
token = request.GET.get('token', '')
"""
Authenticate the worker from the Authorization header and update its status.
Returns (worker, None) on success or (None, JsonResponse) when the request must be rejected.
"""
authorization = request.headers.get('Authorization', '')
if not authorization.startswith('Bearer '):
return None, _error_response('Worker not found', 403)
try:
worker = Worker.objects.get(token=token)
except:
return None, False
worker = Worker.objects.get(token=authorization[len('Bearer '):].strip())
except (Worker.DoesNotExist, ValidationError, ValueError):
return None, _error_response('Worker not found', 403)
worker_status, created = WorkerStatus.objects.get_or_create(worker=worker)
worker_status, worker_status_created = WorkerStatus.objects.get_or_create(worker=worker)
try:
worker_config_version = int(request.GET.get('worker_config_version'))
worker_version = int(request.GET.get('worker_version'))
worker_dns_version = int(request.GET.get('worker_dns_version'))
except:
worker.error_status = 'missing_version'
worker.save()
return worker, False
if worker.error_status == 'missing_version':
worker.error_status = ''
worker.save()
if worker_version < settings.CLUSTER_WORKER_MINIMUM_VERSION:
worker.error_status = 'update_required'
worker.save()
return worker, False
if worker.error_status == 'update_required':
worker.error_status = ''
worker.save()
if worker_status.config_version != worker_config_version:
worker_status.config_version = worker_config_version
if worker_status.worker_version != worker_version:
worker_version = int(request.headers.get('X-Worker-Version', '0'))
except ValueError:
worker_version = 0
worker_status.worker_version = worker_version
if worker_status.dns_version != worker_dns_version:
worker_status.dns_version = worker_dns_version
worker_status.last_seen = timezone.now()
worker_status.save()
worker_status.save(update_fields=['worker_version', 'last_seen', 'updated'])
if not worker.ip_address:
worker.ip_address = ip_address
worker.save()
if worker.ip_lock:
if worker.ip_address == ip_address:
if worker.error_status == 'ip_lock':
worker.error_status = ''
worker.save()
ip_address = get_ip_address(request)
error_status = ''
if worker_version < settings.CLUSTER_WORKER_MINIMUM_VERSION:
error_status = 'update_required'
elif worker.ip_lock and worker.ip_address and worker.ip_address != ip_address:
error_status = 'ip_lock'
elif not worker.enabled:
error_status = 'worker_disabled'
else:
worker.error_status = 'ip_lock'
worker.save()
success = False
else:
if worker.ip_address != ip_address:
worker.ip_address = ip_address
worker.save()
if worker.enabled:
if worker.error_status == 'worker_disabled':
worker.error_status = ''
worker.save()
else:
worker.error_status = 'worker_disabled'
worker.save()
success = False
cluster_settings, created = ClusterSettings.objects.get_or_create(name='cluster_settings')
if not settings.WIREGUARD_STATUS_CACHE_ENABLED and cluster_settings.enabled:
cluster_settings, cluster_settings_created = ClusterSettings.objects.get_or_create(name='cluster_settings')
if cluster_settings.enabled and not settings.WIREGUARD_STATUS_CACHE_ENABLED:
cluster_settings.enabled = False
cluster_settings.save()
if not cluster_settings.enabled:
error_status = 'cluster_disabled'
if cluster_settings.enabled:
if worker.error_status == 'cluster_disabled':
worker.error_status = ''
worker.save()
else:
worker.error_status = 'cluster_disabled'
worker.save()
success = False
update_fields = []
if not worker.ip_lock and worker.ip_address != ip_address:
worker.ip_address = ip_address
update_fields.append('ip_address')
if worker.error_status != error_status:
worker.error_status = error_status
update_fields.append('error_status')
if update_fields:
worker.save(update_fields=update_fields + ['updated'])
return worker, success
if error_status:
return None, _error_response(error_status, 400)
return worker, None
def api_get_worker_dnsmasq_config(request):
dnsmasq_file = "/etc/dnsmasq/dnsmasq_config.tar.gz"
worker, success = get_worker(request)
if worker:
if worker.error_status or not success:
data = {'status': 'error', 'message': worker.error_status}
return JsonResponse(data, status=400)
else:
data = {'status': 'error', 'message': 'Worker not found'}
return JsonResponse(data, status=403)
def api_legacy_cluster_status(request):
# Workers before version 12 poll this endpoint. A 403 makes them shut down WireGuard and stop polling.
return JsonResponse({
'status': 'error',
'message': 'update_required',
'minimum_worker_version': settings.CLUSTER_WORKER_MINIMUM_VERSION,
}, status=403)
if not os.path.exists(dnsmasq_file):
data = {'status': 'error', 'message': 'dnsmasq configuration not found'}
return JsonResponse(data, status=404)
response = FileResponse(open(dnsmasq_file, "rb"), content_type="application/gzip")
response["Content-Disposition"] = 'attachment; filename="dnsmasq_config.tar.gz"'
response["Content-Length"] = str(os.path.getsize(dnsmasq_file))
return response
@require_GET
def api_manifest(request):
worker, error_response = get_worker(request)
if error_response:
return error_response
return JsonResponse({
'status': 'success',
'worker_minimum_version': settings.CLUSTER_WORKER_MINIMUM_VERSION,
'sections': build_manifest(worker),
})
@gzip_page
@require_GET
def api_section(request, section_name):
worker, error_response = get_worker(request)
if error_response:
return error_response
if section_name not in SECTION_NAMES:
return _error_response('Section not found', 404)
return JsonResponse({'status': 'success', 'section': section_name, **build_section(section_name, worker).as_dict()})
def _clean_section_report(sections):
cleaned_sections = {}
for section_name, report in sections.items():
if section_name not in SECTION_NAMES or not isinstance(report, dict):
continue
status = report.get('status')
if status not in ('ok', 'error'):
continue
cleaned_sections[section_name] = {
'hash': str(report.get('hash', ''))[:64],
'status': status,
'message': str(report.get('message', ''))[:1000],
'updated': timezone.now().isoformat(),
}
return cleaned_sections
@csrf_exempt
def api_submit_worker_wireguard_stats(request):
worker, success = get_worker(request)
if worker:
if worker.error_status or not success:
data = {'status': 'error', 'message': worker.error_status}
return JsonResponse(data, status=400)
else:
data = {'status': 'error', 'message': 'Worker not found'}
return JsonResponse(data, status=403)
@require_POST
def api_report(request):
worker, error_response = get_worker(request)
if error_response:
return error_response
try:
if request.method == 'POST':
payload = json.loads(request.body)
except (ValueError, UnicodeDecodeError):
return _error_response('Invalid JSON', 400)
if not isinstance(payload, dict):
return _error_response('Invalid JSON', 400)
worker_status = worker.workerstatus
worker_status.wireguard_status = payload
update_fields = []
if isinstance(payload.get('sections'), dict):
section_status = dict(worker_status.section_status or {})
section_status.update(_clean_section_report(payload['sections']))
worker_status.section_status = section_status
update_fields.append('section_status')
if isinstance(payload.get('services'), dict):
worker_status.services_status = payload['services']
update_fields.append('services_status')
if isinstance(payload.get('certificates'), dict):
worker_status.certificate_status = payload['certificates']
worker_status.certificate_status_updated = timezone.now()
update_fields += ['certificate_status', 'certificate_status_updated']
if isinstance(payload.get('gateway_sessions'), list):
worker_status.gateway_sessions = clean_gateway_sessions(payload['gateway_sessions'])
worker_status.gateway_sessions_updated = timezone.now()
update_fields += ['gateway_sessions', 'gateway_sessions_updated']
if isinstance(payload.get('wireguard_status'), dict):
worker_status.wireguard_status = payload['wireguard_status']
worker_status.wireguard_status_updated = timezone.now()
worker_status.save()
data = {'status': 'success', 'message': 'Stats received'}
return JsonResponse(data, status=200)
except Exception as e:
pass
update_fields += ['wireguard_status', 'wireguard_status_updated']
data = {'status': 'error', 'message': 'Stats not received'}
return JsonResponse(data, status=400)
def api_get_worker_config_files(request):
worker, success = get_worker(request)
if worker:
if worker.error_status or not success:
data = {'status': 'error', 'message': worker.error_status}
return JsonResponse(data, status=400)
else:
data = {'status': 'error', 'message': 'Worker not found'}
return JsonResponse(data, status=403)
config_files = (
glob.glob('/etc/wireguard/wg*.conf') +
glob.glob('/etc/wireguard/wg-firewall.sh')
)
files = {}
for path in config_files:
filename = os.path.basename(path)
with open(path, 'r') as f:
files[filename] = f.read()
data = {'status': 'success', 'files': files, 'cluster_settings': get_cluster_settings()}
return JsonResponse(data, status=200)
def api_worker_ping(request):
worker, success = get_worker(request)
if worker:
if worker.error_status or not success:
data = {'status': 'error', 'message': worker.error_status}
return JsonResponse(data, status=400)
else:
data = {'status': 'error', 'message': 'Worker not found'}
return JsonResponse(data, status=403)
data = {
'status': 'success',
'worker_error_status': worker.error_status,
}
return JsonResponse(data, status=200)
def api_cluster_status(request):
worker, success = get_worker(request)
if worker:
if worker.error_status or not success:
data = {'status': 'error', 'message': worker.error_status}
return JsonResponse(data, status=400)
else:
data = {'status': 'error', 'message': 'Worker not found'}
return JsonResponse(data, status=403)
data = {'status': 'success', 'worker_error_status': worker.error_status, 'cluster_settings': get_cluster_settings()}
return JsonResponse(data, status=200)
if update_fields:
worker_status.save(update_fields=update_fields + ['updated'])
return JsonResponse({'status': 'success'})
+24 -9
View File
@@ -5,7 +5,8 @@ from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from .models import ClusterSettings, Worker
from firewall.models import FirewallRule
from .models import DISTRIBUTED_MODES, ClusterSettings, Worker
class WorkerForm(forms.ModelForm):
@@ -31,8 +32,10 @@ class WorkerForm(forms.ModelForm):
if self.instance.pk:
delete_html = f"<a href='javascript:void(0)' class='btn btn-outline-danger' data-command='delete' onclick='openCommandDialog(this)'>{delete_label}</a>"
back_url = f"/cluster/worker/view/?uuid={self.instance.uuid}"
else:
delete_html = ''
back_url = '/cluster/'
self.helper.layout = Layout(
Row(
@@ -65,7 +68,7 @@ class WorkerForm(forms.ModelForm):
Row(
Column(
Submit('submit', _('Save'), css_class='btn btn-success'),
HTML(f' <a class="btn btn-secondary" href="/cluster/">{back_label}</a> '),
HTML(f' <a class="btn btn-secondary" href="{back_url}">{back_label}</a> '),
HTML(delete_html),
css_class='col-md-12'),
css_class='form-row'
@@ -90,14 +93,13 @@ class WorkerForm(forms.ModelForm):
class ClusterSettingsForm(forms.ModelForm):
class Meta:
model = ClusterSettings
fields = ['enabled', 'primary_enable_wireguard', 'cluster_mode', 'restart_mode', 'worker_display']
fields = ['enabled', 'primary_enable_wireguard', 'cluster_mode', 'worker_display']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['enabled'].label = _("Cluster Enabled")
self.fields['primary_enable_wireguard'].label = _("Primary Enable WireGuard")
self.fields['cluster_mode'].label = _("Cluster Mode")
self.fields['restart_mode'].label = _("Restart Mode")
self.fields['worker_display'].label = _("Worker Display")
back_label = _("Back")
@@ -112,11 +114,7 @@ class ClusterSettingsForm(forms.ModelForm):
),
Row(
Column('cluster_mode', css_class='form-group col-md-6 mb-0'),
Column('restart_mode', css_class='form-group col-md-6 mb-0'),
css_class='form-row'
),
Row(
Column('worker_display', css_class='form-group col-md-12 mb-0'),
Column('worker_display', css_class='form-group col-md-6 mb-0'),
css_class='form-row'
),
Row(
@@ -132,7 +130,24 @@ 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."))
if cluster_enabled and cleaned_data.get('cluster_mode') in DISTRIBUTED_MODES:
instance_rules = list(FirewallRule.with_instance_interface().order_by('firewall_chain', 'sort_order'))
if instance_rules:
rule_list = ', '.join(
rule.description or f"{rule.get_firewall_chain_display()} #{rule.sort_order}" for rule in instance_rules
)
raise ValidationError(_(
"The distributed cluster mode does not allow firewall rules bound to a specific WireGuard instance. "
"Change them to wg+ or IP addresses first: %(rules)s"
) % {'rules': rule_list})
return cleaned_data
View File
@@ -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)
+78
View File
@@ -0,0 +1,78 @@
# Generated by Django 5.2.19 on 2026-11-19 16:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cluster', '0017_alter_workerstatus_wireguard_status'),
]
operations = [
migrations.RemoveField(
model_name='clustersettings',
name='config_version',
),
migrations.RemoveField(
model_name='clustersettings',
name='dns_version',
),
migrations.RemoveField(
model_name='clustersettings',
name='restart_mode',
),
migrations.RemoveField(
model_name='worker',
name='force_reload',
),
migrations.RemoveField(
model_name='worker',
name='force_restart',
),
migrations.RemoveField(
model_name='workerstatus',
name='active_peers',
),
migrations.RemoveField(
model_name='workerstatus',
name='config_version',
),
migrations.RemoveField(
model_name='workerstatus',
name='dns_version',
),
migrations.RemoveField(
model_name='workerstatus',
name='last_reload',
),
migrations.RemoveField(
model_name='workerstatus',
name='last_restart',
),
migrations.AddField(
model_name='workerstatus',
name='certificate_status',
field=models.JSONField(blank=True, default=dict),
),
migrations.AddField(
model_name='workerstatus',
name='certificate_status_updated',
field=models.DateTimeField(blank=True, null=True),
),
migrations.AddField(
model_name='workerstatus',
name='section_status',
field=models.JSONField(blank=True, default=dict),
),
migrations.AddField(
model_name='workerstatus',
name='services_status',
field=models.JSONField(blank=True, default=dict),
),
migrations.AlterField(
model_name='worker',
name='error_status',
field=models.CharField(choices=[('', ''), ('ip_lock', 'IP lock is enabled, but the worker is attempting to access from a different IP address.'), ('worker_disabled', 'Worker is not enabled'), ('cluster_disabled', 'Cluster is not enabled'), ('update_required', 'Worker update is required.')], default='', max_length=32),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 5.2.19 on 2026-11-20 19:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cluster', '0018_cluster_v2'),
]
operations = [
migrations.AlterField(
model_name='clustersettings',
name='cluster_mode',
field=models.CharField(choices=[('mirror', 'Mirror'), ('distributed', 'Distributed')], default='mirror', max_length=16),
),
]
@@ -0,0 +1,23 @@
# Generated by Django 5.2.19 on 2026-11-21 18:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cluster', '0019_alter_clustersettings_cluster_mode'),
]
operations = [
migrations.AddField(
model_name='workerstatus',
name='gateway_sessions',
field=models.JSONField(blank=True, default=list),
),
migrations.AddField(
model_name='workerstatus',
name='gateway_sessions_updated',
field=models.DateTimeField(blank=True, null=True),
),
]
+33 -13
View File
@@ -3,21 +3,22 @@ import uuid
from django.db import models
from django.utils.translation import gettext_lazy as _
DISTRIBUTED_MODES = ('distributed',)
class ClusterSettings(models.Model):
name = models.CharField(default='cluster_settings', max_length=16, unique=True)
enabled = models.BooleanField(default=False)
primary_enable_wireguard = models.BooleanField(default=True)
cluster_mode = models.CharField(default='mirror', max_length=16, choices=(('mirror', 'Mirror'), ))
restart_mode = models.CharField(default='auto', max_length=16, choices=(('auto', 'Automatic restart'),))
cluster_mode = models.CharField(
default='mirror', max_length=16, choices=(('mirror', 'Mirror'), ('distributed', 'Distributed'))
)
worker_display = models.CharField(
default='server_address', max_length=16, choices=(
('name', 'Name'), ('server_address', 'Server Address'),
('location', 'Location'), ('address_location', 'Address + Location')
)
)
config_version = models.PositiveIntegerField(default=0)
dns_version = models.PositiveIntegerField(default=0)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
@@ -26,6 +27,25 @@ class ClusterSettings(models.Model):
def __str__(self):
return self.name
@classmethod
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."""
return cls.objects.filter(name='cluster_settings', enabled=True, cluster_mode__in=DISTRIBUTED_MODES).exists()
class Worker(models.Model):
name = models.CharField(max_length=100, unique=True)
@@ -34,9 +54,6 @@ class Worker(models.Model):
ip_lock = models.BooleanField(default=False)
ip_address = models.GenericIPAddressField(blank=True, null=True)
force_reload = models.BooleanField(default=False)
force_restart = models.BooleanField(default=False)
country = models.CharField(max_length=100, blank=True, null=True)
city = models.CharField(max_length=100, blank=True, null=True)
hostname = models.CharField(max_length=100, blank=True, null=True)
@@ -46,7 +63,6 @@ class Worker(models.Model):
('ip_lock', _('IP lock is enabled, but the worker is attempting to access from a different IP address.')),
('worker_disabled', _('Worker is not enabled')),
('cluster_disabled', _('Cluster is not enabled')),
('missing_version', _('Please report worker_config_version, worker_dns_version and worker_version in the API request.')),
('update_required', _('Worker update is required.'))
))
@@ -105,14 +121,18 @@ class Worker(models.Model):
class WorkerStatus(models.Model):
worker = models.OneToOneField(Worker, on_delete=models.CASCADE)
last_seen = models.DateTimeField(auto_now=True)
last_reload = models.DateTimeField(blank=True, null=True)
last_restart = models.DateTimeField(blank=True, null=True)
dns_version = models.PositiveIntegerField(default=0)
config_version = models.PositiveIntegerField(default=0)
worker_version = models.PositiveIntegerField(default=0)
active_peers = models.PositiveIntegerField(default=0)
wireguard_status = models.JSONField(blank=True, null=True)
wireguard_status_updated = models.DateTimeField(blank=True, null=True)
# {section: {"hash": ..., "status": "ok"|"error", "message": ..., "updated": ...}}
section_status = models.JSONField(default=dict, blank=True)
services_status = models.JSONField(default=dict, blank=True)
# {hostname: {"status": ..., "issuer": ..., "not_after": ..., "generation": ...}}
certificate_status = models.JSONField(default=dict, blank=True)
certificate_status_updated = models.DateTimeField(blank=True, null=True)
# Active sessions of the auth-gateway of the worker, as published in its sessions snapshot
gateway_sessions = models.JSONField(default=list, blank=True)
gateway_sessions_updated = models.DateTimeField(blank=True, null=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
+256
View File
@@ -0,0 +1,256 @@
import glob
import hashlib
import json
import os
from datetime import timedelta
from django.conf import settings
from django.db.models import Prefetch
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from app_gateway.caddy_config_export import (
add_certificate_files, certificate_file_name, load_worker_export, read_exported_certificate
)
from cluster.models import ClusterSettings, WorkerStatus
from dns.functions import generate_dnsmasq_config
from dns.models import DNSFilterList
from firewall.tools import generate_firewall_script
from gatekeeper.sessions import REVOKED_SESSIONS_FILE, build_revoked_sessions_data
from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance
from wireguard_tools.functions import (
CLUSTER_WIREGUARD_CONFIG_DIR, ENDPOINT_PEER_TITLE, WIREGUARD_CONFIG_DIR, peer_config_lines, remove_endpoint_peers
)
DNSMASQ_CONFIG_DIR = '/etc/dnsmasq'
DNSMASQ_MAIN_CONFIG = 'wireguard_webadmin_dns.conf'
# Sections are applied by the node in this order. The firewall comes first because the WireGuard
# configuration runs wg-firewall.sh as PostUp of one of the instances, and certificates come before the
# gateway so the generated Caddyfile only references files that already exist.
SECTION_NAMES = ('firewall', 'wireguard', 'dns', 'settings', 'certificates', 'gateway')
# Large files (e.g. DNS filter lists) are only read and hashed again when they change on disk
_file_cache = {}
def _sha256(text):
return hashlib.sha256(text.encode()).hexdigest()
def _read_file(path):
file_stat = os.stat(path)
cache_key = (file_stat.st_mtime_ns, file_stat.st_size)
cached = _file_cache.get(path)
if cached and cached['key'] == cache_key:
return cached['content'], cached['sha256']
with open(path, 'r', encoding='utf-8', errors='replace') as config_file:
content = config_file.read()
content_sha256 = _sha256(content)
_file_cache[path] = {'key': cache_key, 'content': content, 'sha256': content_sha256}
return content, content_sha256
class Section:
def __init__(self):
self.files = {}
self.file_hashes = {}
self.values = {}
def add_file(self, filename, content, content_sha256=None):
self.files[filename] = content
self.file_hashes[filename] = content_sha256 or _sha256(content)
@property
def hash(self):
fingerprint = json.dumps({'files': self.file_hashes, 'values': self.values}, sort_keys=True)
return _sha256(fingerprint)
def as_dict(self):
return {'hash': self.hash, 'files': self.files, 'values': self.values}
def build_wireguard_section(worker):
section = Section()
if ClusterSettings.is_distributed():
# Only the instances that run on this worker
config_paths = [
os.path.join(CLUSTER_WIREGUARD_CONFIG_DIR, f'wg{instance_id}.conf')
for instance_id in WireGuardInstance.objects.filter(worker=worker).values_list('instance_id', flat=True)
]
else:
config_paths = glob.glob(os.path.join(WIREGUARD_CONFIG_DIR, 'wg[0-9]*.conf'))
for config_path in sorted(config_paths):
if not os.path.isfile(config_path):
continue
content, content_sha256 = _read_file(config_path)
if not ClusterSettings.is_distributed():
content, content_sha256 = _mirror_endpoint_peers(
content, content_sha256, os.path.basename(config_path), worker
)
section.add_file(os.path.basename(config_path), content, content_sha256)
return section
def _mirror_endpoint_peers(content, content_sha256, filename, worker):
"""
In the mirror mode only one server connects to the remote endpoint of a peer: the configuration of the primary
server is sent without its endpoint peers, plus the endpoint peers that run on this worker.
"""
try:
instance_id = int(filename[len('wg'):-len('.conf')])
except ValueError:
return content, content_sha256
endpoint_peers = (
Peer.objects.filter(
wireguard_instance__instance_id=instance_id, active_worker=worker,
suspended=False, disabled_by_schedule=False,
)
.exclude(endpoint='')
.prefetch_related(Prefetch('peerallowedip_set', queryset=PeerAllowedIP.objects.filter(config_file='server')))
)
worker_lines = [line for peer in endpoint_peers for line in peer_config_lines(peer)]
if not worker_lines and ENDPOINT_PEER_TITLE not in content:
return content, content_sha256
content = remove_endpoint_peers(content)
if worker_lines:
content = content.rstrip("\n") + "\n\n" + "\n".join(worker_lines)
return content, None
def build_firewall_section(worker):
section = Section()
section.add_file('wg-firewall.sh', generate_firewall_script(cluster_node=True, worker=worker))
return section
def build_dns_section(worker):
section = Section()
for dns_list in DNSFilterList.objects.filter(enabled=True).order_by('uuid'):
list_path = os.path.join(DNSMASQ_CONFIG_DIR, f'{dns_list.uuid}.conf')
if os.path.isfile(list_path):
content, content_sha256 = _read_file(list_path)
section.add_file(os.path.basename(list_path), content, content_sha256)
section.add_file(DNSMASQ_MAIN_CONFIG, generate_dnsmasq_config(cluster_node=True))
return section
def build_settings_section(worker):
section = Section()
section.values = {
'stats_sync_interval': settings.WIREGUARD_STATUS_CACHE_REFRESH_INTERVAL,
}
return section
EMPTY_GATEWAY_EXPORT = {
'applications.json': {'entries': []},
'auth_policies.json': {'auth_methods': {}, 'groups': {}, 'users': {}, 'policies': {}},
'routes.json': {'entries': {}},
'tls.json': {'hosts': {}, 'dns_credentials': {}},
}
def get_gateway_export(worker):
"""Configuration exported for the worker, with the certificate files currently available on the primary."""
gateway_export = load_worker_export(worker) or json.loads(json.dumps(EMPTY_GATEWAY_EXPORT))
add_certificate_files(gateway_export['tls.json'])
return gateway_export
def build_certificates_section(worker):
"""Certificate and private key of every ACME host served by the worker, named after the certificate hash."""
section = Section()
for hostname, host_tls in sorted(get_gateway_export(worker)['tls.json']['hosts'].items()):
if not host_tls.get('certificate_file'):
continue
certificate, private_key = read_exported_certificate(hostname)
if not certificate or not private_key:
continue
file_name = certificate_file_name(certificate)
section.add_file(f'{file_name}.crt', certificate)
section.add_file(f'{file_name}.key', private_key)
return section
def build_gateway_section(worker):
section = Section()
for file_name, data in get_gateway_export(worker).items():
section.add_file(file_name, json.dumps(data, indent=2) + '\n')
# Sessions ended from the WireGuard WebAdmin, the same for every server
section.add_file(REVOKED_SESSIONS_FILE, json.dumps(build_revoked_sessions_data(), indent=2) + '\n')
return section
SECTION_BUILDERS = {
'firewall': build_firewall_section,
'wireguard': build_wireguard_section,
'dns': build_dns_section,
'settings': build_settings_section,
'certificates': build_certificates_section,
'gateway': build_gateway_section,
}
def build_section(section_name, worker):
return SECTION_BUILDERS[section_name](worker)
def build_manifest(worker):
return {section_name: build_section(section_name, worker).hash for section_name in SECTION_NAMES}
CERTIFICATE_EXPIRATION_WARNING_DAYS = 14
def get_worker_warnings(worker):
"""Stopped services and certificates that are not trusted or expire soon, as reported by the worker."""
try:
worker_status = worker.workerstatus
except WorkerStatus.DoesNotExist:
return {'stopped_services': [], 'certificate_issues': []}
stopped_services = sorted(
service for service, state in (worker_status.services_status or {}).items() if state != 'running'
)
expiration_limit = timezone.now() + timedelta(days=CERTIFICATE_EXPIRATION_WARNING_DAYS)
certificate_issues = []
for hostname, certificate in sorted((worker_status.certificate_status or {}).items()):
not_after = parse_datetime(certificate.get('not_after') or '')
if certificate.get('status') not in ('trusted', 'untrusted'):
certificate_issues.append(hostname)
elif certificate.get('status') == 'trusted' and not_after and not_after < expiration_limit:
certificate_issues.append(hostname)
return {'stopped_services': stopped_services, 'certificate_issues': certificate_issues}
def get_worker_sync_state(worker, manifest=None):
"""
Compare the hashes reported by the worker with the current ones.
Returns {'state': 'synced'|'pending'|'error', 'sections': {name: {'state': ..., 'message': ...}}}.
"""
manifest = manifest or build_manifest(worker)
try:
section_status = worker.workerstatus.section_status or {}
except WorkerStatus.DoesNotExist:
section_status = {}
sections = {}
for section_name, section_hash in manifest.items():
reported = section_status.get(section_name) or {}
if reported.get('hash') != section_hash:
# A previous error is kept as information while the node retries with the new content
sections[section_name] = {'state': 'pending', 'message': reported.get('message', '')}
elif reported.get('status') == 'error':
sections[section_name] = {'state': 'error', 'message': reported.get('message', '')}
else:
sections[section_name] = {'state': 'synced', 'message': ''}
states = {section['state'] for section in sections.values()}
if 'error' in states:
state = 'error'
elif 'pending' in states:
state = 'pending'
else:
state = 'synced'
return {'state': state, 'sections': sections}
+793 -1
View File
@@ -1 +1,793 @@
# Create your tests here.
import json
import os
import socket
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
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.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
from dns.models import DNSSettings
from firewall.forms import FirewallRuleForm
from firewall.models import FirewallRule, FirewallSettings, RedirectRule
from firewall.tools import generate_firewall_script
from user_manager.models import UserAcl
from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance
from wireguard_tools.functions import get_config_servers
from wireguard_tools.tests import load_cluster_worker
from wireguard_tools.views import export_wireguard_configuration, generate_peer_config
FAKE_CERTIFICATE = '-----BEGIN CERTIFICATE-----\nfake\n-----END CERTIFICATE-----\n'
FAKE_PRIVATE_KEY = '-----BEGIN PRIVATE KEY-----\nfake\n-----END PRIVATE KEY-----\n'
class ClusterTestMixin:
"""Isolated directories for the files read and written by the cluster sync and the Caddy export."""
def setUp(self):
super().setUp()
self.temp_dir = tempfile.TemporaryDirectory()
self.addCleanup(self.temp_dir.cleanup)
self.wireguard_dir = os.path.join(self.temp_dir.name, 'wireguard')
self.dnsmasq_dir = os.path.join(self.temp_dir.name, 'dnsmasq')
self.export_dir = os.path.join(self.temp_dir.name, 'caddy_json_export')
self.certificate_export_dir = os.path.join(self.temp_dir.name, 'caddy_cert_export')
for directory in (self.wireguard_dir, self.dnsmasq_dir, self.export_dir, self.certificate_export_dir):
os.makedirs(directory)
with open(os.path.join(self.wireguard_dir, 'wg0.conf'), 'w', encoding='utf-8') as config_file:
config_file.write('[Interface]\nListenPort = 51820\n')
for target, value in (
('cluster.sync.WIREGUARD_CONFIG_DIR', self.wireguard_dir),
('cluster.sync.DNSMASQ_CONFIG_DIR', self.dnsmasq_dir),
('app_gateway.caddy_config_export.CADDY_EXPORT_DIR', self.export_dir),
('app_gateway.caddy_config_export.CERTIFICATE_EXPORT_DIR', self.certificate_export_dir),
):
patcher = patch(target, value)
patcher.start()
self.addCleanup(patcher.stop)
DNSSettings.objects.get_or_create(name='dns_settings')
ClusterSettings.objects.update_or_create(name='cluster_settings', defaults={'enabled': True})
self.worker = Worker.objects.create(name='node-a', hostname='node-a.example.test')
self.headers = {'HTTP_AUTHORIZATION': f'Bearer {self.worker.token}', 'HTTP_X_WORKER_VERSION': '12'}
def write_exported_certificate(self, hostname):
host_dir = os.path.join(self.certificate_export_dir, hostname)
os.makedirs(host_dir, exist_ok=True)
with open(os.path.join(host_dir, 'certificate.crt'), 'w', encoding='utf-8') as certificate_file:
certificate_file.write(FAKE_CERTIFICATE)
with open(os.path.join(host_dir, 'certificate.key'), 'w', encoding='utf-8') as key_file:
key_file.write(FAKE_PRIVATE_KEY)
@override_settings(CLUSTER_WORKER_MINIMUM_VERSION=12, WIREGUARD_STATUS_CACHE_ENABLED=True)
class ClusterApiTests(ClusterTestMixin, TestCase):
def test_legacy_status_endpoint_stops_old_workers_without_token(self):
response = self.client.get('/api/cluster/status/')
self.assertEqual(response.status_code, 403)
self.assertEqual(response.json()['message'], 'update_required')
self.assertEqual(response.json()['minimum_worker_version'], 12)
def test_manifest_requires_token(self):
self.assertEqual(self.client.get('/api/cluster/v2/manifest/').status_code, 403)
response = self.client.get('/api/cluster/v2/manifest/', HTTP_AUTHORIZATION='Bearer not-a-uuid')
self.assertEqual(response.status_code, 403)
def test_worker_is_refused_with_reason(self):
scenarios = (
({'HTTP_X_WORKER_VERSION': '11'}, {}, 'update_required'),
({}, {'enabled': False}, 'worker_disabled'),
({}, {'ip_lock': True, 'ip_address': '203.0.113.10'}, 'ip_lock'),
)
for header_override, worker_fields, expected_error in scenarios:
with self.subTest(expected_error=expected_error):
Worker.objects.filter(pk=self.worker.pk).update(**{'enabled': True, 'ip_lock': False, **worker_fields})
response = self.client.get('/api/cluster/v2/manifest/', **{**self.headers, **header_override})
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()['message'], expected_error)
self.worker.refresh_from_db()
self.assertEqual(self.worker.error_status, expected_error)
def test_disabled_cluster_refuses_workers(self):
ClusterSettings.objects.filter(name='cluster_settings').update(enabled=False)
response = self.client.get('/api/cluster/v2/manifest/', **self.headers)
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json()['message'], 'cluster_disabled')
def test_manifest_hashes_match_sections(self):
response = self.client.get('/api/cluster/v2/manifest/', **self.headers)
self.assertEqual(response.status_code, 200)
manifest = response.json()['sections']
self.assertEqual(list(manifest), list(sync.SECTION_NAMES))
for section_name, section_hash in manifest.items():
with self.subTest(section=section_name):
section_response = self.client.get(f'/api/cluster/v2/section/{section_name}/', **self.headers)
self.assertEqual(section_response.status_code, 200)
self.assertEqual(section_response.json()['hash'], section_hash)
self.assertEqual(self.client.get('/api/cluster/v2/section/unknown/', **self.headers).status_code, 404)
def test_report_stores_worker_status(self):
report = {
'sections': {
'dns': {'hash': 'abc', 'status': 'error', 'message': 'dnsmasq failed'},
'unknown': {'hash': 'abc', 'status': 'ok'},
'settings': {'hash': 'def', 'status': 'invalid'},
},
'services': {'dnsmasq': 'running'},
'certificates': {'app.example.test': {'status': 'trusted'}},
'wireguard_status': {'wg0': {}},
}
response = self.client.post(
'/api/cluster/v2/report/', data=json.dumps(report), content_type='application/json', **self.headers
)
self.assertEqual(response.status_code, 200)
worker_status = WorkerStatus.objects.get(worker=self.worker)
self.assertEqual(list(worker_status.section_status), ['dns'])
self.assertEqual(worker_status.section_status['dns']['message'], 'dnsmasq failed')
self.assertEqual(worker_status.services_status, {'dnsmasq': 'running'})
self.assertEqual(worker_status.certificate_status, report['certificates'])
self.assertEqual(worker_status.wireguard_status, {'wg0': {}})
self.assertIsNotNone(worker_status.certificate_status_updated)
self.assertIsNotNone(worker_status.wireguard_status_updated)
def test_report_stores_gateway_sessions(self):
sessions = [
{'id': 'a' * 64, 'username': 'alice', 'factors': ['password'], 'online': True, 'session_id': 'secret'},
{'id': 'invalid', 'username': 'mallory'},
]
response = self.client.post(
'/api/cluster/v2/report/', data=json.dumps({'gateway_sessions': sessions}), content_type='application/json',
**self.headers
)
self.assertEqual(response.status_code, 200)
worker_status = WorkerStatus.objects.get(worker=self.worker)
self.assertEqual([session['id'] for session in worker_status.gateway_sessions], ['a' * 64])
self.assertNotIn('session_id', worker_status.gateway_sessions[0])
self.assertIsNotNone(worker_status.gateway_sessions_updated)
# A report without sessions (older worker or no change) keeps the last ones
self.client.post('/api/cluster/v2/report/', data=json.dumps({'services': {}}), content_type='application/json', **self.headers)
self.assertEqual(len(WorkerStatus.objects.get(worker=self.worker).gateway_sessions), 1)
class ClusterSyncTests(ClusterTestMixin, TestCase):
def report_sections(self, manifest, overrides=None):
section_status = {name: {'hash': section_hash, 'status': 'ok'} for name, section_hash in manifest.items()}
section_status.update(overrides or {})
WorkerStatus.objects.update_or_create(worker=self.worker, defaults={'section_status': section_status})
self.worker.refresh_from_db()
def test_sync_state(self):
manifest = sync.build_manifest(self.worker)
self.assertEqual(sync.get_worker_sync_state(self.worker, manifest)['state'], 'pending')
self.report_sections(manifest)
self.assertEqual(sync.get_worker_sync_state(self.worker, manifest)['state'], 'synced')
self.report_sections(manifest, {'dns': {'hash': manifest['dns'], 'status': 'error', 'message': 'failed'}})
sync_state = sync.get_worker_sync_state(self.worker, manifest)
self.assertEqual(sync_state['state'], 'error')
self.assertEqual(sync_state['sections']['dns']['message'], 'failed')
# An error reported for older content means the node still has to try the new one
self.report_sections(manifest, {'dns': {'hash': 'old', 'status': 'error', 'message': 'failed'}})
self.assertEqual(sync.get_worker_sync_state(self.worker, manifest)['state'], 'pending')
def test_wireguard_section_follows_config_files(self):
first_hash = sync.build_section('wireguard', self.worker).hash
self.assertEqual(sync.build_section('wireguard', self.worker).hash, first_hash)
with open(os.path.join(self.wireguard_dir, 'wg1.conf'), 'w', encoding='utf-8') as config_file:
config_file.write('[Interface]\nListenPort = 51821\n')
section = sync.build_section('wireguard', self.worker)
self.assertNotEqual(section.hash, first_hash)
self.assertEqual(sorted(section.files), ['wg0.conf', 'wg1.conf'])
def test_dns_section_uses_node_configuration(self):
section = sync.build_section('dns', self.worker)
main_config = section.files[sync.DNSMASQ_MAIN_CONFIG]
self.assertIn('bind-dynamic', main_config)
self.assertIn('interface=wg*', main_config)
self.assertNotIn('listen-address=0.0.0.0', main_config)
def test_firewall_section_is_stable_and_node_specific(self):
self.assertEqual(sync.build_section('firewall', self.worker).hash, sync.build_section('firewall', self.worker).hash)
node_script = generate_firewall_script(cluster_node=True)
primary_script = generate_firewall_script()
self.assertNotIn('DNS_IP', node_script)
self.assertNotIn('--dport 8000', node_script)
self.assertNotIn('generated by', node_script)
self.assertIn('DNS_IP', primary_script)
class ClusterGatewaySyncTests(ClusterTestMixin, TestCase):
def setUp(self):
super().setUp()
self.credential = DnsChallengeCredential.objects.create(
display_name='Cloudflare', provider='cloudflare', credentials={'api_token': 'x' * 40}
)
self.node_app = Application.objects.create(
display_name='Node App', upstream='http://10.0.0.20:8080', serve_on_primary=False
)
self.node_app.workers.add(self.worker)
ApplicationHost.objects.create(
application=self.node_app, hostname='node.example.test', certificate_type='dns_challenge',
dns_credential=self.credential,
)
def gateway_files(self):
return {
filename: json.loads(content)
for filename, content in sync.build_section('gateway', self.worker).files.items()
}
def test_primary_manages_certificates_of_worker_only_applications(self):
export_caddy_config(self.export_dir)
with open(os.path.join(self.export_dir, 'applications.json'), encoding='utf-8') as applications_file:
primary_applications = json.load(applications_file)
with open(os.path.join(self.export_dir, 'tls.json'), encoding='utf-8') as tls_file:
primary_tls = json.load(tls_file)
self.assertNotIn('node-app', [entry['id'] for entry in primary_applications['entries']])
host_tls = primary_tls['hosts']['node.example.test']
self.assertTrue(host_tls['certificate_only'])
self.assertTrue(host_tls['export_certificate'])
self.assertEqual(host_tls['dns_credential'], self.credential.name)
def test_workers_only_publish_exported_configuration(self):
self.assertEqual(self.gateway_files()['applications.json'], {'entries': []})
export_caddy_config(self.export_dir)
self.assertEqual([entry['id'] for entry in self.gateway_files()['applications.json']['entries']], ['node-app'])
self.node_app.upstream = 'http://10.0.0.21:8080'
self.node_app.save()
self.assertTrue(caddy_config_export.has_pending_export(self.export_dir))
self.assertEqual(self.gateway_files()['applications.json']['entries'][0]['upstream'], 'http://10.0.0.20:8080')
export_caddy_config(self.export_dir)
self.assertFalse(caddy_config_export.has_pending_export(self.export_dir))
self.assertEqual(self.gateway_files()['applications.json']['entries'][0]['upstream'], 'http://10.0.0.21:8080')
def test_worker_receives_exported_certificate_without_dns_credentials(self):
export_caddy_config(self.export_dir)
worker_tls = self.gateway_files()['tls.json']
self.assertEqual(worker_tls['dns_credentials'], {})
self.assertEqual(worker_tls['hosts']['node.example.test']['certificate_file'], '')
self.assertEqual(sync.build_section('certificates', self.worker).files, {})
# A renewed certificate reaches the worker without a new export
self.write_exported_certificate('node.example.test')
certificate_name = certificate_file_name(FAKE_CERTIFICATE)
self.assertEqual(self.gateway_files()['tls.json']['hosts']['node.example.test']['certificate_file'], certificate_name)
self.assertEqual(sync.build_section('certificates', self.worker).files, {
f'{certificate_name}.crt': FAKE_CERTIFICATE,
f'{certificate_name}.key': FAKE_PRIVATE_KEY,
})
def test_new_worker_is_pending_until_exported(self):
export_caddy_config(self.export_dir)
self.assertFalse(caddy_config_export.has_pending_export(self.export_dir))
Worker.objects.create(name='node-b')
self.assertTrue(caddy_config_export.has_pending_export(self.export_dir))
class ClusterTrafficAggregationTests(TestCase):
def test_peer_traffic_is_summed_across_servers(self):
worker = Worker.objects.create(name='node-a')
WorkerStatus.objects.create(
worker=worker, wireguard_status_updated=timezone.now(), wireguard_status={'wg0': {
'PEER': {'transfer': {'tx': 5000, 'rx': 500}, 'latest-handshakes': '2000', 'endpoints': 'node:1'},
'NODE_ONLY': {'transfer': {'tx': 7, 'rx': 3}, 'latest-handshakes': '5'},
}},
)
WireguardStatusCache.objects.create(cache_type='master', processing_time_ms=0, data={'wg0': {
'PEER': {'transfer': {'tx': 100, 'rx': 10}, 'latest-handshakes': '1000', 'endpoints': 'primary:1'},
}})
func_concatenate_cluster_wireguard_status_cache()
combined = WireguardStatusCache.objects.filter(cache_type='cluster').latest('created').data['wg0']
self.assertEqual(combined['PEER']['transfer'], {'tx': 5100, 'rx': 510})
self.assertEqual(combined['PEER']['endpoints'], 'node:1')
self.assertEqual(combined['PEER']['source_name'], 'worker_node-a')
self.assertEqual(combined['NODE_ONLY']['transfer'], {'tx': 7, 'rx': 3})
def create_instance(instance_id, worker=None):
return WireGuardInstance.objects.create(
instance_id=instance_id, private_key=f'private-{instance_id}', public_key=f'public-{instance_id}',
hostname='primary.example.test', listen_port=51820 + instance_id, address=f'10.188.{instance_id}.1',
worker=worker,
)
@override_settings(WIREGUARD_STATUS_CACHE_ENABLED=True)
class DistributedModeTests(ClusterTestMixin, TestCase):
"""wg0 runs on the primary server, wg1 on node-a and node-b runs no instance."""
def setUp(self):
super().setUp()
self.cluster_wireguard_dir = os.path.join(self.wireguard_dir, 'cluster')
for target, value in (
('cluster.sync.CLUSTER_WIREGUARD_CONFIG_DIR', self.cluster_wireguard_dir),
('wireguard_tools.functions.WIREGUARD_CONFIG_DIR', self.wireguard_dir),
('wireguard_tools.functions.CLUSTER_WIREGUARD_CONFIG_DIR', self.cluster_wireguard_dir),
('wireguard_tools.views.WIREGUARD_CONFIG_DIR', self.wireguard_dir),
('wireguard_tools.views.CLUSTER_WIREGUARD_CONFIG_DIR', self.cluster_wireguard_dir),
):
patcher = patch(target, value)
patcher.start()
self.addCleanup(patcher.stop)
self.worker_b = Worker.objects.create(name='node-b', hostname='node-b.example.test')
self.primary_instance = create_instance(0)
self.worker_instance = create_instance(1, worker=self.worker)
ClusterSettings.objects.filter(name='cluster_settings').update(cluster_mode='distributed')
def set_mode(self, enabled=True, cluster_mode='distributed'):
ClusterSettings.objects.filter(name='cluster_settings').update(enabled=enabled, cluster_mode=cluster_mode)
def create_peer(self, instance):
peer = Peer.objects.create(
name=f'peer-wg{instance.instance_id}', public_key=f'peer-public-{instance.instance_id}',
pre_shared_key='', private_key=f'peer-private-{instance.instance_id}', wireguard_instance=instance,
)
PeerAllowedIP.objects.create(
peer=peer, priority=0, allowed_ip=f'10.188.{instance.instance_id}.10', netmask=32, config_file='server'
)
return peer
def test_hosting_worker_only_in_distributed_mode(self):
self.assertTrue(ClusterSettings.is_distributed())
self.assertEqual(self.worker_instance.hosting_worker, self.worker)
self.assertIsNone(self.primary_instance.hosting_worker)
self.set_mode(cluster_mode='mirror')
self.assertIsNone(WireGuardInstance.objects.get(instance_id=1).hosting_worker)
self.set_mode(enabled=False)
self.assertFalse(ClusterSettings.is_distributed())
self.assertIsNone(WireGuardInstance.objects.get(instance_id=1).hosting_worker)
def test_export_places_configs_by_server(self):
FirewallSettings.objects.update_or_create(name='global', defaults={'instance_to_execute_firewall': self.worker_instance})
export_wireguard_configuration()
self.assertEqual(sorted(os.listdir(self.cluster_wireguard_dir)), ['wg1.conf'])
self.assertIn('wg0.conf', os.listdir(self.wireguard_dir))
self.assertNotIn('wg1.conf', os.listdir(self.wireguard_dir))
# The firewall script must run from an instance of the primary server
self.assertEqual(FirewallSettings.objects.get(name='global').instance_to_execute_firewall, self.primary_instance)
with open(os.path.join(self.wireguard_dir, 'wg0.conf'), encoding='utf-8') as config_file:
self.assertIn('PostUp = /etc/wireguard/wg-firewall.sh', config_file.read())
# Moving a single instance back to the primary server removes it from the cluster directory
WireGuardInstance.objects.filter(instance_id=1).update(worker=None)
export_wireguard_configuration(WireGuardInstance.objects.get(instance_id=1))
self.assertIn('wg1.conf', os.listdir(self.wireguard_dir))
self.assertEqual(os.listdir(self.cluster_wireguard_dir), [])
def test_wireguard_section_only_has_worker_instances(self):
export_wireguard_configuration()
self.assertEqual(sorted(sync.build_section('wireguard', self.worker).files), ['wg1.conf'])
self.assertEqual(sync.build_section('wireguard', self.worker_b).files, {})
self.set_mode(cluster_mode='mirror')
export_wireguard_configuration()
self.assertEqual(sorted(sync.build_section('wireguard', self.worker_b).files), ['wg0.conf', 'wg1.conf'])
def test_port_forwards_only_on_instance_server(self):
RedirectRule.objects.create(port=8081, wireguard_instance=self.worker_instance, ip_address='10.188.1.10')
RedirectRule.objects.create(port=8082, wireguard_instance=self.primary_instance, ip_address='10.188.0.10')
worker_script = generate_firewall_script(cluster_node=True, worker=self.worker)
other_worker_script = generate_firewall_script(cluster_node=True, worker=self.worker_b)
primary_script = generate_firewall_script()
self.assertIn('--dport 8081', worker_script)
self.assertNotIn('--dport 8082', worker_script)
self.assertNotIn('--dport 808', other_worker_script)
self.assertIn('--dport 8082', primary_script)
self.assertNotIn('--dport 8081', primary_script)
self.set_mode(cluster_mode='mirror')
self.assertIn('--dport 8082', generate_firewall_script(cluster_node=True, worker=self.worker_b))
def test_activation_blocked_by_instance_interface_rules(self):
self.set_mode(cluster_mode='mirror')
FirewallRule.objects.create(description='wg0 to internet', in_interface='wg0', out_interface='eth0')
cluster_settings = ClusterSettings.objects.get(name='cluster_settings')
data = {'enabled': True, 'primary_enable_wireguard': True, 'cluster_mode': 'distributed', 'worker_display': 'name'}
form = ClusterSettingsForm(data=data, instance=cluster_settings)
self.assertFalse(form.is_valid())
self.assertIn('wg0 to internet', str(form.non_field_errors()))
FirewallRule.objects.update(in_interface='wg+')
self.assertTrue(ClusterSettingsForm(data=data, instance=cluster_settings).is_valid())
def test_firewall_rule_form_rejects_instance_interface(self):
def rule_form(in_interface):
return FirewallRuleForm(data={
'firewall_chain': 'forward', 'in_interface': in_interface, 'out_interface': '', 'rule_action': 'accept',
'source_netmask': 32, 'destination_netmask': 32, 'protocol': '', 'sort_order': 10,
})
form = rule_form('wg0')
self.assertFalse(form.is_valid())
self.assertIn('distributed cluster mode', str(form.non_field_errors()))
self.assertTrue(rule_form('wg+').is_valid())
self.set_mode(cluster_mode='mirror')
self.assertTrue(rule_form('wg0').is_valid())
def test_peer_config_uses_instance_server(self):
worker_peer = self.create_peer(self.worker_instance)
primary_peer = self.create_peer(self.primary_instance)
self.assertIn('Endpoint = node-a.example.test:51821', generate_peer_config(worker_peer.uuid))
# A server picked for another worker is ignored: the instance only runs on node-a
self.assertIn(
'Endpoint = node-a.example.test:51821',
generate_peer_config(worker_peer.uuid, server_address='node-b.example.test:51821'),
)
self.assertIn('Endpoint = primary.example.test:51820', generate_peer_config(primary_peer.uuid))
self.assertEqual(get_config_servers(self.worker_instance), [{'name': 'node-a.example.test', 'uuid': str(self.worker.uuid)}])
self.assertEqual([server['uuid'] for server in get_config_servers(self.primary_instance)], [''])
self.set_mode(cluster_mode='mirror')
self.assertEqual(len(get_config_servers(self.worker_instance)), 3)
def test_worker_with_instances_cannot_be_deleted(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)
response = self.client.get(f'/cluster/worker/manage/?uuid={self.worker.uuid}&action=delete&confirmation=delete')
self.assertRedirects(response, f'/cluster/worker/view/?uuid={self.worker.uuid}', fetch_redirect_response=False)
self.assertTrue(Worker.objects.filter(pk=self.worker.pk).exists())
self.client.get(f'/cluster/worker/manage/?uuid={self.worker_b.uuid}&action=delete&confirmation=delete')
self.assertFalse(Worker.objects.filter(pk=self.worker_b.pk).exists())
class AgentGatewaySessionsTests(TestCase):
"""Sessions of the node auth-gateway are reported when they change, and revocations reach its config."""
@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
self.sessions_file = os.path.join(self.gateway_dir, 'state', 'sessions.json')
os.makedirs(os.path.dirname(self.sessions_file))
for name, value in (
('GATEWAY_DIR', self.gateway_dir),
('GATEWAY_SESSIONS_FILE', self.sessions_file),
('gateway_enabled', lambda: True),
('wireguard_status', lambda: {}),
):
patcher = patch.object(self.cluster_worker, name, value)
patcher.start()
self.addCleanup(patcher.stop)
for name in ('services_status', 'certificates_status'):
patcher = patch.object(self.cluster_worker.ClusterNodeAgent, name, staticmethod(lambda: {}))
patcher.start()
self.addCleanup(patcher.stop)
self.agent = self.cluster_worker.ClusterNodeAgent()
self.reports = []
self.status_code = 200
self.agent.request = self.record_report
def record_report(self, method, path, json=None):
self.reports.append(json)
return type('Response', (), {'status_code': self.status_code})()
def publish(self, sessions):
with open(self.sessions_file, 'w', encoding='utf-8') as sessions_file:
sessions_file.write(json.dumps({'sessions': sessions}))
def test_sessions_are_only_reported_when_they_change(self):
self.publish([{'id': 'a' * 64}])
self.agent.send_stats()
self.agent.send_stats()
self.publish([])
self.agent.send_stats()
self.assertEqual([report.get('gateway_sessions') for report in self.reports], [[{'id': 'a' * 64}], None, []])
def test_sessions_are_reported_again_when_the_primary_did_not_accept_them(self):
self.publish([{'id': 'a' * 64}])
self.status_code = 500
self.agent.send_stats()
self.status_code = 200
self.agent.send_stats()
self.agent.send_stats()
self.assertEqual(['gateway_sessions' in report for report in self.reports], [True, True, False])
def test_no_sessions_file_reports_nothing(self):
self.agent.send_stats()
self.assertNotIn('gateway_sessions', self.reports[0])
def test_revoked_sessions_are_written_when_sent(self):
files = {name: '{}' for name in self.cluster_worker.GATEWAY_FILES}
self.agent.apply_gateway({'files': files})
self.assertFalse(os.path.exists(os.path.join(self.gateway_dir, 'revoked_sessions.json')))
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))
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.functions.subprocess.run', run), \
patch('wireguard_tools.views.os.path.isfile', lambda path: path.endswith('/wg0.conf')), \
patch('wireguard_tools.functions.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, '')
+5 -7
View File
@@ -1,12 +1,10 @@
from django.urls import path
from cluster.cluster_api import api_cluster_status, api_get_worker_config_files, api_get_worker_dnsmasq_config, \
api_worker_ping, api_submit_worker_wireguard_stats
from cluster.cluster_api import api_legacy_cluster_status, api_manifest, api_report, api_section
urlpatterns = [
path('status/', api_cluster_status, name='api_cluster_status'),
path('worker/get_config_files/', api_get_worker_config_files, name='api_get_worker_config_files'),
path('worker/get_dnsmasq_config/', api_get_worker_dnsmasq_config, name='api_get_worker_dnsmasq_config'),
path('worker/ping/', api_worker_ping, name='api_worker_ping'),
path('worker/submit_wireguard_stats/', api_submit_worker_wireguard_stats, name='api_submit_worker_wireguard_stats'),
path('status/', api_legacy_cluster_status, name='api_legacy_cluster_status'),
path('v2/manifest/', api_manifest, name='api_cluster_manifest'),
path('v2/section/<str:section_name>/', api_section, name='api_cluster_section'),
path('v2/report/', api_report, name='api_cluster_report'),
]
+2 -1
View File
@@ -1,9 +1,10 @@
from django.urls import path
from cluster.views import cluster_main, cluster_settings, worker_manage
from cluster.views import cluster_main, cluster_settings, worker_details, worker_manage
urlpatterns = [
path('', cluster_main, name='cluster_main'),
path('worker/view/', worker_details, name='worker_details'),
path('worker/manage/', worker_manage, name='worker_manage'),
path('settings/', cluster_settings, name='cluster_settings'),
]
+165 -60
View File
@@ -1,34 +1,92 @@
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db.models import ProtectedError
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils.dateparse import parse_datetime
from django.utils.translation import gettext_lazy as _
from api.models import WireguardStatusCache
from dns.functions import compress_dnsmasq_config
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
from wireguard_tools.views import export_firewall_configuration, export_wireguard_configuration
from .forms import WorkerForm, ClusterSettingsForm
from .models import ClusterSettings, Worker
from .models import ClusterSettings, Worker, WorkerStatus
from .sync import SECTION_NAMES, get_worker_sync_state, get_worker_warnings
def get_worker_status(worker):
try:
return worker.workerstatus
except WorkerStatus.DoesNotExist:
return None
def describe_worker(worker):
"""Attach the synchronization state, warnings and reported data used by the cluster templates."""
worker.sync_state = get_worker_sync_state(worker)
worker.unsynced_sections = [
section_name for section_name, section in worker.sync_state['sections'].items() if section['state'] != 'synced'
]
worker.error_messages = [
f"{section_name}: {section['message']}" for section_name, section in worker.sync_state['sections'].items()
if section['state'] == 'error' and section['message']
]
worker.warnings = get_worker_warnings(worker)
# Reported data of disabled, refused or offline workers is only the last known state
worker.operational = worker.enabled and not worker.error_status and worker.is_online
worker_status = get_worker_status(worker)
worker.status = worker_status
worker.services = sorted((worker_status.services_status or {}).items()) if worker_status else []
worker.runs_gateway = any(service == 'caddy' for service, state in worker.services)
worker.outdated = bool(worker_status and worker_status.worker_version != settings.CLUSTER_WORKER_CURRENT_VERSION)
# WireGuard instances that run only on this worker (distributed cluster mode)
worker.hosted_instances = (
list(worker.wireguard_instances.order_by('instance_id')) if ClusterSettings.is_distributed() else []
)
return worker
@login_required
def cluster_main(request):
"""Main cluster page with workers list"""
if not UserAcl.objects.filter(user=request.user).filter(user_level__gte=50).exists():
return render(request, 'access_denied.html', {'page_title': _('Access Denied')})
cluster_settings, created = ClusterSettings.objects.get_or_create(name='cluster_settings')
page_title = _('Cluster')
workers = Worker.objects.all().order_by('name')
cluster_settings, cluster_settings_created = ClusterSettings.objects.get_or_create(name='cluster_settings')
workers = [describe_worker(worker) for worker in Worker.objects.all().select_related('workerstatus').order_by('name')]
enabled_workers = [worker for worker in workers if worker.enabled]
master_cache_times = ", ".join([str(c.processing_time_ms) for c in WireguardStatusCache.objects.filter(cache_type='master').order_by('-created')])
cluster_cache_times = ", ".join([str(c.processing_time_ms) for c in WireguardStatusCache.objects.filter(cache_type='cluster').order_by('-created')])
master_cache_times = ", ".join(
str(cache.processing_time_ms) for cache in WireguardStatusCache.objects.filter(cache_type='master').order_by('-created')
)
cluster_cache_times = ", ".join(
str(cache.processing_time_ms) for cache in WireguardStatusCache.objects.filter(cache_type='cluster').order_by('-created')
)
context = {
'page_title': page_title,
'page_title': _('Cluster'),
'workers': workers,
'current_worker_version': settings.CLUSTER_WORKER_CURRENT_VERSION,
'cluster_settings': cluster_settings,
'current_worker_version': settings.CLUSTER_WORKER_CURRENT_VERSION,
'distributed': ClusterSettings.is_distributed(),
'primary_instances': WireGuardInstance.objects.filter(worker__isnull=True).order_by('instance_id'),
# Instances that no server runs: their worker is disabled
'stopped_instances': [
instance for worker in workers if not worker.enabled for instance in worker.hosted_instances
],
'summary': {
'enabled': len(enabled_workers),
'online': sum(1 for worker in enabled_workers if worker.operational),
'synced': sum(1 for worker in enabled_workers if worker.operational and worker.sync_state['state'] == 'synced'),
'attention': sum(
1 for worker in enabled_workers
if worker.sync_state['state'] == 'error' or worker.error_status or worker.warnings['stopped_services']
or worker.warnings['certificate_issues'] or not worker.is_online
),
},
'cache_refresh_interval': settings.WIREGUARD_STATUS_CACHE_REFRESH_INTERVAL,
'cache_enabled': settings.WIREGUARD_STATUS_CACHE_ENABLED,
'cache_web_load_previous_count': settings.WIREGUARD_STATUS_CACHE_WEB_LOAD_PREVIOUS_COUNT,
@@ -38,62 +96,106 @@ def cluster_main(request):
return render(request, 'cluster/workers_list.html', context)
@login_required
def worker_details(request):
if not UserAcl.objects.filter(user=request.user).filter(user_level__gte=50).exists():
return render(request, 'access_denied.html', {'page_title': _('Access Denied')})
worker = describe_worker(get_object_or_404(Worker.objects.select_related('workerstatus'), uuid=request.GET.get('uuid')))
cluster_settings, cluster_settings_created = ClusterSettings.objects.get_or_create(name='cluster_settings')
sections = []
for section_name in SECTION_NAMES:
section_state = worker.sync_state['sections'].get(section_name, {})
reported = (worker.status.section_status or {}).get(section_name, {}) if worker.status else {}
sections.append({
'name': section_name,
'state': section_state.get('state', 'pending'),
'message': section_state.get('message', ''),
'updated': parse_datetime(reported.get('updated', '')) if reported.get('updated') else None,
})
certificates = []
if worker.status:
for hostname, certificate in sorted((worker.status.certificate_status or {}).items()):
certificates.append({
'hostname': hostname,
'status': certificate.get('status', ''),
'issuer': certificate.get('issuer', ''),
'not_after': parse_datetime(certificate['not_after']) if certificate.get('not_after') else None,
})
webadmin_hostnames = get_webadmin_hostnames()
primary_address = f"https://{webadmin_hostnames[0] if webadmin_hostnames else request.get_host()}"
context = {
'page_title': worker.name,
'worker': worker,
'cluster_settings': cluster_settings,
'current_worker_version': settings.CLUSTER_WORKER_CURRENT_VERSION,
'distributed': ClusterSettings.is_distributed(),
'sections': sections,
'certificates': certificates,
'primary_address': primary_address,
'time_zone': settings.TIME_ZONE,
}
return render(request, 'cluster/worker_details.html', context)
@login_required
def worker_manage(request):
"""Add/Edit worker view"""
if not UserAcl.objects.filter(user=request.user).filter(user_level__gte=50).exists():
return render(request, 'access_denied.html', {'page_title': _('Access Denied')})
worker = None
if 'uuid' in request.GET:
worker = get_object_or_404(Worker, uuid=request.GET['uuid'])
form = WorkerForm(instance=worker)
page_title = _('Edit Worker: ') + worker.name
if request.GET.get('action') == 'delete':
worker_name = worker.name
if request.GET.get('confirmation') == 'delete':
try:
worker.delete()
messages.success(request, _('Worker deleted|Worker deleted: ') + worker_name)
return redirect('/cluster/')
except ProtectedError:
messages.warning(request, _(
'Worker not deleted|Move the WireGuard instances of this worker to another server first: '
) + ', '.join(str(instance) for instance in worker.wireguard_instances.all()))
return redirect(reverse('worker_details') + f'?uuid={worker.uuid}')
else:
messages.warning(request, _('Worker not deleted|Invalid confirmation.'))
return redirect('/cluster/')
return redirect(reverse('cluster_main'))
else:
form = WorkerForm()
page_title = _('Add Worker')
if request.method == 'POST':
if worker:
form = WorkerForm(request.POST, instance=worker)
else:
form = WorkerForm(request.POST)
form = WorkerForm(request.POST or None, instance=worker)
if form.is_valid():
is_new_worker = worker is None
worker = form.save()
if worker.pk:
messages.success(request, _('Worker updated|Worker updated: ') + worker.name)
else:
if is_new_worker:
messages.success(request, _('Worker created|Worker created: ') + worker.name)
return redirect('/cluster/')
else:
messages.success(request, _('Worker updated|Worker updated: ') + worker.name)
return redirect(reverse('worker_details') + f'?uuid={worker.uuid}')
form_description = {
'size': 'col-lg-6',
'content': _('''
<h5>Worker Configuration</h5>
<p>Configure a cluster worker node that will synchronize with this primary instance.</p>
<h5>Worker</h5>
<p>A worker is a cluster node that replicates WireGuard, firewall and DNS from this primary server and, optionally, publishes App Gateway applications.</p>
<h5>Name</h5>
<p>A unique name to identify this worker.</p>
<h5>Name and location</h5>
<p>Used to identify the worker. The <strong>hostname</strong> is the address clients use to connect to this worker: it is written as the endpoint of the peer configurations downloaded for this server.</p>
<h5>IP Address</h5>
<p>The IP address of the worker node. Leave empty if IP lock is disabled.</p>
<h5>Token</h5>
<p>Secret used by the worker to authenticate with this primary server. Changing it disconnects the worker until its configuration is updated.</p>
<h5>IP Lock</h5>
<p>When enabled, the worker can only connect from the specified IP address.</p>
<h5>IP lock</h5>
<p>When enabled, the worker is only accepted from the IP address below. Without it, the address is updated automatically from the last connection.</p>
<h5>Location Information</h5>
<p>Optional location details for this worker (country, city, hostname).</p>
<h5>Enabled</h5>
<p>Disabled workers are refused and shut down their WireGuard interfaces until enabled again.</p>
''')
}
@@ -102,56 +204,59 @@ def worker_manage(request):
'form': form,
'worker': worker,
'instance': worker,
'form_description': form_description
'form_description': form_description,
}
return render(request, 'generic_form.html', context)
@login_required
def cluster_settings(request):
"""Cluster settings configuration"""
if not UserAcl.objects.filter(user=request.user).filter(user_level__gte=50).exists():
return render(request, 'access_denied.html', {'page_title': _('Access Denied')})
cluster_settings, created = ClusterSettings.objects.get_or_create(name='cluster_settings')
page_title = _('Cluster Settings')
cluster_settings, cluster_settings_created = ClusterSettings.objects.get_or_create(name='cluster_settings')
if request.method == 'POST':
form = ClusterSettingsForm(request.POST, instance=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():
form.save()
cluster_settings = form.save()
messages.success(request, _('Cluster settings updated successfully.'))
if cluster_settings.enabled:
if cluster_settings.config_version == 0:
cluster_settings.config_version += 1
cluster_settings.save()
compress_dnsmasq_config()
return redirect('/cluster/')
else:
form = ClusterSettingsForm(instance=cluster_settings)
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
export_wireguard_configuration()
export_firewall_configuration()
WireGuardInstance.objects.update(pending_changes=True)
return redirect(reverse('cluster_main'))
form_description = {
'size': 'col-lg-6',
'content': _('''
<h5>Cluster Enabled</h5>
<p>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.</p>
<h5>Primary Enable WireGuard</h5>
<p>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.</p>
<h5>Cluster Mode</h5>
<p>Configure how the cluster operates and synchronizes configurations between nodes.</p>
<h5>Sync Intervals</h5>
<p>Configure how frequently statistics and cache data are synchronized between cluster nodes.</p>
<h5>Restart Mode</h5>
<p>Choose whether WireGuard services should be automatically restarted when configurations change, or if manual intervention is required.</p>
<p><strong>Mirror</strong>: every worker receives the same WireGuard instances, peers, firewall and DNS configuration. Peers can connect to any server.</p>
<p><strong>Distributed</strong>: each WireGuard instance runs only on the server selected in the instance settings (the primary server by default). Peers connect to that server. Firewall rules cannot be bound to a specific instance interface: use wg+ or IP addresses. After changing the mode, apply the WireGuard configuration so the primary server stops the instances that moved to workers.</p>
<h5>Worker Display</h5>
<p>Select how workers should be identified in the interface - by name, server address, location, or a combination.</p>
<p>How workers are named in server selections (peer configuration downloads and VPN invites).</p>
''')
}
context = {
'page_title': page_title,
'page_title': _('Cluster Settings'),
'form': form,
'cluster_settings': cluster_settings,
'instance': cluster_settings,
'form_description': form_description
'form_description': form_description,
}
return render(request, 'generic_form.html', context)
@@ -1,12 +1,10 @@
FROM python:3.12-alpine
FROM python:3.14-slim
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
WORKDIR /app
RUN apk add --no-cache bash
COPY requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r /app/requirements.txt
@@ -96,9 +96,16 @@ def load_runtime_config(config_dir: Path) -> RuntimeConfig:
users=auth.users,
groups=auth.groups,
policies=auth.policies,
revoked_sessions=_load_revoked_sessions(config_dir),
)
def _load_revoked_sessions(config_dir: Path) -> set[str]:
payload = _load_json(config_dir / "revoked_sessions.json") or {}
sessions = payload.get("sessions", []) if isinstance(payload, dict) else []
return {value for value in sessions if isinstance(value, str)}
class RuntimeConfigStore:
def __init__(self, config_dir: Path):
self.config_dir = config_dir
@@ -112,6 +119,7 @@ class RuntimeConfigStore:
"applications.json",
"routes.json",
"auth_policies.json",
"revoked_sessions.json",
):
path = self.config_dir / filename
if path.exists():
@@ -1,14 +1,40 @@
import ipaddress
from fastapi import Request
from slowapi import Limiter
AUTH_RATE_LIMIT = "5/minute"
def _is_trusted_proxy(peer: str) -> bool:
"""Caddy reaches the gateway over a Docker network, so only private and loopback peers can forward the client."""
try:
address = ipaddress.ip_address(peer)
except ValueError:
return False
return address.is_private or address.is_loopback
def get_real_client_ip(request: Request) -> str:
peer = request.client.host if request.client else ""
forwarded_for = request.headers.get("x-forwarded-for", "")
if forwarded_for:
if forwarded_for and _is_trusted_proxy(peer):
return forwarded_for.split(",")[0].strip()
return request.client.host if request.client else "unknown"
return peer or "unknown"
limiter = Limiter(key_func=get_real_client_ip)
def get_rate_limit_key(request: Request) -> str:
"""Client address used by the rate limit. IPv6 clients usually own a whole /64, so it counts as one address."""
client = get_real_client_ip(request)
try:
address = ipaddress.ip_address(client)
except ValueError:
return client
if address.version == 6:
if address.ipv4_mapped:
return str(address.ipv4_mapped)
return str(ipaddress.ip_network(f"{address}/64", strict=False))
return str(address)
limiter = Limiter(key_func=get_rate_limit_key)
+27 -10
View File
@@ -1,23 +1,26 @@
import asyncio
import logging
import time
from contextlib import asynccontextmanager
from pathlib import Path
from auth_gateway.config_loader import RuntimeConfigStore
from auth_gateway.limiter import get_real_client_ip, limiter
from auth_gateway.services.oidc_service import OIDCService
from auth_gateway.services.session_service import SessionService
from auth_gateway.settings import settings
from auth_gateway.storage.sqlite import SQLiteStorage
from auth_gateway.web.auth_routes import router as auth_router
from auth_gateway.web.challenge_routes import router as challenge_router
from auth_gateway.web.login_routes import router as login_router
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from slowapi.errors import RateLimitExceeded
from auth_gateway.config_loader import RuntimeConfigStore
from auth_gateway.limiter import get_real_client_ip, limiter
from auth_gateway.services.oidc_service import OIDCService
from auth_gateway.services.session_service import SessionService
from auth_gateway.services.session_snapshot import SNAPSHOT_INTERVAL_SECONDS, SessionSnapshot
from auth_gateway.settings import settings
from auth_gateway.storage.sqlite import SQLiteStorage
from auth_gateway.web.auth_routes import router as auth_router
from auth_gateway.web.challenge_routes import router as challenge_router
from auth_gateway.web.login_routes import router as login_router
BASE_DIR = Path(__file__).resolve().parent
_access_logger = logging.getLogger("uvicorn.error")
@@ -30,7 +33,20 @@ async def lifespan(app: FastAPI):
app.state.session_service = SessionService(storage, settings.session_default_minutes, settings.oidc_state_ttl_minutes)
app.state.oidc_service = OIDCService()
app.state.templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
app.state.session_snapshot = SessionSnapshot(storage, app.state.config_store, settings.config_dir / "state" / "sessions.json")
snapshot_task = asyncio.create_task(_refresh_session_snapshot(app.state.session_snapshot))
yield
snapshot_task.cancel()
async def _refresh_session_snapshot(session_snapshot: SessionSnapshot):
# Sessions also end without a request (expiration, revocation, changed credentials) and go offline over time
while True:
try:
await asyncio.to_thread(session_snapshot.refresh)
except Exception as error:
_access_logger.warning("Session snapshot failed: %s", error)
await asyncio.sleep(SNAPSHOT_INTERVAL_SECONDS)
app = FastAPI(
@@ -59,8 +75,9 @@ async def _rate_limit_handler(request: Request, exc: RateLimitExceeded) -> HTMLR
templates = request.app.state.templates
external_path = request.app.state.settings.external_path
return templates.TemplateResponse(
request,
"ratelimit.html",
{"request": request, "external_path": external_path, "back_url": str(request.url.path)},
{"external_path": external_path, "back_url": str(request.url.path)},
status_code=429,
)
@@ -1,7 +1,8 @@
from pydantic import BaseModel, Field
from auth_gateway.models.applications import ApplicationModel
from auth_gateway.models.auth import AuthMethodModel, GroupModel, PolicyModel, UserModel
from auth_gateway.models.routes import AppRoutesModel
from pydantic import BaseModel, Field
class RuntimeConfig(BaseModel):
@@ -11,3 +12,5 @@ class RuntimeConfig(BaseModel):
users: dict[str, UserModel] = Field(default_factory=dict)
groups: dict[str, GroupModel] = Field(default_factory=dict)
policies: dict[str, PolicyModel] = Field(default_factory=dict)
# sha256 of the IDs of sessions ended from the WireGuard WebAdmin
revoked_sessions: set[str] = Field(default_factory=set)
@@ -8,6 +8,8 @@ import time
ALTCHA_MAX_NUMBER = 1_000_000
CHALLENGE_TTL_SECONDS = 300 # 5 minutes
CHALLENGE_COOKIE_NAME = "auth_gateway_challenge"
# Nonces of challenge cookies revoked after a failed login: a script keeping the old cookie must solve a new challenge
_revoked_nonces: dict[str, float] = {}
def generate_altcha_challenge(hmac_key: str) -> dict:
@@ -63,7 +65,20 @@ def verify_challenge_cookie(cookie_value: str, secret: str) -> bool:
expected_sig = hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected_sig, sig):
return False
timestamp = int(message.split(".")[0])
return (time.time() - timestamp) < CHALLENGE_TTL_SECONDS
timestamp, nonce = message.split(".")
if nonce in _revoked_nonces:
return False
return (time.time() - int(timestamp)) < CHALLENGE_TTL_SECONDS
except Exception:
return False
def revoke_challenge_cookie(cookie_value: str | None) -> None:
"""Make a challenge cookie invalid before it expires."""
now = time.time()
for nonce, revoked_at in list(_revoked_nonces.items()):
if now - revoked_at > CHALLENGE_TTL_SECONDS:
del _revoked_nonces[nonce]
parts = (cookie_value or "").split(".")
if len(parts) == 3 and parts[1]:
_revoked_nonces[parts[1]] = now
@@ -1,8 +1,9 @@
from dataclasses import dataclass
from auth_gateway.models.auth import OIDCMethodModel
from authlib.integrations.starlette_client import OAuth
from auth_gateway.models.auth import OIDCMethodModel
@dataclass
class OIDCIdentity:
@@ -45,6 +46,9 @@ class OIDCService:
if "userinfo" in token and isinstance(token["userinfo"], dict):
claims.update(token["userinfo"])
email = claims.get("email")
# An email the provider did not verify can be set by the user, so it must not pass the allowlists
if str(claims.get("email_verified", True)).lower() == "false":
email = None
subject = claims.get("sub")
return OIDCIdentity(subject=subject, email=email, claims=claims)
@@ -1,10 +1,11 @@
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
from argon2.exceptions import InvalidHashError, VerifyMismatchError
from auth_gateway.models.auth import UserModel
password_hasher = PasswordHasher()
# Checked when the user does not exist, so the response time does not reveal which usernames exist
DUMMY_PASSWORD_HASH = password_hasher.hash("unused-password")
MAX_PASSWORD_LENGTH = 1024
@@ -14,10 +15,9 @@ def verify_user_password(username: str, password: str, users: dict[str, UserMode
if not password or len(password) > MAX_PASSWORD_LENGTH:
return None
user = users.get(username)
if not user or not user.password_hash:
return None
password_hash = user.password_hash if user and user.password_hash else DUMMY_PASSWORD_HASH
try:
password_hasher.verify(user.password_hash, password)
except VerifyMismatchError:
password_hasher.verify(password_hash, password)
except (VerifyMismatchError, InvalidHashError):
return None
return user
return user if password_hash is not DUMMY_PASSWORD_HASH else None
@@ -1,6 +1,7 @@
import posixpath
import re
from dataclasses import dataclass
from urllib.parse import unquote, urlsplit
from urllib.parse import unquote
from auth_gateway.models.applications import ApplicationModel
from auth_gateway.models.routes import AppRoutesModel, RoutePolicyBindingModel
@@ -21,16 +22,22 @@ def normalize_host(raw_host: str) -> str:
def normalize_path(raw_uri: str) -> str:
parsed = urlsplit(raw_uri or "/")
path = unquote(parsed.path or "/")
"""
Path used to pick the policy, normalized the same way Caddy matches routes: repeated slashes are merged and
. and .. segments are resolved. The value is a request URI, never a full URL, so a leading // is part of the
path and not a network location.
"""
path = re.split(r"[?#]", raw_uri or "/", maxsplit=1)[0]
path = unquote(path) or "/"
path = path if path.startswith("/") else f"/{path}"
# Resolve any .. or . segments to prevent path traversal bypasses
path = re.sub(r"/{2,}", "/", path)
return posixpath.normpath(path)
def _path_matches(path: str, prefix: str) -> bool:
"""Check path boundary correctly — prevents /admin matching /administrator."""
prefix = prefix.rstrip("/")
"""Check path boundary correctly — prevents /admin matching /administrator. Case-insensitive, like Caddy."""
path = path.lower()
prefix = prefix.rstrip("/").lower()
return path == prefix or path.startswith(prefix + "/")
@@ -1,9 +1,37 @@
import hashlib
from datetime import UTC, datetime, timedelta
from secrets import token_urlsafe
from auth_gateway.models.auth import UserModel
from auth_gateway.models.runtime import RuntimeConfig
from auth_gateway.models.session import OIDCStateRecord, SessionRecord
from auth_gateway.storage.sqlite import SQLiteStorage
# The last access is written at most this often, so requests do not write to the database
LAST_SEEN_WRITE_INTERVAL = timedelta(minutes=5)
def session_id_hash(session_id: str) -> str:
"""Identifies a session outside the gateway (snapshot, revocation) without exposing the session ID."""
return hashlib.sha256(session_id.encode()).hexdigest()
def credential_fingerprint(user: UserModel) -> str:
"""Changes when the password or the TOTP secret of the user changes."""
value = f"{user.password_hash or ''}\0{user.totp_secret or ''}"
return hashlib.sha256(value.encode()).hexdigest()[:32]
def session_is_valid(session: SessionRecord, runtime_config: RuntimeConfig) -> bool:
"""A session ends when it is revoked or when the credentials of its user change or the user is removed."""
if session_id_hash(session.session_id) in runtime_config.revoked_sessions:
return False
if session.username:
user = runtime_config.users.get(session.username)
if not user or session.metadata.get("credential") != credential_fingerprint(user):
return False
return True
class SessionService:
def __init__(self, storage: SQLiteStorage, default_session_minutes: int, oidc_state_ttl_minutes: int):
@@ -66,6 +94,15 @@ class SessionService:
self.storage.save_session(session)
return session
def touch(self, session: SessionRecord) -> None:
"""Record the last access, at most once per LAST_SEEN_WRITE_INTERVAL."""
now = datetime.now(UTC)
last_seen = session.metadata.get("last_seen")
if last_seen and now - datetime.fromisoformat(last_seen) < LAST_SEEN_WRITE_INTERVAL:
return
session.metadata["last_seen"] = now.isoformat()
self.storage.save_session(session)
def delete_session(self, session_id: str | None) -> None:
if session_id:
self.storage.delete_session(session_id)
@@ -0,0 +1,80 @@
import json
import logging
import os
import threading
from datetime import UTC, datetime, timedelta
from pathlib import Path
from auth_gateway.config_loader import RuntimeConfigStore
from auth_gateway.models.session import SessionRecord
from auth_gateway.services.session_service import session_id_hash, session_is_valid
from auth_gateway.storage.sqlite import SQLiteStorage
logger = logging.getLogger("uvicorn.error")
SNAPSHOT_INTERVAL_SECONDS = 30
# A session used in the last minutes is online. The last access is written at most every 5 minutes, so the window
# must be longer than that.
ONLINE_WINDOW = timedelta(minutes=10)
class SessionSnapshot:
"""
Active sessions published for the WireGuard WebAdmin (read by Django on the primary server and reported by the
cluster agent on workers). The file is only rewritten when its content changes: an active session is published
as online without a timestamp, so using it does not change the snapshot.
"""
def __init__(self, storage: SQLiteStorage, config_store: RuntimeConfigStore, path: Path):
self.storage = storage
self.config_store = config_store
self.path = path
self._lock = threading.Lock()
self._written = None
@staticmethod
def _entry(session: SessionRecord, now: datetime) -> dict:
last_seen = session.metadata.get("last_seen") or session.created_at.isoformat()
online = now - datetime.fromisoformat(last_seen) < ONLINE_WINDOW
entry = {
"id": session_id_hash(session.session_id),
"username": session.username or "",
"email": session.email or "",
"groups": session.groups,
"factors": session.auth_factors,
"host": session.metadata.get("host", ""),
"client_ip": session.metadata.get("client_ip", ""),
"user_agent": session.metadata.get("user_agent", ""),
"created_at": session.created_at.isoformat(),
"expires_at": session.expires_at.isoformat(),
"online": online,
}
if not online:
entry["last_seen"] = last_seen
return entry
def refresh(self) -> None:
with self._lock:
now = datetime.now(UTC)
self.storage.delete_expired(now)
try:
runtime_config = self.config_store.get()
except Exception as error:
logger.warning("Session snapshot skipped: configuration not loaded (%s)", error)
return
entries = []
for session in self.storage.list_sessions():
if not session_is_valid(session, runtime_config):
self.storage.delete_session(session.session_id)
continue
entries.append(self._entry(session, now))
content = json.dumps({"sessions": entries}, indent=2, sort_keys=True) + "\n"
if content == self._written:
return
self.path.parent.mkdir(parents=True, exist_ok=True)
temp_path = self.path.with_name(f"{self.path.name}.tmp")
temp_path.write_text(content, encoding="utf-8")
os.replace(temp_path, self.path)
self._written = content
@@ -1,9 +1,45 @@
import hashlib
import logging
import time
from datetime import datetime
import pyotp
logger = logging.getLogger("uvicorn.error")
VALID_WINDOW = 1
# (secret hash, time step) of codes already accepted, so a code cannot be used twice
_used_codes: dict[tuple[str, int], float] = {}
def _forget_expired_codes(now: float, interval: int) -> None:
oldest = now - interval * (2 * VALID_WINDOW + 2)
for key, used_at in list(_used_codes.items()):
if used_at < oldest:
del _used_codes[key]
def verify_totp(secret: str, token: str) -> bool:
normalized_secret = secret.strip()
normalized_token = token.strip().replace(" ", "")
if not normalized_secret or not normalized_token:
return False
return pyotp.TOTP(normalized_secret).verify(normalized_token, valid_window=1)
try:
totp = pyotp.TOTP(normalized_secret)
except ValueError as error:
logger.warning("TOTP secret rejected (%s) — generate a new secret with at least 24 Base32 characters.", error)
return False
now = time.time()
_forget_expired_codes(now, totp.interval)
secret_hash = hashlib.sha256(normalized_secret.encode()).hexdigest()
current_step = totp.timecode(datetime.fromtimestamp(now))
for offset in range(-VALID_WINDOW, VALID_WINDOW + 1):
step = current_step + offset
if pyotp.utils.strings_equal(normalized_token, totp.generate_otp(step)):
if (secret_hash, step) in _used_codes:
logger.warning("TOTP code reuse rejected.")
return False
_used_codes[(secret_hash, step)] = now
return True
return False
@@ -92,6 +92,9 @@ class SQLiteStorage:
).fetchone()
if not row:
return None
return self._session_from_row(row)
def _session_from_row(self, row: sqlite3.Row) -> SessionRecord:
return SessionRecord(
session_id=row["session_id"],
created_at=self._from_iso(row["created_at"]),
@@ -105,6 +108,17 @@ class SQLiteStorage:
metadata=json.loads(row["metadata_json"]),
)
def list_sessions(self) -> list[SessionRecord]:
with self._lock, self._connect() as connection:
rows = connection.execute("SELECT * FROM sessions ORDER BY created_at").fetchall()
return [self._session_from_row(row) for row in rows]
def delete_expired(self, now: datetime) -> None:
with self._lock, self._connect() as connection:
connection.execute("DELETE FROM sessions WHERE expires_at <= ?", (self._to_iso(now),))
connection.execute("DELETE FROM oidc_states WHERE expires_at <= ?", (self._to_iso(now),))
connection.commit()
def delete_session(self, session_id: str) -> None:
with self._lock, self._connect() as connection:
connection.execute("DELETE FROM sessions WHERE session_id = ?", (session_id,))
@@ -11,11 +11,11 @@
<input type="hidden" name="next" value="{{ next }}">
<label class="field">
<span>Username</span>
<input type="text" name="username" autocomplete="username" autofocus required>
<input type="text" name="username" value="{{ username }}" autocomplete="username"{% if not username %} autofocus{% endif %} required>
</label>
<label class="field">
<span>Password</span>
<input type="password" name="password" autocomplete="current-password" required>
<input type="password" name="password" autocomplete="current-password"{% if username %} autofocus{% endif %} required>
</label>
<button class="btn btn-primary" type="submit">Continue</button>
</form>
@@ -1,5 +1,9 @@
import re
from fastapi import APIRouter, Request, Response
from fastapi.responses import PlainTextResponse, RedirectResponse
from auth_gateway.limiter import get_real_client_ip
from auth_gateway.services.policy_engine import evaluate_ip_access, extract_client_ip
from auth_gateway.services.resolver import resolve_request_context
from auth_gateway.web.dependencies import (
@@ -7,10 +11,9 @@ from auth_gateway.web.dependencies import (
get_effective_policy,
get_runtime_config,
get_session,
get_session_factors,
session_is_allowed,
)
from fastapi import APIRouter, Request, Response
from fastapi.responses import PlainTextResponse, RedirectResponse
router = APIRouter()
@@ -32,7 +35,7 @@ async def auth_check(request: Request):
if effective_policy.mode == "bypass":
return PlainTextResponse("OK", status_code=200)
client_ip = extract_client_ip(request.headers.get("x-forwarded-for", ""))
client_ip = extract_client_ip(get_real_client_ip(request))
ip_allowed = evaluate_ip_access(runtime_config, effective_policy, client_ip)
if effective_policy.ip_method_names and not ip_allowed:
return PlainTextResponse("Access denied for this IP address.", status_code=403)
@@ -44,7 +47,7 @@ async def auth_check(request: Request):
login_url = build_external_url(request, "/login", next=context.path)
return RedirectResponse(login_url, status_code=302)
current_factors = set(session.auth_factors if session else [])
current_factors = get_session_factors(session, effective_policy)
if ip_allowed:
current_factors.add("ip")
@@ -59,6 +62,7 @@ async def auth_check(request: Request):
response = PlainTextResponse("OK", status_code=200)
response.headers["Cache-Control"] = "no-store"
if session:
request.app.state.session_service.touch(session)
if session.username:
response.headers["X-Auth-User"] = _safe_header(session.username)
if session.email:
@@ -1,13 +1,14 @@
from urllib.parse import urlsplit
from fastapi import APIRouter, Form, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from auth_gateway.services.challenge_service import (
CHALLENGE_COOKIE_NAME,
generate_altcha_challenge,
generate_challenge_cookie,
verify_altcha_solution,
)
from fastapi import APIRouter, Form, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
router = APIRouter()
@@ -28,8 +29,9 @@ def _safe_next(url: str | None, external_path: str) -> str:
async def challenge_page(request: Request, next: str = "/"):
external_path = request.app.state.settings.external_path
return request.app.state.templates.TemplateResponse(
request,
"challenge.html",
{"request": request, "external_path": external_path, "next": next},
{"external_path": external_path, "next": next},
)
@@ -47,8 +49,9 @@ async def challenge_verify(request: Request, next: str = Form("/"), altcha: str
if not verify_altcha_solution(altcha, hmac_key):
return request.app.state.templates.TemplateResponse(
request,
"challenge.html",
{"request": request, "external_path": external_path, "next": next, "error": True},
{"external_path": external_path, "next": next, "error": True},
status_code=400,
)
@@ -1,14 +1,18 @@
from datetime import UTC, datetime
from secrets import token_urlsafe
from urllib.parse import urlencode
from fastapi import HTTPException, Request
from fastapi.responses import Response
from auth_gateway.config_loader import RuntimeConfigStore
from auth_gateway.limiter import get_real_client_ip
from auth_gateway.models.auth import OIDCMethodModel, TotpMethodModel
from auth_gateway.models.runtime import RuntimeConfig
from auth_gateway.models.session import SessionRecord
from auth_gateway.services.policy_engine import EffectivePolicy, build_effective_policy
from auth_gateway.services.resolver import RequestContext, normalize_host, normalize_path, resolve_request_context
from fastapi import HTTPException, Request
from fastapi.responses import Response
from auth_gateway.services.session_service import credential_fingerprint, session_is_valid
def get_runtime_config(request: Request) -> RuntimeConfig:
@@ -19,7 +23,25 @@ def get_runtime_config(request: Request) -> RuntimeConfig:
def get_session(request: Request) -> SessionRecord | None:
session_service = request.app.state.session_service
cookie_name = request.app.state.settings.cookie_name
return session_service.get_session(request.cookies.get(cookie_name))
session = session_service.get_session(request.cookies.get(cookie_name))
if session and not session_is_valid(session, get_runtime_config(request)):
session_service.delete_session(session.session_id)
return None
return session
def login_metadata(request: Request, username: str | None = None) -> dict:
"""Where the session was opened and, for local users, the fingerprint of their credentials."""
metadata = {
"host": normalize_host(request.headers.get("host", "")),
"client_ip": get_real_client_ip(request),
"user_agent": request.headers.get("user-agent", "")[:200],
"last_seen": datetime.now(UTC).isoformat(),
}
user = get_runtime_config(request).users.get(username) if username else None
if user:
metadata["credential"] = credential_fingerprint(user)
return metadata
def build_external_url(request: Request, path: str, **params: str) -> str:
@@ -64,6 +86,31 @@ def session_is_allowed(session: SessionRecord | None, effective_policy: Effectiv
return session.username in effective_policy.allowed_users
def get_session_factors(session: SessionRecord | None, effective_policy: EffectivePolicy) -> set[str]:
"""
Factors of the session that count for the policy. OIDC and TOTP only count when they were completed with one
of the methods of the policy: each method has its own allowlists or secret.
"""
if not session:
return set()
factors = set(session.auth_factors)
factor_methods = session.metadata.get("factor_methods", {})
for factor, method_names in (("oidc", effective_policy.oidc_method_names), ("totp", effective_policy.totp_method_names)):
if factor in factors and not set(factor_methods.get(factor, [])) & set(method_names):
factors.discard(factor)
return factors
def factor_method_metadata(session: SessionRecord | None, factor: str, method_name: str) -> dict:
"""Session metadata recording that the factor was completed with the given method."""
current = session.metadata.get("factor_methods", {}) if session else {}
factor_methods = {name: list(methods) for name, methods in current.items()}
method_names = factor_methods.setdefault(factor, [])
if method_name not in method_names:
method_names.append(method_name)
return {"factor_methods": factor_methods}
def get_totp_method(runtime_config: RuntimeConfig, effective_policy: EffectivePolicy) -> tuple[str, TotpMethodModel] | tuple[None, None]:
for method_name in effective_policy.totp_method_names:
method = runtime_config.auth_methods[method_name]
@@ -120,9 +167,14 @@ def challenge_is_valid(request: Request) -> bool:
return verify_challenge_cookie(cookie, request.app.state.settings.challenge_secret)
def build_challenge_url(request: Request, login_route: str, next_url: str) -> str:
def build_challenge_url(request: Request, login_route: str, next_url: str, error: str | None = None) -> str:
external_path = request.app.state.settings.external_path.rstrip("/")
login_path = f"{external_path}{login_route}"
params = {}
if next_url and next_url != "/":
login_path = f"{login_path}?{urlencode({'next': next_url})}"
params["next"] = next_url
if error:
params["error"] = error
if params:
login_path = f"{login_path}?{urlencode(params)}"
return build_external_url(request, "/challenge", next=login_path)
@@ -5,6 +5,7 @@ from auth_gateway.models.auth import OIDCMethodModel
logger = logging.getLogger("uvicorn.error")
from auth_gateway.services.oidc_service import is_oidc_identity_allowed
from auth_gateway.services.password_service import verify_user_password
from auth_gateway.services.challenge_service import CHALLENGE_COOKIE_NAME, revoke_challenge_cookie
from auth_gateway.services.policy_engine import evaluate_ip_access, extract_client_ip
from auth_gateway.services.resolver import normalize_host
from auth_gateway.services.totp_service import verify_totp
@@ -12,33 +13,41 @@ from auth_gateway.web.dependencies import (
build_challenge_url,
build_external_url,
challenge_is_valid,
factor_method_metadata,
get_effective_expiration,
get_effective_policy,
get_oidc_method,
get_or_create_csrf_token,
get_runtime_config,
get_session,
get_session_factors,
get_totp_method,
login_metadata,
resolve_context_from_request,
set_csrf_cookie,
session_is_allowed,
validate_csrf,
)
from auth_gateway.limiter import AUTH_RATE_LIMIT, limiter
from auth_gateway.limiter import AUTH_RATE_LIMIT, get_real_client_ip, limiter
from fastapi import APIRouter, Form, HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse
router = APIRouter()
LOGIN_USERNAME_COOKIE_NAME = "auth_gateway_login_user"
LOGIN_ERRORS = {
"invalid_password": "Invalid username or password.",
"invalid_totp": "Invalid verification code.",
}
def _render(request: Request, template_name: str, status_code: int = 200, **context):
templates = request.app.state.templates
base_context = {
"request": request,
"external_path": request.app.state.settings.external_path,
}
base_context.update(context)
response = templates.TemplateResponse(template_name, base_context, status_code=status_code)
response = templates.TemplateResponse(request, template_name, base_context, status_code=status_code)
csrf_token = context.get("csrf_token")
if csrf_token:
set_csrf_cookie(request, response, csrf_token)
@@ -46,6 +55,7 @@ def _render(request: Request, template_name: str, status_code: int = 200, **cont
def _redirect_with_cookie(request: Request, destination: str, session) -> RedirectResponse:
request.app.state.session_snapshot.refresh()
response = RedirectResponse(destination, status_code=303)
response.set_cookie(
key=request.app.state.settings.cookie_name,
@@ -67,12 +77,34 @@ def _create_authenticated_session(request: Request, *, username=None, email=None
email=email,
subject=subject,
groups=groups,
metadata=metadata,
metadata={**login_metadata(request, username), **(metadata or {})},
add_factors=factors,
expires_in_minutes=expires_in_minutes,
)
def _failed_login_redirect(request: Request, login_route: str, next_path: str, error: str, username: str | None = None):
"""
After a failed attempt the challenge must be solved again: the current challenge cookie is revoked and the
browser goes through the challenge back to the form, which shows the error.
"""
revoke_challenge_cookie(request.cookies.get(CHALLENGE_COOKIE_NAME))
response = RedirectResponse(build_challenge_url(request, login_route, next_path, error=error), status_code=303)
response.delete_cookie(CHALLENGE_COOKIE_NAME, path="/")
if username:
# Kept out of the URL so the username does not end up in logs and browser history
response.set_cookie(
key=LOGIN_USERNAME_COOKIE_NAME,
value=username,
max_age=300,
httponly=True,
secure=request.app.state.settings.secure_cookies,
samesite="strict",
path="/",
)
return response
def _csrf_error(request: Request, next_path: str, application_name: str | None = None):
return _render(
request,
@@ -109,9 +141,9 @@ async def login_page(request: Request, next: str = "/"):
return RedirectResponse(context.path, status_code=303)
if session and session_is_allowed(session, effective_policy):
current_factors = set(session.auth_factors)
current_factors = get_session_factors(session, effective_policy)
if effective_policy.ip_method_names:
client_ip = extract_client_ip(request.headers.get("x-forwarded-for", ""))
client_ip = extract_client_ip(get_real_client_ip(request))
if evaluate_ip_access(runtime_config, effective_policy, client_ip):
current_factors.add("ip")
missing_factors = [factor for factor in effective_policy.required_factors if factor not in current_factors]
@@ -156,14 +188,17 @@ async def login_password_page(request: Request, next: str = "/"):
effective_policy = get_effective_policy(runtime_config, context.policy_name)
if not effective_policy.password_method_names:
return _render(request, "error.html", status_code=400, title="Password login unavailable", message="The selected policy does not require a password step.")
return _render(
response = _render(
request,
"login_password.html",
next=next,
application_name=context.application.name,
error=None,
error=LOGIN_ERRORS.get(request.query_params.get("error", "")),
username=request.cookies.get(LOGIN_USERNAME_COOKIE_NAME, ""),
csrf_token=get_or_create_csrf_token(request),
)
response.delete_cookie(LOGIN_USERNAME_COOKIE_NAME, path="/")
return response
@router.post("/login/password")
@@ -188,15 +223,7 @@ async def login_password_submit(
if not user:
logger.warning("AUTH password failed for '%s' (policy: %s)", username, context.policy_name)
return _render(
request,
"login_password.html",
status_code=401,
next=next,
application_name=context.application.name,
error="Invalid username or password.",
csrf_token=get_or_create_csrf_token(request),
)
return _failed_login_redirect(request, "/login/password", next, "invalid_password", username=username)
if effective_policy.allowed_users and username not in effective_policy.allowed_users:
logger.warning("AUTH password denied for '%s' — not in allowed_users (policy: %s)", username, context.policy_name)
return _render(
@@ -248,7 +275,7 @@ async def login_totp_page(request: Request, next: str = "/"):
"login_totp.html",
next=next,
application_name=context.application.name,
error=None,
error=LOGIN_ERRORS.get(request.query_params.get("error", "")),
csrf_token=get_or_create_csrf_token(request),
)
@@ -269,7 +296,7 @@ async def login_totp_submit(request: Request, next: str = Form("/"), token: str
if effective_policy.password_method_names and (not session or "password" not in session.auth_factors):
return RedirectResponse(build_external_url(request, "/login/password", next=next), status_code=303)
if effective_policy.oidc_method_names and (not session or "oidc" not in session.auth_factors):
if effective_policy.oidc_method_names and "oidc" not in get_session_factors(session, effective_policy):
return RedirectResponse(build_external_url(request, "/login/oidc/start", next=next), status_code=303)
method_name, method = get_totp_method(runtime_config, effective_policy)
@@ -284,20 +311,14 @@ async def login_totp_submit(request: Request, next: str = Form("/"), token: str
if not verify_totp(secret, token):
logger.warning("AUTH totp failed for '%s' (policy: %s)", session.username if session else "?", context.policy_name)
return _render(
request,
"login_totp.html",
status_code=401,
next=next,
application_name=context.application.name,
error="Invalid verification code.",
csrf_token=get_or_create_csrf_token(request),
)
return _failed_login_redirect(request, "/login/totp", next, "invalid_totp")
session_service = request.app.state.session_service
refreshed_session = session_service.issue_session(
existing_session=session,
add_factors=["totp"],
# Without a password or OIDC step (TOTP only), the session starts here
metadata={**({} if session else login_metadata(request)), **factor_method_metadata(session, "totp", method_name)},
expires_in_minutes=get_effective_expiration(request, effective_policy, ["totp"]),
)
logger.info("AUTH login ok for '%s' via password+totp (policy: %s)", refreshed_session.username, context.policy_name)
@@ -353,7 +374,7 @@ async def login_oidc_callback(request: Request, state: str):
request,
email=identity.email,
subject=identity.subject,
metadata={"oidc_claims": identity.claims},
metadata={"oidc_claims": identity.claims, **factor_method_metadata(None, "oidc", oidc_state.method_name)},
factors=["oidc"],
expires_in_minutes=get_effective_expiration(request, effective_policy, ["oidc"]),
)
@@ -375,6 +396,7 @@ def _do_logout(request: Request, next_url: str = "/") -> RedirectResponse:
session_cookie = request.cookies.get(request.app.state.settings.cookie_name)
session = request.app.state.session_service.get_session(session_cookie)
request.app.state.session_service.delete_session(session_cookie)
request.app.state.session_snapshot.refresh()
if session:
logger.info("AUTH logout for '%s'", session.username or session.email or "unknown")
response = RedirectResponse(_safe_redirect_path(next_url), status_code=303)
@@ -383,8 +405,9 @@ def _do_logout(request: Request, next_url: str = "/") -> RedirectResponse:
@router.get("/logout")
async def logout_get(request: Request, next: str = "/"):
return _do_logout(request, next)
async def logout_get(request: Request):
# A link must not be able to end the session: the session page asks for the confirmation (POST with CSRF)
return RedirectResponse(build_external_url(request, "/"), status_code=303)
@router.post("/logout")
+1 -1
View File
@@ -2,4 +2,4 @@
set -eu
exec uvicorn auth_gateway.main:app --host 0.0.0.0 --port 9091 --no-access-log --proxy-headers --forwarded-allow-ips="*"
exec uvicorn auth_gateway.main:app --host 0.0.0.0 --port 9091 --no-access-log --no-proxy-headers
+33 -31
View File
@@ -1,38 +1,40 @@
annotated-doc==0.0.4
annotated-types==0.7.0
anyio==4.12.1
annotated-doc==0.0.6
annotated-types==0.8.0
anyio==4.16.0
argon2-cffi==25.1.0
argon2-cffi-bindings==25.1.0
Authlib==1.6.9
certifi==2026.2.25
cffi==2.0.0
click==8.3.1
cryptography==46.0.5
Deprecated==1.3.1
fastapi==0.135.1
argon2-cffi-bindings==26.2.0
Authlib==1.9.8
certifi==2026.10.23
cffi==2.1.1
click==8.5.1
cryptography==50.0.2
Deprecated==3.0.1
fastapi==0.163.1
h11==0.16.0
httpcore==1.0.9
httptools==0.7.1
httptools==0.9.0
httpx==0.28.1
idna==3.11
idna==3.20
Jinja2==3.1.6
joserfc==1.8.0
limits==5.8.0
MarkupSafe==3.0.3
packaging==26.0
pycparser==3.0
pydantic==2.12.5
pydantic-settings==2.13.1
pydantic_core==2.41.5
pyotp==2.9.0
python-dotenv==1.2.2
python-multipart==0.0.22
MarkupSafe==3.0.4
opentelemetry-api==1.45.2
packaging==26.3
pycparser==3.12
pydantic==2.14.3
pydantic-settings==2.16.3
pydantic_core==2.50.4
PyOTP==2.12.0
python-dotenv==1.2.4
python-multipart==0.0.34
PyYAML==6.0.3
slowapi==0.1.9
starlette==0.52.1
typing-inspection==0.4.2
typing_extensions==4.15.0
uvicorn==0.42.0
uvloop==0.22.1
watchfiles==1.1.1
websockets==16.0
wrapt==2.1.2
slowapi==0.1.10
starlette==1.10.0
typing-inspection==0.4.5
typing_extensions==4.16.0
uvicorn==0.54.0
uvloop==0.23.0
watchfiles==1.3.0
websockets==17.4
wrapt==2.5.2
@@ -0,0 +1,55 @@
{
"entries": [
{
"id": "cafe",
"name": "Caf\u00e9",
"hosts": [],
"upstream": "http://10.0.0.14:8000",
"allow_invalid_cert": false
},
{
"id": "dashboard",
"name": "Dashboard",
"hosts": [
"dashboard.example.test"
],
"upstream": "http://10.0.0.10:3000",
"allow_invalid_cert": false
},
{
"id": "files",
"name": "Files",
"hosts": [],
"upstream": "http://10.0.0.13:8080",
"allow_invalid_cert": false
},
{
"id": "hypervisor",
"name": "Hypervisor",
"hosts": [
"hypervisor.example.test"
],
"upstream": "https://10.0.0.12:8006",
"allow_invalid_cert": true
},
{
"id": "media",
"name": "Media",
"hosts": [
"media.example.test",
"media2.example.test"
],
"upstream": "http://10.0.0.11:32400",
"allow_invalid_cert": false
},
{
"id": "sso",
"name": "SSO",
"hosts": [
"sso.example.test"
],
"upstream": "http://10.0.0.15:8000",
"allow_invalid_cert": false
}
]
}
@@ -0,0 +1,137 @@
{
"auth_methods": {
"ip-allowlist": {
"type": "ip_address",
"rules": [
{
"address": "10.10.0.1",
"prefix_length": null,
"action": "allow",
"description": ""
},
{
"address": "10.20.0.0",
"prefix_length": 24,
"action": "allow",
"description": ""
},
{
"address": "10.20.0.12",
"prefix_length": null,
"action": "deny",
"description": ""
},
{
"address": "10.30.0.15",
"prefix_length": null,
"action": "allow",
"description": ""
}
]
},
"ip-empty": {
"type": "ip_address",
"rules": []
},
"local-password": {
"type": "local_password",
"session_expiration_minutes": 720
},
"oidc-company": {
"type": "oidc",
"session_expiration_minutes": 2880,
"provider": "https://idp.example.test",
"client_id": "fixture-client",
"client_secret": "fixture-client-secret",
"allowed_domains": [
"example.test"
],
"allowed_emails": [
"contractor@partner.example.test"
]
},
"totp-global": {
"type": "totp",
"totp_secret": "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP"
}
},
"groups": {
"staff": {
"users": [
"alice",
"bob"
]
}
},
"users": {
"alice": {
"email": "alice@example.test",
"password_hash": "$argon2id$v=19$m=65536,t=3,p=4$bEzFGMfGGK4rdHKhmwwMqw$1J+Ss48IEK1Q4Vpy0RaS+FHIZOjhjhE4MK5C5pzDzHg",
"totp_secret": ""
},
"bob": {
"email": "",
"password_hash": "$argon2id$v=19$m=65536,t=3,p=4$bEzFGMfGGK4rdHKhmwwMqw$1J+Ss48IEK1Q4Vpy0RaS+FHIZOjhjhE4MK5C5pzDzHg",
"totp_secret": "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
}
},
"policies": {
"deny": {
"policy_type": "deny",
"groups": [],
"methods": []
},
"empty-ip-list": {
"policy_type": "protected",
"groups": [],
"methods": [
"ip-empty"
]
},
"oidc-company": {
"policy_type": "protected",
"groups": [],
"methods": [
"oidc-company"
]
},
"password-totp": {
"policy_type": "protected",
"groups": [
"staff"
],
"methods": [
"local-password",
"totp-global"
]
},
"public": {
"policy_type": "bypass",
"groups": [],
"methods": []
},
"staff-password": {
"policy_type": "protected",
"groups": [
"staff"
],
"methods": [
"local-password"
]
},
"totp-only": {
"policy_type": "protected",
"groups": [],
"methods": [
"totp-global"
]
},
"trusted-ips": {
"policy_type": "protected",
"groups": [],
"methods": [
"ip-allowlist"
]
}
}
}
@@ -0,0 +1,42 @@
{
"entries": {
"cafe": {
"routes": []
},
"dashboard": {
"routes": [
{
"id": "admin",
"path_prefix": "/admin",
"policy": "password-totp"
},
{
"id": "api",
"path_prefix": "/api",
"policy": "trusted-ips"
}
],
"default_policy": "staff-password"
},
"files": {
"routes": [],
"default_policy": "totp-only"
},
"hypervisor": {
"routes": [],
"default_policy": "trusted-ips"
},
"media": {
"routes": [],
"default_policy": "public"
},
"sso": {
"routes": [],
"default_policy": "oidc-company"
},
"wireguard_webadmin": {
"routes": [],
"default_policy": "public"
}
}
}
@@ -0,0 +1,40 @@
{
"hosts": {
"dashboard.example.test": {
"certificate_type": "http_challenge",
"certificate_fallback": true,
"certificate_generation": 0
},
"hypervisor.example.test": {
"certificate_type": "http_challenge",
"certificate_fallback": true,
"certificate_generation": 0
},
"media.example.test": {
"certificate_type": "http_challenge",
"certificate_fallback": true,
"certificate_generation": 0
},
"media2.example.test": {
"certificate_type": "http_challenge",
"certificate_fallback": true,
"certificate_generation": 0
},
"sso.example.test": {
"certificate_type": "http_challenge",
"certificate_fallback": true,
"certificate_generation": 0
},
"webadmin.example.test": {
"certificate_type": "http_challenge",
"certificate_fallback": true,
"certificate_generation": 0
},
"webadmin2.example.test": {
"certificate_type": "http_challenge",
"certificate_fallback": true,
"certificate_generation": 0
}
},
"dns_credentials": {}
}
@@ -0,0 +1,21 @@
{
"entries": [
{
"id": "wireguard_webadmin",
"name": "WireGuard WebAdmin",
"hosts": [
"webadmin.example.test",
"webadmin2.example.test"
],
"upstream": "wireguard-webadmin:8000",
"static_routes": [
{
"path_prefix": "/static",
"root": "/static",
"strip_prefix": "/static",
"cache_control": "public, max-age=3600"
}
]
}
]
}
@@ -4,6 +4,7 @@ import unittest
from pathlib import Path
import pyotp
from auth_gateway.config_loader import load_runtime_config
from auth_gateway.services.policy_engine import build_effective_policy, evaluate_ip_rules
from auth_gateway.services.resolver import resolve_request_context
@@ -16,25 +17,32 @@ assert _PROCESS_CONFIG_SPEC and _PROCESS_CONFIG_SPEC.loader
_PROCESS_CONFIG_SPEC.loader.exec_module(_PROCESS_CONFIG_MODULE)
build_caddyfile = _PROCESS_CONFIG_MODULE.build_caddyfile
# Generated by the Django exporter: UPDATE_AUTH_GATEWAY_FIXTURES=1 python manage.py test app_gateway
FIXTURES_CONFIG_DIR = Path(__file__).resolve().parent / "fixtures" / "config_files"
class AuthGatewayConfigTests(unittest.TestCase):
def test_existing_config_loads_and_resolves_routes(self):
config_dir = Path(__file__).resolve().parents[2] / "caddy" / "config_files"
runtime_config = load_runtime_config(config_dir)
runtime_config = load_runtime_config(FIXTURES_CONFIG_DIR)
context = resolve_request_context(runtime_config, "app1-dev.local", "/admin/settings")
context = resolve_request_context(runtime_config, "dashboard.example.test", "/admin/settings")
self.assertIsNotNone(context)
self.assertEqual(context.policy_name, "senha-totp")
self.assertEqual(context.policy_name, "password-totp")
context = resolve_request_context(runtime_config, "app1-dev.local", "/api/status")
context = resolve_request_context(runtime_config, "dashboard.example.test", "/api/status")
self.assertIsNotNone(context)
self.assertEqual(context.policy_name, "ips-conhecidos")
self.assertEqual(context.policy_name, "trusted-ips")
policy = build_effective_policy(runtime_config, "senha-totp")
context = resolve_request_context(runtime_config, "dashboard.example.test", "/")
self.assertIsNotNone(context)
self.assertEqual(context.policy_name, "staff-password")
policy = build_effective_policy(runtime_config, "password-totp")
self.assertIsNotNone(policy)
self.assertEqual(policy.required_factors, ["totp", "password"])
self.assertEqual(policy.required_factors, ["password", "totp"])
self.assertEqual(policy.allowed_users, {"alice", "bob"})
def test_invalid_oidc_provider_fails_loudly(self):
def test_invalid_oidc_provider_disables_policy(self):
with tempfile.TemporaryDirectory() as tmpdir:
tmp_path = Path(tmpdir)
(tmp_path / "wireguard_webadmin.json").write_text(
@@ -50,22 +58,33 @@ class AuthGatewayConfigTests(unittest.TestCase):
encoding="utf-8",
)
with self.assertRaises(ValueError):
load_runtime_config(tmp_path)
with self.assertLogs("auth_gateway.config_loader", level="WARNING"):
runtime_config = load_runtime_config(tmp_path)
self.assertNotIn("oidc", runtime_config.auth_methods)
self.assertEqual(runtime_config.policies["default"].policy_type, "error")
def test_ip_rules_respect_json_order(self):
config_dir = Path(__file__).resolve().parents[2] / "caddy" / "config_files"
runtime_config = load_runtime_config(config_dir)
method = runtime_config.auth_methods["iplist1"]
self.assertTrue(evaluate_ip_rules("192.168.0.8", method.rules))
self.assertTrue(evaluate_ip_rules("192.168.0.12", method.rules))
self.assertFalse(evaluate_ip_rules("10.10.10.10", method.rules))
runtime_config = load_runtime_config(FIXTURES_CONFIG_DIR)
method = runtime_config.auth_methods["ip-allowlist"]
self.assertTrue(evaluate_ip_rules("10.10.0.1", method.rules))
self.assertTrue(evaluate_ip_rules("10.20.0.8", method.rules))
self.assertTrue(evaluate_ip_rules("10.20.0.12", method.rules))
self.assertFalse(evaluate_ip_rules("10.99.0.1", method.rules))
def test_totp_verification_accepts_valid_tokens(self):
secret = "JBSWY3DPEHPK3PXP"
secret = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP"
token = pyotp.TOTP(secret).now()
self.assertTrue(verify_totp(secret, token))
def test_totp_verification_rejects_short_secrets(self):
with self.assertLogs("uvicorn.error", level="WARNING"):
self.assertFalse(verify_totp("JBSWY3DPEHPK3PXP", "123456"))
def test_totp_verification_rejects_invalid_secrets(self):
with self.assertLogs("uvicorn.error", level="WARNING"):
self.assertFalse(verify_totp("NOT-A-BASE32-SECRET!", "123456"))
def test_caddyfile_uses_boundary_matchers_and_clears_identity_headers(self):
caddyfile = build_caddyfile(
apps=[
@@ -0,0 +1,147 @@
import json
import tempfile
import unittest
from datetime import UTC, datetime, timedelta
from pathlib import Path
from auth_gateway.config_loader import RuntimeConfigStore
from auth_gateway.models.auth import UserModel
from auth_gateway.models.runtime import RuntimeConfig
from auth_gateway.services.session_service import (
SessionService,
credential_fingerprint,
session_id_hash,
session_is_valid,
)
from auth_gateway.services.session_snapshot import SessionSnapshot
from auth_gateway.storage.sqlite import SQLiteStorage
ALICE = UserModel(email="alice@example.test", password_hash="hash-1", totp_secret="SECRET-1")
def write_config(config_dir: Path, users: dict, revoked: list[str] | None = None) -> None:
(config_dir / "applications.json").write_text(json.dumps({"entries": []}))
(config_dir / "routes.json").write_text(json.dumps({"entries": {}}))
(config_dir / "auth_policies.json").write_text(json.dumps({"users": users}))
if revoked is not None:
(config_dir / "revoked_sessions.json").write_text(json.dumps({"sessions": revoked}))
class SessionValidityTests(unittest.TestCase):
def setUp(self):
temp_dir = tempfile.TemporaryDirectory()
self.addCleanup(temp_dir.cleanup)
self.service = SessionService(SQLiteStorage(Path(temp_dir.name) / "sessions.sqlite3"), 720, 10)
self.session = self.service.issue_session(
username="alice", add_factors=["password"], metadata={"credential": credential_fingerprint(ALICE)},
)
def test_session_with_current_credentials_is_valid(self):
self.assertTrue(session_is_valid(self.session, RuntimeConfig(users={"alice": ALICE})))
def test_changed_password_or_totp_ends_the_session(self):
for changed in (ALICE.model_copy(update={"password_hash": "hash-2"}), ALICE.model_copy(update={"totp_secret": "SECRET-2"})):
self.assertFalse(session_is_valid(self.session, RuntimeConfig(users={"alice": changed})))
def test_removed_user_ends_the_session(self):
self.assertFalse(session_is_valid(self.session, RuntimeConfig(users={})))
def test_session_without_credential_fingerprint_is_not_valid(self):
old_session = self.service.issue_session(username="alice", add_factors=["password"])
self.assertFalse(session_is_valid(old_session, RuntimeConfig(users={"alice": ALICE})))
def test_revoked_session_is_not_valid(self):
runtime_config = RuntimeConfig(users={"alice": ALICE}, revoked_sessions={session_id_hash(self.session.session_id)})
self.assertFalse(session_is_valid(self.session, runtime_config))
def test_session_without_local_user_only_checks_revocation(self):
totp_session = self.service.issue_session(add_factors=["totp"])
self.assertTrue(session_is_valid(totp_session, RuntimeConfig()))
def test_last_access_is_written_at_most_every_five_minutes(self):
self.session.metadata["last_seen"] = (datetime.now(UTC) - timedelta(minutes=2)).isoformat()
recent = self.session.metadata["last_seen"]
self.service.touch(self.session)
self.assertEqual(self.service.storage.get_session(self.session.session_id).metadata.get("last_seen"), None)
self.assertEqual(self.session.metadata["last_seen"], recent)
self.session.metadata["last_seen"] = (datetime.now(UTC) - timedelta(minutes=6)).isoformat()
self.service.touch(self.session)
stored = datetime.fromisoformat(self.service.storage.get_session(self.session.session_id).metadata["last_seen"])
self.assertLess(datetime.now(UTC) - stored, timedelta(seconds=5))
class SessionSnapshotTests(unittest.TestCase):
def setUp(self):
temp_dir = tempfile.TemporaryDirectory()
self.addCleanup(temp_dir.cleanup)
self.config_dir = Path(temp_dir.name)
write_config(self.config_dir, {"alice": ALICE.model_dump()})
self.storage = SQLiteStorage(self.config_dir / "sessions.sqlite3")
self.service = SessionService(self.storage, 720, 10)
self.snapshot_path = self.config_dir / "state" / "sessions.json"
self.snapshot = SessionSnapshot(self.storage, RuntimeConfigStore(self.config_dir), self.snapshot_path)
def issue(self, minutes_since_last_access=0):
return self.service.issue_session(
username="alice", email="alice@example.test", groups=["staff"], add_factors=["password"],
metadata={
"credential": credential_fingerprint(ALICE),
"host": "app.example.test",
"client_ip": "203.0.113.5",
"last_seen": (datetime.now(UTC) - timedelta(minutes=minutes_since_last_access)).isoformat(),
"oidc_claims": {"name": "Alice"},
},
)
def read(self):
return json.loads(self.snapshot_path.read_text())["sessions"]
def test_snapshot_lists_sessions_without_session_id_or_claims(self):
session = self.issue()
self.snapshot.refresh()
content = self.snapshot_path.read_text()
entry = self.read()[0]
self.assertEqual(entry["id"], session_id_hash(session.session_id))
self.assertEqual((entry["username"], entry["host"], entry["client_ip"], entry["online"]), ("alice", "app.example.test", "203.0.113.5", True))
self.assertNotIn("last_seen", entry)
self.assertNotIn(session.session_id, content)
self.assertNotIn("Alice", content)
def test_session_unused_for_ten_minutes_is_offline_with_last_access(self):
self.issue(minutes_since_last_access=11)
self.snapshot.refresh()
entry = self.read()[0]
self.assertFalse(entry["online"])
self.assertIn("last_seen", entry)
def test_snapshot_is_only_rewritten_when_it_changes(self):
self.issue()
self.snapshot.refresh()
# Nothing changed, so a refresh must not touch the file
self.snapshot_path.write_text("left untouched")
self.snapshot.refresh()
self.assertEqual(self.snapshot_path.read_text(), "left untouched")
self.issue()
self.snapshot.refresh()
self.assertEqual(len(self.read()), 2)
def test_expired_revoked_and_outdated_sessions_are_removed(self):
expired = self.service.issue_session(username="alice", add_factors=["password"], expires_in_minutes=1,
metadata={"credential": credential_fingerprint(ALICE)})
expired.expires_at = datetime.now(UTC) - timedelta(minutes=1)
self.storage.save_session(expired)
revoked = self.issue()
outdated = self.service.issue_session(username="alice", add_factors=["password"], metadata={"credential": "old"})
kept = self.issue()
write_config(self.config_dir, {"alice": ALICE.model_dump()}, revoked=[session_id_hash(revoked.session_id)])
self.snapshot.refresh()
self.assertEqual([entry["id"] for entry in self.read()], [session_id_hash(kept.session_id)])
for removed in (expired, revoked, outdated):
self.assertIsNone(self.storage.get_session(removed.session_id))
if __name__ == "__main__":
unittest.main()
+11 -5
View File
@@ -1,15 +1,21 @@
# Compiled natively for the target platform to avoid slow emulated Go builds.
# DNS provider modules must match app_gateway/dns_providers.py
FROM --platform=$BUILDPLATFORM caddy:2-builder AS builder
ARG TARGETOS
ARG TARGETARCH
ARG TARGETVARIANT
RUN GOOS=$TARGETOS GOARCH=$TARGETARCH GOARM=${TARGETVARIANT#v} xcaddy build \
--with github.com/caddy-dns/cloudflare
FROM caddy:2
COPY --from=builder /usr/bin/caddy /usr/bin/caddy
RUN apk add --no-cache \
python3 \
py3-pip \
py3-yaml \
inotify-tools \
bash
RUN python3 -m venv /usr/local/bin/.venv && \
/usr/local/bin/.venv/bin/pip install --no-cache-dir pyyaml
COPY export_wireguard_webadmin_config.py /usr/local/bin/export_wireguard_webadmin_config.py
COPY process_config.py /usr/local/bin/process_config.py
COPY entrypoint.sh /usr/local/bin/caddy-entrypoint.sh
+85 -9
View File
@@ -3,30 +3,106 @@
set -eu
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PYTHON="${SCRIPT_DIR}/.venv/bin/python3"
PYTHON="python3"
JSON_DIR="${JSON_DIR:-/caddy_json_export}"
CADDYFILE_PATH="${CADDYFILE_PATH:-/etc/caddy/Caddyfile}"
CADDY_PID=""
CLUSTER_NODE="${CLUSTER_NODE:-false}"
# The WireGuard WebAdmin interface is only published by the primary server
if [ "$CLUSTER_NODE" != "true" ]; then
echo "==> Generating wireguard_webadmin.json..."
"$PYTHON" "${SCRIPT_DIR}/export_wireguard_webadmin_config.py"
fi
echo "==> Processing config files..."
"$PYTHON" "${SCRIPT_DIR}/process_config.py"
generate_caddyfile() {
"$PYTHON" "${SCRIPT_DIR}/process_config.py" >/dev/null
# Validation output is not printed because provider errors may include credentials
if ! caddy validate --config "$CADDYFILE_PATH" --adapter caddyfile >/dev/null 2>&1; then
echo "Warning: generated Caddyfile is invalid, regenerating with DNS challenge disabled. Check the DNS credentials."
DISABLE_DNS_CHALLENGE=1 "$PYTHON" "${SCRIPT_DIR}/process_config.py" >/dev/null
fi
}
echo "==> Starting Caddy..."
sync_tls_state() {
"$PYTHON" "${SCRIPT_DIR}/process_config.py" --sync-tls-state
}
start_caddy() {
caddy run --config "$CADDYFILE_PATH" --adapter caddyfile &
CADDY_PID=$!
}
stop_caddy() {
kill "$CADDY_PID" 2>/dev/null || true
for attempt in $(seq 1 10); do
kill -0 "$CADDY_PID" 2>/dev/null || break
sleep 1
done
kill -9 "$CADDY_PID" 2>/dev/null || true
wait "$CADDY_PID" 2>/dev/null || true
}
echo "==> Processing config files..."
generate_caddyfile
sync_tls_state >/dev/null
# Nothing is cached yet, so hosts left on a fallback certificate get a new ACME attempt
"$PYTHON" "${SCRIPT_DIR}/process_config.py" --reset-fallback-certificates
echo "==> Starting Caddy..."
start_caddy
if [ "$CLUSTER_NODE" != "true" ]; then
# Certificates used by cluster workers are exported as soon as they are issued or renewed
(
while true; do
sleep 60
"$PYTHON" "${SCRIPT_DIR}/process_config.py" --export-certificates || true
done
) &
fi
sleep 2
caddyfile_checksum() {
sha256sum "$CADDYFILE_PATH" 2>/dev/null | cut -d ' ' -f 1
}
APPLIED_CADDYFILE="$(caddyfile_checksum)"
echo "==> Watching ${JSON_DIR} for config changes..."
while true; do
inotifywait -qq -e close_write,moved_to,create "${JSON_DIR}/" --include '.*\.json$' 2>/dev/null || true
# The timeout also picks up changes written before the watch started or missed while reloading
inotifywait -qq -t 60 -e close_write,moved_to,create "${JSON_DIR}/" --include '.*\.json$' 2>/dev/null || true
sleep 1
echo "==> Config change detected, reprocessing..."
"$PYTHON" "${SCRIPT_DIR}/process_config.py"
# The container that owns this network namespace was restarted: exit so Docker restarts Caddy and it
# joins the new namespace (otherwise it keeps serving from a namespace without published ports)
if [ -f "${JSON_DIR}/.netns_owner" ] && [ "$(cat "${JSON_DIR}/.netns_owner")" != "$(readlink /proc/self/ns/net)" ]; then
echo "Network namespace owner changed, restarting..."
stop_caddy
exit 1
fi
echo "==> Reloading Caddy..."
caddy reload --config "$CADDYFILE_PATH" --adapter caddyfile 2>/dev/null || echo "Warning: Caddy reload failed, will retry on next change."
generate_caddyfile
if ! kill -0 "$CADDY_PID" 2>/dev/null; then
echo "==> Caddy is not running, starting it again..."
sync_tls_state >/dev/null
start_caddy
APPLIED_CADDYFILE="$(caddyfile_checksum)"
elif [ "$(sync_tls_state)" = "restart" ]; then
# A reload keeps previously issued certificates cached in memory
echo "==> Certificate settings changed, restarting Caddy..."
stop_caddy
start_caddy
APPLIED_CADDYFILE="$(caddyfile_checksum)"
elif [ "$(caddyfile_checksum)" != "$APPLIED_CADDYFILE" ]; then
echo "==> Config change detected, reloading Caddy..."
if caddy reload --config "$CADDYFILE_PATH" --adapter caddyfile 2>/dev/null; then
APPLIED_CADDYFILE="$(caddyfile_checksum)"
else
echo "Warning: Caddy reload failed, will retry on next change."
fi
fi
done
+375 -11
View File
@@ -7,11 +7,15 @@ Expected input files in /caddy_json_export/:
- applications.json (optional, exported from Django)
- auth_policies.json (optional, exported from Django)
- routes.json (optional, exported from Django)
- tls.json (optional, exported from Django)
"""
import hashlib
import json
import os
import re
import shutil
import sys
from urllib.parse import urlparse
JSON_DIR = os.environ.get("JSON_DIR", "/caddy_json_export")
@@ -19,6 +23,24 @@ CADDYFILE_PATH = os.environ.get("CADDYFILE_PATH", "/etc/caddy/Caddyfile")
AUTH_GATEWAY_INTERNAL_URL = os.environ.get("AUTH_GATEWAY_INTERNAL_URL", "http://wireguard-webadmin-auth-gateway:9091")
AUTH_GATEWAY_PORTAL_PATH = os.environ.get("AUTH_GATEWAY_EXTERNAL_PATH", "/auth-gateway")
AUTH_GATEWAY_CHECK_URI = "/auth/check"
CERTIFICATE_TYPES = ("self_signed", "http_challenge", "dns_challenge")
DEFAULT_CERTIFICATE_TYPE = "http_challenge"
ACME_CERTIFICATE_TYPES = ("http_challenge", "dns_challenge")
# The propagation check queries DNS from this server, which fails on networks that intercept
# port 53 traffic. Waiting a fixed delay and letting the CA validate from outside is more reliable.
ACME_DNS_PROPAGATION_DELAY = "30s"
CADDY_DATA_DIR = os.path.join(os.environ.get("XDG_DATA_HOME", "/data"), "caddy")
CERTIFICATES_DIR = os.path.join(CADDY_DATA_DIR, "certificates")
INTERNAL_ISSUER_DIR_NAME = "local"
TLS_STATE_PATH = os.path.join(CADDY_DATA_DIR, "wireguard_webadmin_tls_state.json")
TLS_STATE_PENDING_PATH = f"{CADDYFILE_PATH}.tls_state.json"
# Set by entrypoint.sh when the generated Caddyfile fails validation
DISABLE_DNS_CHALLENGE = os.environ.get("DISABLE_DNS_CHALLENGE", "") == "1"
# Cluster nodes never request ACME certificates: they use the ones exported by the primary server
CLUSTER_NODE = os.environ.get("CLUSTER_NODE", "").lower() == "true"
NODE_CERTIFICATES_DIR = os.environ.get("NODE_CERTIFICATES_DIR", "/caddy_certificates")
CERTIFICATE_EXPORT_DIR = os.environ.get("CERTIFICATE_EXPORT_DIR", "/caddy_cert_export")
DNS_NAME_PATTERN = re.compile(r"^(?=.{1,253}$)[a-z0-9_]([a-z0-9_-]{0,62})(\.[a-z0-9_]([a-z0-9_-]{0,62}))+$")
AUTH_IDENTITY_HEADERS = (
"X-Auth-User",
"X-Auth-Email",
@@ -66,10 +88,88 @@ def _safe_value(val: str) -> str:
return re.sub(r"[\r\n\x00]", "", val)
def build_caddyfile(apps, auth_policies, routes):
def _quote_value(val) -> str:
escaped = _safe_value(str(val)).replace("\\", "\\\\").replace('"', '\\"')
return f'"{escaped}"'
def _safe_identifier(val: str) -> str:
return re.sub(r"[^A-Za-z0-9_]", "", str(val))
def get_node_host_tls(host_tls):
"""
TLS settings of a host on a cluster node: the certificate exported by the primary server, the internal CA
as fallback, or None when there is no certificate yet and the fallback is disabled.
The last item (DNS challenge override domain) is only used on the primary server.
"""
certificate_type = host_tls.get("certificate_type", DEFAULT_CERTIFICATE_TYPE)
certificate_fallback = host_tls.get("certificate_fallback", True) is not False
certificate_file = re.sub(r"[^a-f0-9]", "", str(host_tls.get("certificate_file", "")))
if certificate_type in ACME_CERTIFICATE_TYPES and certificate_file:
return "certificate_file", certificate_file, certificate_fallback, None
if certificate_type == "self_signed" or certificate_fallback:
return "self_signed", None, True, None
return None
def get_host_tls(host, tls_data):
"""
Return (certificate_type, dns_credential_name, certificate_fallback, override_domain) for a host.
Hosts not listed use the HTTP challenge with fallback. The override domain is where the DNS challenge record
is created when the challenge is delegated to another zone through a CNAME record. On cluster nodes the second item is the
certificate file name, and None is returned for hosts that must not be served.
"""
host_tls = tls_data.get("hosts", {}).get(host.lower(), {})
if CLUSTER_NODE:
return get_node_host_tls(host_tls)
certificate_type = host_tls.get("certificate_type", DEFAULT_CERTIFICATE_TYPE)
if certificate_type not in CERTIFICATE_TYPES:
certificate_type = DEFAULT_CERTIFICATE_TYPE
dns_credential = None
override_domain = None
if certificate_type == "dns_challenge":
dns_credential = host_tls.get("dns_credential")
if DISABLE_DNS_CHALLENGE or dns_credential not in tls_data.get("dns_credentials", {}):
certificate_type = DEFAULT_CERTIFICATE_TYPE
dns_credential = None
else:
override_domain = str(host_tls.get("dns_challenge_override_domain") or "").lower()
if not DNS_NAME_PATTERN.match(override_domain):
override_domain = None
certificate_fallback = certificate_type == "self_signed" or host_tls.get("certificate_fallback", True) is not False
return certificate_type, dns_credential, certificate_fallback, override_domain
def group_hosts_by_tls(hosts, tls_data):
"""Hosts sharing the same certificate settings are served by the same site block."""
groups = {}
for host in hosts:
host_tls = get_host_tls(host, tls_data)
if host_tls is not None:
groups.setdefault(host_tls, []).append(host)
return groups.items()
def get_certificate_only_hosts(apps, tls_data):
"""Hosts the primary server only manages certificates for, because their application is served by workers."""
if CLUSTER_NODE:
return []
served_hosts = {host.lower() for app in apps for host in app.get("hosts", [])}
return [
host for host, host_tls in tls_data.get("hosts", {}).items()
if host_tls.get("certificate_only") and host not in served_hosts
]
def build_caddyfile(apps, auth_policies, routes, tls_data=None):
tls_data = tls_data or {}
policies = auth_policies.get("policies", {}) if auth_policies else {}
route_entries = routes.get("entries", {}) if routes else {}
lines = []
# Caddy refuses an empty Caddyfile, which happens on cluster nodes without applications
lines = ["# Generated by process_config.py. Do not edit.", ""]
def get_policy_type(policy_name):
if policy_name and policy_name in policies:
@@ -82,6 +182,41 @@ def build_caddyfile(apps, auth_policies, routes):
lines.append(" }")
lines.append("")
def emit_tls(certificate_type, dns_credential, certificate_fallback, override_domain=None):
if certificate_type == "self_signed":
lines.append(" tls internal")
lines.append("")
return
if certificate_type == "certificate_file":
certificate_path = os.path.join(NODE_CERTIFICATES_DIR, dns_credential)
lines.append(f" tls {certificate_path}.crt {certificate_path}.key")
lines.append("")
return
lines.append(" tls {")
if certificate_type == "dns_challenge":
dns_credential_data = tls_data["dns_credentials"][dns_credential]
provider = _safe_identifier(dns_credential_data.get("provider", ""))
lines.append(" issuer acme {")
lines.append(f" dns {provider} {{")
for field_name, field_value in dns_credential_data.get("credentials", {}).items():
lines.append(f" {_safe_identifier(field_name)} {_quote_value(field_value)}")
lines.append(" }")
if override_domain:
# The challenge record of the host is a CNAME pointing to this name, in a zone of the credential
lines.append(f" dns_challenge_override_domain {override_domain}")
lines.append(f" propagation_delay {ACME_DNS_PROPAGATION_DELAY}")
lines.append(" propagation_timeout -1")
lines.append(" }")
else:
lines.append(" issuer acme")
if certificate_fallback:
# Fall back to the internal CA when the ACME certificate cannot be issued
lines.append(" issuer internal")
lines.append(" }")
lines.append("")
def emit_identity_header_sanitization(indent=" "):
for header_name in AUTH_IDENTITY_HEADERS:
lines.append(f"{indent}request_header -{header_name}")
@@ -94,8 +229,10 @@ def build_caddyfile(apps, auth_policies, routes):
# Caddy's path matcher does not decode percent-encoding, so /%2fadmin would
# NOT match path /admin and would fall through to the default (potentially
# bypass) handler even though some upstreams decode it to /admin.
# Path parameters (;, also encoded as %3b) are rejected for the same reason: /admin;x does not match the
# /admin route, but Java upstreams (Tomcat, Spring) serve it as /admin.
lines.append(" @encoded_slash {")
lines.append(" path_regexp (?i)%(?:25)*2f")
lines.append(" path_regexp (?i)%(?:25)*2f|;|%(?:25)*3b")
lines.append(" }")
lines.append(" handle @encoded_slash {")
lines.append(" respond 400")
@@ -142,20 +279,18 @@ def build_caddyfile(apps, auth_policies, routes):
lines.append(" }")
lines.append("")
for app in apps:
hosts = app.get("hosts", [])
def emit_site_block(app, hosts, host_tls):
upstream = app.get("upstream", "")
allow_invalid_cert = app.get("allow_invalid_cert", False)
# tls_insecure_skip_verify is only valid for https upstreams
allow_invalid_cert = app.get("allow_invalid_cert", False) and upstream.startswith("https://")
static_routes = app.get("static_routes", [])
app_id = app.get("id", "")
if not hosts or not upstream:
continue
base, upstream_path = split_upstream(upstream)
safe_hosts = [_safe_value(h) for h in hosts]
lines.append(f"{', '.join(safe_hosts)} {{")
emit_tls(*host_tls)
lines.append(" # Security: overwrite client-supplied forwarding headers with verified values")
lines.append(" request_header X-Forwarded-For {http.request.remote.host}")
lines.append(" request_header -X-Forwarded-Host")
@@ -181,7 +316,7 @@ def build_caddyfile(apps, auth_policies, routes):
emit_reverse_proxy(base, upstream_path, indent=" ", allow_invalid_cert=allow_invalid_cert)
lines.append("}")
lines.append("")
continue
return
route_list = sorted(app_route_data.get("routes", []), key=lambda route: len(route.get("path_prefix", "")), reverse=True)
for route_index, route in enumerate(route_list):
@@ -211,20 +346,249 @@ def build_caddyfile(apps, auth_policies, routes):
lines.append("}")
lines.append("")
for app in apps:
hosts = app.get("hosts", [])
if not hosts or not app.get("upstream", ""):
continue
for host_tls, group_hosts in group_hosts_by_tls(hosts, tls_data):
emit_site_block(app, group_hosts, host_tls)
certificate_only_hosts = get_certificate_only_hosts(apps, tls_data)
for host_tls, group_hosts in group_hosts_by_tls(certificate_only_hosts, tls_data):
# Keeps the certificate managed for cluster workers; the application is not published here
lines.append(f"{', '.join(_safe_value(host) for host in group_hosts)} {{")
emit_tls(*host_tls)
lines.append(" respond 404")
lines.append("}")
lines.append("")
return "\n".join(lines)
def build_tls_state(apps, tls_data):
"""Map each host to a fingerprint of the certificate settings used in the generated Caddyfile."""
tls_data = tls_data or {}
tls_state = {}
hosts = [host for app in apps if app.get("upstream") for host in app.get("hosts", [])]
hosts += get_certificate_only_hosts(apps, tls_data)
for host in hosts:
host_tls = get_host_tls(host, tls_data)
if host_tls is None:
continue
certificate_type, certificate_reference, certificate_fallback, override_domain = host_tls
credential_hash = ""
if certificate_type == "dns_challenge":
credential_data = tls_data["dns_credentials"][certificate_reference]
# Hosts without delegation keep the fingerprint they had before the override domain existed
if override_domain:
credential_data = {"credential": credential_data, "override_domain": override_domain}
credential_data = json.dumps(credential_data, sort_keys=True)
credential_hash = hashlib.sha256(credential_data.encode()).hexdigest()
certificate_generation = tls_data.get("hosts", {}).get(host.lower(), {}).get("certificate_generation", 0)
tls_state[host.lower()] = [
certificate_type, certificate_reference or "", credential_hash, certificate_fallback, certificate_generation
]
return tls_state
def _write_json(filepath, data):
os.makedirs(os.path.dirname(filepath), exist_ok=True)
with open(filepath, "w", encoding="utf-8") as json_file:
json.dump(data, json_file)
def _read_json(filepath):
if not os.path.exists(filepath):
return None
with open(filepath, "r", encoding="utf-8") as json_file:
return json.load(json_file)
def has_acme_certificate(host):
if not os.path.isdir(CERTIFICATES_DIR):
return False
for issuer_dir_name in os.listdir(CERTIFICATES_DIR):
if issuer_dir_name == INTERNAL_ISSUER_DIR_NAME:
continue
if os.path.isfile(os.path.join(CERTIFICATES_DIR, issuer_dir_name, host, f"{host}.crt")):
return True
return False
def is_self_signed_renewal(previous_host_state, host_state):
"""A new self-signed certificate was requested for a host that keeps using the internal CA."""
return (
previous_host_state is not None and previous_host_state[0] == "self_signed" == host_state[0]
and previous_host_state[4] != host_state[4]
)
def sync_tls_state():
"""
Compare the certificate settings of the last generated Caddyfile with the ones currently applied.
For hosts whose ACME settings changed (including a retry request), the fallback certificate from the
internal CA is removed so a new ACME certificate is requested right away instead of on the next renewal.
Prints "restart" when Caddy must be restarted, since a reload keeps cached certificates in memory. Hosts
that already hold an ACME certificate and had no fallback certificate removed do not require a restart.
"""
pending_state = _read_json(TLS_STATE_PENDING_PATH)
if pending_state is None:
return
applied_state = _read_json(TLS_STATE_PATH)
restart_required = False
if applied_state is not None:
for host, host_state in pending_state.items():
previous_host_state = applied_state.get(host)
if previous_host_state == host_state or "/" in host or host in ("", ".", ".."):
continue
# A new host normally has nothing cached, unless a fallback certificate was left by an earlier use
# of the same hostname (e.g. removed from one application and added to another)
if previous_host_state is None and not os.path.isdir(
os.path.join(CERTIFICATES_DIR, INTERNAL_ISSUER_DIR_NAME, host)
):
continue
if is_self_signed_renewal(previous_host_state, host_state):
# The internal CA only issues a new certificate when the cached one is gone
internal_certificate_dir = os.path.join(CERTIFICATES_DIR, INTERNAL_ISSUER_DIR_NAME, host)
if os.path.isdir(internal_certificate_dir):
shutil.rmtree(internal_certificate_dir)
print(f"Removed self-signed certificate for {host}", file=sys.stderr)
restart_required = True
continue
if CLUSTER_NODE:
# Certificates received from the primary server replace cached ones only after a restart
if host_state[0] == "certificate_file":
fallback_certificate_dir = os.path.join(CERTIFICATES_DIR, INTERNAL_ISSUER_DIR_NAME, host)
if os.path.isdir(fallback_certificate_dir):
shutil.rmtree(fallback_certificate_dir)
restart_required = True
continue
if host_state[0] not in ACME_CERTIFICATE_TYPES:
# A cached ACME certificate would keep being served instead of the self-signed one
if has_acme_certificate(host):
restart_required = True
continue
fallback_removed = False
fallback_certificate_dir = os.path.join(CERTIFICATES_DIR, INTERNAL_ISSUER_DIR_NAME, host)
if os.path.isdir(fallback_certificate_dir):
shutil.rmtree(fallback_certificate_dir)
fallback_removed = True
print(f"Removed fallback certificate for {host}", file=sys.stderr)
if fallback_removed or not has_acme_certificate(host):
restart_required = True
_write_json(TLS_STATE_PATH, pending_state)
if restart_required:
print("restart")
def reset_fallback_certificates():
"""
Remove fallback certificates of ACME hosts before Caddy starts, so the ACME certificate is requested again
on every start instead of only on the next renewal. If the request fails, the fallback is issued again.
"""
pending_state = _read_json(TLS_STATE_PENDING_PATH) or {}
for host, host_state in pending_state.items():
if host_state[0] not in ACME_CERTIFICATE_TYPES or "/" in host or host in ("", ".", ".."):
continue
fallback_certificate_dir = os.path.join(CERTIFICATES_DIR, INTERNAL_ISSUER_DIR_NAME, host)
if os.path.isdir(fallback_certificate_dir):
shutil.rmtree(fallback_certificate_dir)
print(f"Removed fallback certificate for {host}", file=sys.stderr)
def find_acme_certificate(host):
"""Return (certificate_path, key_path) of the newest ACME certificate stored by Caddy for a host."""
candidates = []
if os.path.isdir(CERTIFICATES_DIR):
for issuer_dir_name in os.listdir(CERTIFICATES_DIR):
if issuer_dir_name == INTERNAL_ISSUER_DIR_NAME:
continue
certificate_path = os.path.join(CERTIFICATES_DIR, issuer_dir_name, host, f"{host}.crt")
key_path = os.path.join(CERTIFICATES_DIR, issuer_dir_name, host, f"{host}.key")
if os.path.isfile(certificate_path) and os.path.isfile(key_path):
candidates.append((os.path.getmtime(certificate_path), certificate_path, key_path))
if not candidates:
return None, None
newest = max(candidates)
return newest[1], newest[2]
def _copy_if_changed(source_path, destination_path):
with open(source_path, "r", encoding="utf-8") as source_file:
content = source_file.read()
if _read_text(destination_path) == content:
return False
temp_path = f"{destination_path}.tmp"
with open(temp_path, "w", encoding="utf-8") as destination_file:
destination_file.write(content)
os.chmod(temp_path, 0o600)
os.replace(temp_path, destination_path)
return True
def _read_text(filepath):
try:
with open(filepath, "r", encoding="utf-8") as text_file:
return text_file.read()
except OSError:
return None
def export_certificates():
"""
Copy the ACME certificates of hosts served by cluster workers to CERTIFICATE_EXPORT_DIR, where Django reads
them to distribute to the workers. Fallback certificates from the internal CA are never exported.
"""
if CLUSTER_NODE or not os.path.isdir(CERTIFICATE_EXPORT_DIR):
return
tls_data = load_json("tls.json") or {}
export_hosts = {
host for host, host_tls in tls_data.get("hosts", {}).items()
if host_tls.get("export_certificate") and "/" not in host and host not in ("", ".", "..")
}
for host in sorted(export_hosts):
certificate_path, key_path = find_acme_certificate(host)
if not certificate_path:
continue
host_export_dir = os.path.join(CERTIFICATE_EXPORT_DIR, host)
os.makedirs(host_export_dir, exist_ok=True)
key_changed = _copy_if_changed(key_path, os.path.join(host_export_dir, "certificate.key"))
certificate_changed = _copy_if_changed(certificate_path, os.path.join(host_export_dir, "certificate.crt"))
if certificate_changed or key_changed:
print(f"Exported certificate for {host}")
for host in os.listdir(CERTIFICATE_EXPORT_DIR):
host_export_dir = os.path.join(CERTIFICATE_EXPORT_DIR, host)
if host not in export_hosts and os.path.isdir(host_export_dir):
shutil.rmtree(host_export_dir)
print(f"Removed exported certificate for {host}")
def main():
apps = collect_all_applications()
auth_policies = load_json("auth_policies.json")
routes = load_json("routes.json")
tls_data = load_json("tls.json")
caddyfile_content = build_caddyfile(apps, auth_policies, routes)
caddyfile_content = build_caddyfile(apps, auth_policies, routes, tls_data)
os.makedirs(os.path.dirname(CADDYFILE_PATH), exist_ok=True)
with open(CADDYFILE_PATH, "w", encoding="utf-8") as caddyfile:
caddyfile.write(caddyfile_content)
_write_json(TLS_STATE_PENDING_PATH, build_tls_state(apps, tls_data))
print(f"Caddyfile written to {CADDYFILE_PATH}")
if __name__ == "__main__":
if "--sync-tls-state" in sys.argv:
sync_tls_state()
elif "--export-certificates" in sys.argv:
export_certificates()
elif "--reset-fallback-certificates" in sys.argv:
reset_fallback_certificates()
else:
main()
@@ -1,10 +1,10 @@
# Single stage build for Cluster Node
FROM python:3.12-slim
FROM python:3.14-slim
WORKDIR /app
# Install necessary runtime packages
RUN apt-get update && apt-get install -y --no-install-recommends \
wireguard \
wireguard-tools \
iptables \
iproute2 \
net-tools \
@@ -12,6 +12,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
inetutils-traceroute \
procps \
curl \
openssl \
nano \
&& rm -rf /var/lib/apt/lists/*
@@ -21,13 +22,11 @@ COPY requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
# Copy the application code
COPY . /app/
COPY cluster_worker.py entrypoint.sh /app/
# Set execution permissions on scripts
RUN chmod +x /app/entrypoint.sh
ARG SERVER_ADDRESS
ARG DEBUG_MODE
ENTRYPOINT ["/app/entrypoint.sh"]
CMD ["python", "-u", "/app/cluster_worker.py"]
+502 -296
View File
@@ -1,350 +1,556 @@
import glob
import hashlib
import ipaddress
import json
import logging
import os
import re
import socket
import ssl
import subprocess
import tempfile
import time
from typing import Dict, Any
from datetime import datetime, timezone
import requests
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Constants
MASTER_SERVER_ADDRESS = os.environ.get('MASTER_SERVER_ADDRESS')
TOKEN = os.environ.get('TOKEN')
MASTER_SERVER_ADDRESS = os.environ.get('MASTER_SERVER_ADDRESS', '')
TOKEN = os.environ.get('TOKEN', '')
WORKER_VERSION = 15
REQUEST_TIMEOUT = 30
MANIFEST_INTERVAL = 60
DEFAULT_STATS_INTERVAL = 60
WIREGUARD_DIR = '/etc/wireguard'
FIREWALL_SCRIPT = os.path.join(WIREGUARD_DIR, 'wg-firewall.sh')
DNS_DIR = '/etc/dnsmasq'
WORKER_VERSION = 11
REQUEST_TIMEOUT = 20
class ClusterWorker:
def __init__(self):
self.config_version = 0
self.dns_version = self.get_local_dns_version()
self.should_run = True
self.session = requests.Session()
if not MASTER_SERVER_ADDRESS or not TOKEN:
logger.error("MASTER_SERVER_ADDRESS or TOKEN not set")
self.should_run = False
self.base_url = f"https://{MASTER_SERVER_ADDRESS}/api/cluster"
# Validate URL scheme
if not MASTER_SERVER_ADDRESS.startswith(('http://', 'https://')):
self.base_url = f"https://{MASTER_SERVER_ADDRESS}/api/cluster"
else:
self.base_url = f"{MASTER_SERVER_ADDRESS}/api/cluster"
DNS_MAIN_CONFIG = 'wireguard_webadmin_dns.conf'
# Only mounted when the node runs the App Gateway (cluster_node-gateway.yml)
GATEWAY_DIR = '/caddy_json_export'
CERTIFICATES_DIR = '/caddy_certificates'
GATEWAY_FILES = ('applications.json', 'auth_policies.json', 'routes.json', 'tls.json')
# Sessions ended from the WireGuard WebAdmin, sent by primary servers that support it
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)$')
# 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'),
('nat', 'WGWADM_PREROUTING'),
('filter', 'WGWADM_FORWARD'),
('filter', 'WGWADM_ROUTE_POLICY'),
)
def func_process_wireguard_status(self) -> Dict[str, Any]:
command = "wg show all dump"
class SectionError(Exception):
pass
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stdout, stderr = process.communicate()
if process.returncode != 0:
return {"message": stderr, "status": "error"}
def run_command(command, check=True):
result = subprocess.run(command, capture_output=True, text=True)
if check and result.returncode != 0:
raise SectionError(f"{' '.join(command)}: {(result.stderr or result.stdout).strip()}")
return result
data: Dict[str, Dict[str, Dict[str, Any]]] = {}
# wg dump format is tab-separated.
# There are two kinds of lines:
# - Interface line: interface \t private_key \t public_key \t listen_port \t fwmark
# - Peer line: interface \t peer_public_key \t preshared_key \t endpoint \t allowed_ips \t latest_handshake \t transfer_rx \t transfer_tx \t persistent_keepalive
for line in stdout.strip().split("\n"):
parts = line.split("\t")
if len(parts) < 5:
def interface_is_up(interface):
return run_command(['wg', 'show', interface], check=False).returncode == 0
def sync_interface_routes(interface):
"""
Bring the IPv4 routes of a running interface in line with its allowed IPs, as wg-quick does on start.
wg syncconf only updates the peers. Default routes (/0) are left to wg-quick.
"""
allowed_networks = set()
for line in run_command(['wg', 'show', interface, 'allowed-ips']).stdout.splitlines():
for value in line.split()[1:]:
try:
network = ipaddress.IPv4Network(value, strict=False)
except ValueError:
continue
if network.prefixlen:
allowed_networks.add(network)
allowed_networks = sorted(allowed_networks, key=lambda network: network.prefixlen)
interface = parts[0]
errors = []
for network in allowed_networks:
if run_command(['ip', '-4', 'route', 'show', 'dev', interface, 'match', str(network)], check=False).stdout.strip():
continue
# replace instead of add: the network may still be routed to another instance it was moved from
result = run_command(['ip', '-4', 'route', 'replace', str(network), 'dev', interface], check=False)
if result.returncode != 0:
errors.append(f'{network}: {result.stderr.strip()}')
# Peer lines are expected to have at least 9 fields
for route in run_command(['ip', '-o', '-4', 'route', 'show', 'dev', interface], check=False).stdout.splitlines():
fields = route.split()
if not fields or 'kernel' in fields:
continue
try:
route_network = ipaddress.IPv4Network(fields[0], strict=False)
except ValueError:
continue
# Only routes that no allowed IP covers are removed: the interface drops their traffic anyway
if any(route_network.subnet_of(network) for network in allowed_networks):
continue
result = run_command(['ip', '-4', 'route', 'delete', str(route_network), 'dev', interface], check=False)
if result.returncode != 0:
errors.append(f'{route_network}: {result.stderr.strip()}')
if errors:
raise SectionError(f"{interface} routes: {'; '.join(errors)}")
def interface_section(config):
"""Return the [Interface] part of a WireGuard config, used to decide between syncconf and restart."""
return config.split('[Peer]', 1)[0].strip()
def read_file(path):
try:
with open(path, 'r', encoding='utf-8') as config_file:
return config_file.read()
except FileNotFoundError:
return None
def write_file(path, content, mode=0o600, in_place=False):
if in_place:
with open(path, 'w', encoding='utf-8') as config_file:
config_file.write(content)
os.chmod(path, mode)
return
temp_path = f'{path}.tmp'
with open(temp_path, 'w', encoding='utf-8') as config_file:
config_file.write(content)
os.chmod(temp_path, mode)
os.replace(temp_path, path)
def wireguard_status():
result = run_command(['wg', 'show', 'all', 'dump'], check=False)
if result.returncode != 0:
return {}
data = {}
# Peer lines: interface, public_key, preshared_key, endpoint, allowed_ips, latest_handshake, rx, tx, keepalive
for line in result.stdout.strip().splitlines():
parts = line.split('\t')
if len(parts) < 9:
# interface line, ignore
continue
peer_public_key = parts[1]
endpoint = parts[3]
allowed_ips_raw = parts[4]
latest_handshake = parts[5]
transfer_rx = parts[6]
transfer_tx = parts[7]
if interface not in data:
data[interface] = {}
data[interface][peer_public_key] = {
"allowed-ips": [ip for ip in allowed_ips_raw.split(",") if ip] if allowed_ips_raw else [],
"latest-handshakes": latest_handshake or "",
"transfer": {"tx": int(transfer_tx or 0), "rx": int(transfer_rx or 0)},
"endpoints": endpoint or "",
interface, peer_public_key, endpoint, allowed_ips = parts[0], parts[1], parts[3], parts[4]
data.setdefault(interface, {})[peer_public_key] = {
'allowed-ips': [ip for ip in allowed_ips.split(',') if ip] if allowed_ips else [],
'latest-handshakes': parts[5] or '',
'transfer': {'tx': int(parts[7] or 0), 'rx': int(parts[6] or 0)},
'endpoints': endpoint or '',
}
return data
def cleanup_wireguard(self):
logger.info("Cleaning up WireGuard configuration...")
# Stop all wireguard interfaces
def gateway_enabled():
return os.path.isdir(GATEWAY_DIR) and os.path.isdir(CERTIFICATES_DIR)
def tcp_service_is_running(address):
try:
files = glob.glob(f"{WIREGUARD_DIR}/*.conf")
for f in files:
interface = os.path.basename(f).replace('.conf', '')
subprocess.run(['wg-quick', 'down', interface], capture_output=True)
except Exception as e:
logger.error(f"Error stopping wireguard interfaces: {e}")
# Remove files
try:
for f in glob.glob(f"{WIREGUARD_DIR}/*"):
os.remove(f)
except Exception as e:
logger.error(f"Error cleaning directory: {e}")
try:
subprocess.run(['iptables', '-t', 'nat', '-F', 'WGWADM_POSTROUTING'], capture_output=True)
subprocess.run(['iptables', '-t', 'nat', '-F', 'WGWADM_PREROUTING'], capture_output=True)
subprocess.run(['iptables', '-t', 'filter', '-F', 'WGWADM_FORWARD'], capture_output=True)
except Exception as e:
logger.error(f"Error flushing firewall: {e}")
def get_local_dns_version(self):
try:
version_file = os.path.join(DNS_DIR, 'config_version.conf')
if os.path.exists(version_file):
with open(version_file, 'r') as f:
for line in f:
if line.startswith('DNS_VERSION='):
return int(line.strip().split('=')[1])
except Exception as e:
logger.error(f"Error reading DNS version: {e}")
return 0
def get_status(self):
params = {
'token': TOKEN,
'worker_config_version': self.config_version,
'worker_dns_version': self.dns_version,
'worker_version': WORKER_VERSION
}
logger.info(f"Requesting status from Master... (Config Version: {self.config_version}, DNS Version: {self.dns_version}, Worker Version: {WORKER_VERSION})")
try:
response = self.session.get(f"{self.base_url}/status/", params=params, timeout=REQUEST_TIMEOUT)
logger.info(f"Status response received. HTTP Code: {response.status_code}")
return response
except requests.RequestException as e:
logger.error(f"Connection error while getting status: {e}")
return None
def download_configs(self):
params = {
'token': TOKEN,
'worker_config_version': self.config_version,
'worker_dns_version': self.dns_version,
'worker_version': WORKER_VERSION
}
try:
response = self.session.get(f"{self.base_url}/worker/get_config_files/", params=params, timeout=REQUEST_TIMEOUT)
if response.status_code == 200:
data = response.json()
if data.get('status') == 'success':
return data
return None
except requests.RequestException as e:
logger.error(f"Error downloading configs: {e}")
return None
def download_dns_config(self):
params = {
'token': TOKEN,
'worker_config_version': self.config_version,
'worker_dns_version': self.dns_version,
'worker_version': WORKER_VERSION
}
try:
logger.info(f"Downloading DNS config... (Current Version: {self.dns_version})")
response = self.session.get(f"{self.base_url}/worker/get_dnsmasq_config/", params=params, timeout=REQUEST_TIMEOUT)
if response.status_code == 200:
tar_path = 'dnsmasq_config.tar.gz'
with open(tar_path, 'wb') as f:
f.write(response.content)
logger.info("Extracting DNS config...")
if not os.path.exists(DNS_DIR):
os.makedirs(DNS_DIR, exist_ok=True)
subprocess.run(['tar', 'xvfz', tar_path, '-C', DNS_DIR], check=True, capture_output=True)
if os.path.exists(tar_path):
os.remove(tar_path)
# Update version
self.dns_version = self.get_local_dns_version()
logger.info(f"DNS config updated (New Version: {self.dns_version})")
with socket.create_connection(address, timeout=3):
return True
except OSError:
return False
def _parse_not_after(value):
return datetime.strptime(value, '%b %d %H:%M:%S %Y %Z').replace(tzinfo=timezone.utc).isoformat()
def _fetch_certificate(hostname, verify):
if verify:
context = ssl.create_default_context()
else:
logger.error(f"Failed to download DNS config. Status: {response.status_code}")
return False
except Exception as e:
logger.error(f"Error updating DNS config: {e}")
return False
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
with socket.create_connection(('127.0.0.1', 443), timeout=3) as raw_socket:
with context.wrap_socket(raw_socket, server_hostname=hostname) as tls_socket:
return tls_socket.getpeercert() if verify else tls_socket.getpeercert(binary_form=True)
def send_ping(self):
params = {
'token': TOKEN,
'worker_config_version': self.config_version,
'worker_dns_version': self.dns_version,
'worker_version': WORKER_VERSION
def inspect_certificate(hostname):
"""Same checks as app_gateway/certificate_status.py on the primary server, against the local Caddy."""
try:
certificate = _fetch_certificate(hostname, verify=True)
issuer = dict(field[0] for field in certificate.get('issuer', ()))
return {
'status': 'trusted',
'issuer': issuer.get('organizationName') or issuer.get('commonName') or '',
'not_after': _parse_not_after(certificate['notAfter']),
}
except ssl.SSLCertVerificationError:
pass
except (OSError, ValueError):
return {'status': 'unavailable', 'issuer': '', 'not_after': None}
try:
logger.info("Sending ping to Master...")
self.session.get(f"{self.base_url}/worker/ping/", params=params, timeout=REQUEST_TIMEOUT)
except Exception as e:
logger.error(f"Error sending ping: {e}")
certificate_der = _fetch_certificate(hostname, verify=False)
result = subprocess.run(
['openssl', 'x509', '-inform', 'DER', '-noout', '-issuer', '-enddate', '-nameopt', 'RFC2253'],
input=certificate_der, capture_output=True, timeout=5,
)
except (OSError, ValueError, subprocess.SubprocessError):
return {'status': 'unavailable', 'issuer': '', 'not_after': None}
issuer = ''
not_after = None
for line in result.stdout.decode(errors='replace').splitlines():
if line.startswith('issuer='):
parts = dict(part.split('=', 1) for part in line[len('issuer='):].split(',') if '=' in part)
issuer = INTERNAL_CA_NAME if INTERNAL_CA_NAME in line else parts.get('O') or parts.get('CN') or ''
elif line.startswith('notAfter='):
not_after = _parse_not_after(line[len('notAfter='):])
return {'status': 'untrusted', 'issuer': issuer, 'not_after': not_after}
def apply_configs(self, data):
logger.info("Applying new configurations...")
files = data.get('files', {})
cluster_settings = data.get('cluster_settings', {})
new_config_version = cluster_settings.get('config_version', 0)
# 1. Stop existing interfaces
self.cleanup_wireguard()
def dns_is_running():
# dnsmasq always listens on loopback when it is restricted to specific interfaces. The DNS container pauses
# for a few seconds while reloading, so a missing answer is retried before reporting it as stopped.
query = b'\x12\x34\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x09localhost\x00\x00\x01\x00\x01'
for attempt in range(4):
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as dns_socket:
dns_socket.settimeout(2)
try:
dns_socket.sendto(query, ('127.0.0.1', 53))
dns_socket.recvfrom(512)
return True
except OSError:
pass
time.sleep(1)
return False
# 2. Write new files
class ClusterNodeAgent:
def __init__(self):
self.base_url = f"{MASTER_SERVER_ADDRESS.rstrip('/')}/api/cluster/v2"
self.session = requests.Session()
self.session.headers.update({
'Authorization': f'Bearer {TOKEN}',
'X-Worker-Version': str(WORKER_VERSION),
})
# Nothing is persisted: after a restart interfaces and firewall rules are gone, so every section is applied again
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
def request(self, method, path, **kwargs):
try:
return self.session.request(method, f'{self.base_url}/{path}', timeout=REQUEST_TIMEOUT, **kwargs)
except requests.RequestException as error:
logger.error('Request to %s failed: %s', path, error)
return None
@staticmethod
def response_json(response, path):
"""Decoded JSON object of a response, or None when the primary server did not answer with one."""
try:
data = response.json()
except ValueError:
data = None
if isinstance(data, dict):
return data
content_type = response.headers.get('Content-Type', 'no content type')
if response.history:
logger.error(
'Request to %s was redirected to %s (HTTP %s, %s) instead of answering with JSON. If the App Gateway '
'protects the WireGuard WebAdmin of the primary server, add a route for /api/cluster/ with a public '
'policy to it.', path, response.url, response.status_code, content_type
)
else:
logger.error(
'Request to %s did not return JSON (HTTP %s, %s). Check MASTER_SERVER_ADDRESS and, if the App Gateway '
'protects the WireGuard WebAdmin of the primary server, add a route for /api/cluster/ with a public '
'policy to it.', path, response.status_code, content_type
)
return None
# Section handlers
def apply_firewall(self, section):
content = section['files'].get('wg-firewall.sh')
if content is None:
raise SectionError('wg-firewall.sh missing from section')
write_file(FIREWALL_SCRIPT, content, mode=0o700)
run_command(['bash', FIREWALL_SCRIPT])
def apply_wireguard(self, section):
desired_files = {
filename: content for filename, content in section['files'].items()
if filename.startswith('wg') and filename.endswith('.conf') and '/' not in filename
}
errors = []
for config_path in glob.glob(os.path.join(WIREGUARD_DIR, 'wg[0-9]*.conf')):
filename = os.path.basename(config_path)
if filename in desired_files:
continue
interface = filename[:-len('.conf')]
if interface_is_up(interface):
run_command(['wg-quick', 'down', interface], check=False)
os.remove(config_path)
logger.info('Removed WireGuard interface %s', interface)
for filename, content in sorted(desired_files.items()):
interface = filename[:-len('.conf')]
config_path = os.path.join(WIREGUARD_DIR, filename)
previous_content = read_file(config_path)
write_file(config_path, content)
try:
if not interface_is_up(interface):
run_command(['wg-quick', 'up', interface])
logger.info('Started WireGuard interface %s', interface)
elif previous_content is None or interface_section(previous_content) != interface_section(content):
run_command(['wg-quick', 'down', interface], check=False)
run_command(['wg-quick', 'up', interface])
logger.info('Restarted WireGuard interface %s', interface)
elif previous_content != content:
self.sync_peers(interface, config_path)
logger.info('Synchronized peers of WireGuard interface %s', interface)
except SectionError as error:
errors.append(str(error))
# Back to the content actually applied, so the next attempt sees the change again
if previous_content is not None:
write_file(config_path, previous_content)
self.wireguard_active = True
if errors:
raise SectionError('; '.join(errors))
@staticmethod
def sync_peers(interface, config_path):
stripped_config = run_command(['wg-quick', 'strip', config_path]).stdout
with tempfile.NamedTemporaryFile('w', suffix='.conf', delete=False) as stripped_file:
stripped_file.write(stripped_config)
try:
run_command(['wg', 'syncconf', interface, stripped_file.name])
finally:
os.remove(stripped_file.name)
sync_interface_routes(interface)
def apply_dns(self, section):
files = section['files']
if DNS_MAIN_CONFIG not in files:
raise SectionError(f'{DNS_MAIN_CONFIG} missing from section')
os.makedirs(DNS_DIR, exist_ok=True)
for filename, content in files.items():
if filename == 'wg-firewall.sh' and isinstance(content, str):
content = content.replace('wireguard-webadmin-dns', 'cluster-node-dns')
filepath = os.path.join(WIREGUARD_DIR, filename)
with open(filepath, 'w') as f:
f.write(content)
if filename != DNS_MAIN_CONFIG and '/' not in filename:
write_file(os.path.join(DNS_DIR, filename), content, mode=0o644)
for config_path in glob.glob(os.path.join(DNS_DIR, '*.conf')):
if os.path.basename(config_path) not in files:
os.remove(config_path)
# Written last and in place: the DNS container watches this file with inotify to reload
write_file(os.path.join(DNS_DIR, DNS_MAIN_CONFIG), files[DNS_MAIN_CONFIG], mode=0o644, in_place=True)
if filename == 'wg-firewall.sh':
os.chmod(filepath, 0o755)
def apply_settings(self, section):
self.stats_interval = int(section['values'].get('stats_sync_interval', DEFAULT_STATS_INTERVAL))
# Start interfaces
conf_files = glob.glob(f"{WIREGUARD_DIR}/*.conf")
for conf in conf_files:
interface = os.path.basename(conf).replace('.conf', '')
logger.info(f"Starting WireGuard interface: {interface}")
def apply_certificates(self, section):
if not gateway_enabled():
return
files = {
filename: content for filename, content in section['files'].items()
if CERTIFICATE_FILE_PATTERN.match(filename)
}
for filename, content in files.items():
certificate_path = os.path.join(CERTIFICATES_DIR, filename)
if read_file(certificate_path) != content:
write_file(certificate_path, content, mode=0o600)
for certificate_path in glob.glob(os.path.join(CERTIFICATES_DIR, '*')):
if os.path.basename(certificate_path) not in files:
os.remove(certificate_path)
def apply_gateway(self, section):
if not gateway_enabled():
return
for filename in GATEWAY_FILES:
if filename not in section['files']:
raise SectionError(f'{filename} missing from section')
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,
'wireguard': apply_wireguard,
'dns': apply_dns,
'settings': apply_settings,
'certificates': apply_certificates,
'gateway': apply_gateway,
}
# Main loop
def shutdown_wireguard(self):
if not self.wireguard_active:
return
logger.warning('Shutting down WireGuard interfaces and firewall rules')
for config_path in glob.glob(os.path.join(WIREGUARD_DIR, 'wg[0-9]*.conf')):
run_command(['wg-quick', 'down', os.path.basename(config_path)[:-len('.conf')]], check=False)
for table, chain in FIREWALL_CHAINS:
run_command(['iptables', '-t', table, '-F', chain], check=False)
self.applied_hashes.pop('wireguard', None)
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:
return True
if response.status_code not in (200, 400, 403):
logger.error('Unexpected manifest response: HTTP %s', response.status_code)
return True
# Answers that do not come from the cluster API (a login page, a proxy error) never stop the worker
data = self.response_json(response, 'manifest/')
if data is None:
return True
if response.status_code == 403:
logger.error('Token rejected by the primary server. Stopping.')
self.shutdown_services()
return False
if response.status_code == 400:
logger.warning('Primary server refused this worker: %s', data.get('message', ''))
self.shutdown_services()
return True
manifest = data.get('sections', {})
reports = {}
for section_name, section_hash in manifest.items():
if section_name not in self.SECTION_HANDLERS or self.applied_hashes.get(section_name) == section_hash:
continue
section_response = self.request('GET', f'section/{section_name}/')
if section_response is None or section_response.status_code != 200:
continue
section = self.response_json(section_response, f'section/{section_name}/')
if section is None:
continue
try:
subprocess.run(['wg-quick', 'up', interface], check=True, capture_output=True)
except subprocess.CalledProcessError as e:
logger.error(f"Failed to start {interface}: {e.stderr.decode()}")
self.SECTION_HANDLERS[section_name](self, section)
self.applied_hashes[section_name] = section['hash']
reports[section_name] = {'hash': section['hash'], 'status': 'ok'}
logger.info('Section %s applied', section_name)
except (SectionError, OSError, ValueError) as error:
# Forget the last applied content: the next version must be applied and reported even if it
# is identical to the one that was applied before the failure
self.applied_hashes.pop(section_name, None)
reports[section_name] = {'hash': section['hash'], 'status': 'error', 'message': str(error)}
logger.error('Section %s failed: %s', section_name, error)
# 4. Update config version
self.config_version = new_config_version
logger.info(f"Configuration updated to version {self.config_version}")
if reports:
# Services are reported with the periodic stats: right after a DNS change dnsmasq is still reloading
self.request('POST', 'report/', json={'sections': reports})
return True
@staticmethod
def services_status():
services = {'dnsmasq': 'running' if dns_is_running() else 'stopped'}
if gateway_enabled():
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
def certificates_status():
try:
with open(os.path.join(GATEWAY_DIR, 'tls.json'), 'r', encoding='utf-8') as tls_file:
hosts = json.load(tls_file).get('hosts', {})
except (OSError, ValueError):
return {}
return {hostname: inspect_certificate(hostname) for hostname in sorted(hosts)}
@staticmethod
def gateway_sessions():
"""Sessions published by the auth-gateway and their hash, or (None, None) when not available."""
content = read_file(GATEWAY_SESSIONS_FILE)
if content is None:
return None, None
try:
sessions = json.loads(content).get('sessions')
except (ValueError, AttributeError):
return None, None
if not isinstance(sessions, list):
return None, None
return sessions, hashlib.sha256(content.encode()).hexdigest()
def send_stats(self):
try:
stats = self.func_process_wireguard_status()
params = {
'token': TOKEN,
'worker_config_version': self.config_version,
'worker_dns_version': self.dns_version,
'worker_version': WORKER_VERSION
report = {
'wireguard_status': wireguard_status(),
'services': self.services_status(),
}
logger.info("Sending WireGuard stats to Master...")
response = self.session.post(f"{self.base_url}/worker/submit_wireguard_stats/", json=stats, params=params, timeout=REQUEST_TIMEOUT)
sessions_hash = None
if gateway_enabled():
report['certificates'] = self.certificates_status()
sessions, sessions_hash = self.gateway_sessions()
if sessions_hash and sessions_hash != self.sent_sessions_hash:
report['gateway_sessions'] = sessions
response = self.request('POST', 'report/', json=report)
if 'gateway_sessions' in report and response is not None and response.status_code == 200:
self.sent_sessions_hash = sessions_hash
if response.status_code == 200:
logger.info("Stats sent successfully.")
return True
else:
logger.error(f"Failed to send stats. Status: {response.status_code}")
return False
except Exception as e:
logger.error(f"Error sending stats: {e}")
return False
@staticmethod
def publish_network_namespace():
# Containers sharing this network namespace (DNS, Caddy) restart themselves when it changes
network_namespace = os.readlink('/proc/self/ns/net')
for directory in (DNS_DIR, GATEWAY_DIR):
if os.path.isdir(directory):
write_file(os.path.join(directory, '.netns_owner'), network_namespace + '\n', mode=0o644)
def run(self):
if not self.should_run:
return
logger.info("Cluster Worker starting...")
# Initial cleanup
self.cleanup_wireguard()
last_config_check = 0
last_stats_send = 0
stats_sync_interval = 60 # Default initial value
logger.info('Cluster node agent %s starting', WORKER_VERSION)
self.publish_network_namespace()
self.wireguard_active = True
self.shutdown_wireguard()
last_manifest = 0
last_stats = 0
while True:
current_time = time.time()
# Check Config (Fixed 60s interval)
if current_time - last_config_check >= 60:
try:
response = self.get_status()
last_config_check = time.time()
if response is not None:
if response.status_code == 403:
logger.error("Received 403 Forbidden (Token invalid/deleted). Deactivating WireGuard and stopping requests permanently.")
self.cleanup_wireguard()
self.config_version = 0
self.should_run = False
now = time.monotonic()
if now - last_manifest >= MANIFEST_INTERVAL or not last_manifest:
last_manifest = now
if not self.sync_configuration():
break
if response.status_code == 400:
logger.warning("Received 400 Bad Request (Worker suspended or error). Deactivating WireGuard and Firewall, but will keep retrying...")
self.cleanup_wireguard()
self.config_version = 0
if response.status_code == 200:
data = response.json()
# Update stats interval from master settings
cluster_settings = data.get('cluster_settings', {})
stats_sync_interval = cluster_settings.get('stats_sync_interval', 60)
remote_config_version = cluster_settings.get('config_version', 0)
# Check WireGuard Config
updated = False
if int(remote_config_version) != self.config_version:
logger.info(f"Config version mismatch (Local: {self.config_version}, Remote: {remote_config_version}). Updating...")
config_data = self.download_configs()
if config_data:
self.apply_configs(config_data)
self.send_ping()
updated = True
else:
logger.error("Failed to download config files.")
# Check DNS Config
remote_dns_version = int(cluster_settings.get('dns_version', 0))
if not updated and remote_dns_version != self.dns_version:
logger.info(f"DNS version mismatch (Local: {self.dns_version}, Remote: {remote_dns_version}). Updating...")
if self.download_dns_config():
self.send_ping()
updated = True
if not updated and int(remote_config_version) == self.config_version and remote_dns_version == self.dns_version:
logger.info(f"No changes detected. Configuration is up to date (WG: {self.config_version}, DNS: {self.dns_version}).")
except Exception as e:
logger.error(f"Unexpected error in config check loop: {e}")
# Check Stats Sync
if current_time - last_stats_send >= stats_sync_interval:
if now - last_stats >= self.stats_interval:
last_stats = now
self.send_stats()
last_stats_send = time.time()
# Sleep briefly to be responsive but not busy loop
time.sleep(1)
# Final loop state if 403 was received
while not self.should_run:
logger.info("Worker disabled due to 403 Forbidden. WireGuard is off.")
time.sleep(60)
while True:
time.sleep(3600)
if __name__ == "__main__":
worker = ClusterWorker()
worker.run()
if __name__ == '__main__':
if not MASTER_SERVER_ADDRESS or not TOKEN:
logger.error('MASTER_SERVER_ADDRESS and TOKEN must be set')
else:
ClusterNodeAgent().run()
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/bash
set -e
if [[ "$COMPOSE_VERSION" != "c1b" ]]; then
if [[ "$COMPOSE_VERSION" != "c2a" ]]; then
echo "ERROR: Please upgrade your docker compose file. Exiting."
exit 1
fi
+5 -5
View File
@@ -1,5 +1,5 @@
certifi==2026.2.25
charset-normalizer==3.4.6
idna==3.11
requests==2.32.5
urllib3==2.6.3
certifi==2026.10.23
charset-normalizer==3.5.2
idna==3.20
requests==2.34.2
urllib3==2.8.0
+2 -2
View File
@@ -1,6 +1,6 @@
FROM ubuntu:latest
FROM debian:trixie-slim
RUN apt-get update && apt-get install -y cron curl && rm -rf /var/lib/apt/lists/*
RUN apt-get update && apt-get install -y --no-install-recommends cron curl ca-certificates procps && rm -rf /var/lib/apt/lists/*
COPY entrypoint.sh /entrypoint.sh
COPY cron_runner.sh /cron_runner.sh
+2 -2
View File
@@ -1,9 +1,9 @@
FROM ubuntu:latest
FROM debian:trixie-slim
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && \
apt-get install -y dnsmasq nano inotify-tools psmisc && \
apt-get install -y --no-install-recommends dnsmasq nano inotify-tools procps && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
+17
View File
@@ -34,7 +34,24 @@ handle_sigint() {
exit 0
}
# Written by cluster nodes, where this container shares the network namespace of the node. When the node
# container is restarted it gets a new namespace, so this container must restart to join it again.
NETNS_OWNER_FILE="/etc/dnsmasq/.netns_owner"
watch_network_namespace() {
while sleep 30; do
if [ -f "$NETNS_OWNER_FILE" ] && [ "$(cat "$NETNS_OWNER_FILE")" != "$(readlink /proc/self/ns/net)" ]; then
echo "Network namespace of the cluster node changed, restarting..."
kill -TERM 1
pkill inotifywait
return
fi
done
}
trap handle_sigint SIGINT
trap 'pkill dnsmasq; exit 1' SIGTERM
create_default_config
watch_network_namespace &
start_dnsmasq
+2 -5
View File
@@ -1,14 +1,11 @@
FROM python:3.12-slim
FROM python:3.14-slim
WORKDIR /app
RUN apt-get update && apt-get install -y \
RUN apt-get update && apt-get install -y --no-install-recommends \
net-tools \
inetutils-ping \
inetutils-traceroute \
nano \
vim-nox \
rrdtool \
librrd-dev \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
+5 -5
View File
@@ -1,5 +1,5 @@
certifi==2026.2.25
charset-normalizer==3.4.6
idna==3.11
requests==2.32.5
urllib3==2.6.3
certifi==2026.10.23
charset-normalizer==3.5.2
idna==3.20
requests==2.34.2
urllib3==2.8.0
+12 -52
View File
@@ -1,58 +1,8 @@
import os
import tarfile
from cluster.models import ClusterSettings
from .models import DNSSettings, StaticHost, DNSFilterList
def compress_dnsmasq_config():
output_file = "/etc/dnsmasq/dnsmasq_config.tar.gz"
base_dir = "/etc/dnsmasq"
cluster_settings = ClusterSettings.objects.filter(enabled=True, name='cluster_settings').first()
if not cluster_settings:
if os.path.exists(output_file):
os.remove(output_file)
return None
if not os.path.isdir(base_dir):
if os.path.exists(output_file):
os.remove(output_file)
return None
conf_files = [
fn for fn in os.listdir(base_dir)
if fn.endswith(".conf") and os.path.isfile(os.path.join(base_dir, fn))
]
# If tar exists and is newer (or equal) than all .conf, do not recompile
if os.path.exists(output_file):
tar_mtime = os.path.getmtime(output_file)
newest_conf_mtime = max(
os.path.getmtime(os.path.join(base_dir, fn)) for fn in conf_files
)
if newest_conf_mtime <= tar_mtime:
return output_file
# If we reach here, we need to increment DNS version and recompile the tar.gz
cluster_settings.dns_version += 1
cluster_settings.save()
dns_version_file = os.path.join(base_dir, "config_version.conf")
with open(dns_version_file, "w", encoding="utf-8") as f:
f.write(f"DNS_VERSION={cluster_settings.dns_version}\n")
if "config_version.conf" not in conf_files:
conf_files.append("config_version.conf")
# Create tar.gz
tmp_output = output_file + ".tmp"
with tarfile.open(tmp_output, "w:gz") as tar:
for fn in conf_files:
fullpath = os.path.join(base_dir, fn)
tar.add(fullpath, arcname=fn)
os.replace(tmp_output, output_file)
return output_file
def generate_unbound_config():
dns_settings = DNSSettings.objects.get(name='dns_settings')
static_hosts = StaticHost.objects.all()
@@ -106,11 +56,21 @@ def generate_dnsdist_config():
return dnsdist_config
def generate_dnsmasq_config():
def generate_dnsmasq_config(cluster_node=False):
dns_settings = DNSSettings.objects.get(name='dns_settings')
static_hosts = StaticHost.objects.all()
dns_lists = DNSFilterList.objects.filter(enabled=True)
dnsmasq_config = f'''
if cluster_node:
# On cluster nodes dnsmasq shares the network namespace of the node and must also answer on
# WireGuard interfaces created after it starts
dnsmasq_config = '''
no-dhcp-interface=
interface=wg*
bind-dynamic
'''
else:
dnsmasq_config = '''
no-dhcp-interface=
listen-address=0.0.0.0
bind-interfaces
+1 -2
View File
@@ -13,7 +13,7 @@ from django.utils.translation import gettext_lazy as _
from user_manager.models import UserAcl
from .forms import DNSFilterListForm
from .forms import DNSSettingsForm, StaticHostForm
from .functions import generate_dnsmasq_config, compress_dnsmasq_config
from .functions import generate_dnsmasq_config
from .models import DNSFilterList, DNSSettings
from .models import StaticHost
@@ -44,7 +44,6 @@ def export_dns_configuration():
dnsmasq_config = generate_dnsmasq_config()
with open(settings.DNS_CONFIG_FILE, 'w') as f:
f.write(dnsmasq_config)
compress_dnsmasq_config()
dns_settings, dns_settings_created = DNSSettings.objects.get_or_create(name='dns_settings')
dns_settings.pending_changes = False
dns_settings.save(update_fields=['pending_changes', 'updated'])
-339
View File
@@ -1,339 +0,0 @@
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Categories · wireguard_webadmin</title>
<meta name="description" content="Self-hosted VPN management and Zero Trust access control.">
<link rel="alternate" hreflang="en-us" href="https://wireguard-webadmin.com/categories/">
<link rel="alternate" hreflang="pt-BR" href="https://wireguard-webadmin.com/pt-br/categories/">
<link rel="alternate" hreflang="es" href="https://wireguard-webadmin.com/es/categories/">
<link rel="alternate" hreflang="fr" href="https://wireguard-webadmin.com/fr/categories/">
<link rel="alternate" hreflang="de" href="https://wireguard-webadmin.com/de/categories/">
<link rel="alternate" hreflang="x-default" href="https://wireguard-webadmin.com/">
<meta property="og:type" content="website">
<meta property="og:url" content="https://wireguard-webadmin.com/categories/">
<meta property="og:title" content="Categories · wireguard_webadmin">
<meta property="og:description" content="Self-hosted VPN management and Zero Trust access control.">
<meta property="og:image" content="https://wireguard-webadmin.com/og-image.png">
<meta property="og:image:width" content="1280">
<meta property="og:image:height" content="800">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Categories · wireguard_webadmin">
<meta name="twitter:description" content="Self-hosted VPN management and Zero Trust access control.">
<meta name="twitter:image" content="https://wireguard-webadmin.com/og-image.png">
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/css/main.min.css">
</head>
<body>
<header class="site-header">
<div class="container">
<nav class="nav-inner">
<a href="/" class="nav-logo">wireguard_<span>webadmin</span></a>
<button class="hamburger" aria-label="Toggle menu" aria-expanded="false">
<span></span><span></span><span></span>
</button>
<ul class="nav-links">
<li>
<a href="/"
>
Home
</a>
</li>
<li>
<a href="/zero-trust/"
>
Zero Trust
</a>
</li>
<li>
<a href="/deployment/"
>
Deployment
</a>
</li>
<li>
<a href="/get-involved/"
>
Get Involved
</a>
</li>
<li>
<a href="https://github.com/eduardogsilva/wireguard_webadmin"
target="_blank" rel="noopener"
class="nav-github">
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0C5.374 0 0 5.373 0 12c0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23A11.509 11.509 0 0 1 12 5.803c1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576C20.566 21.797 24 17.3 24 12c0-6.627-5.373-12-12-12z"/></svg>
GitHub
</a>
</li>
<li class="nav-lang-sep"></li>
<li class="lang-dropdown">
<button class="lang-btn" aria-expanded="false">
🇬🇧 EN
<svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor"><path d="M2 3.5L5 6.5L8 3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/></svg>
</button>
<ul class="lang-menu">
<li>
<a href="/categories/"
hreflang="en"
class="lang-active">
<span class="lang-flag">🇬🇧</span>
<span>English</span>
</a>
</li>
<li>
<a href="/pt-br/categories/"
hreflang="pt-br"
class="">
<span class="lang-flag">🇧🇷</span>
<span>Português</span>
</a>
</li>
<li>
<a href="/es/categories/"
hreflang="es"
class="">
<span class="lang-flag">🇪🇸</span>
<span>Español</span>
</a>
</li>
<li>
<a href="/fr/categories/"
hreflang="fr"
class="">
<span class="lang-flag">🇫🇷</span>
<span>Français</span>
</a>
</li>
<li>
<a href="/de/categories/"
hreflang="de"
class="">
<span class="lang-flag">🇩🇪</span>
<span>Deutsch</span>
</a>
</li>
</ul>
</li>
</ul>
</nav>
</div>
</header>
<main>
<div class="container" style="padding: 4rem 0">
<h1>Categories</h1>
</div>
</main>
<footer class="site-footer">
<div class="container">
<div class="footer-inner">
<div class="footer-logo">wireguard_<span>webadmin</span></div>
<ul class="footer-links">
<li><a href="https://github.com/eduardogsilva/wireguard_webadmin" target="_blank" rel="noopener">GitHub</a></li>
<li><a href="https://github.com/eduardogsilva/wireguard_webadmin/discussions" target="_blank" rel="noopener">Discussions</a></li>
<li><a href="/zero-trust/">Zero Trust</a></li>
<li><a href="/deployment/">Deployment</a></li>
<li><a href="/get-involved/">Get Involved</a></li>
</ul>
<div class="footer-built">
built by <a href="https://github.com/eduardogsilva" target="_blank" rel="noopener">@eduardogsilva</a>
</div>
</div>
</div>
</footer>
<script>
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', () => {
const group = btn.closest('.tab-group');
group.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
group.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
btn.classList.add('active');
group.querySelector('#' + btn.dataset.tab).classList.add('active');
});
});
const hamburger = document.querySelector('.hamburger');
const navLinks = document.querySelector('.nav-links');
if (hamburger) {
hamburger.addEventListener('click', (e) => {
e.stopPropagation();
const open = navLinks.classList.toggle('open');
hamburger.classList.toggle('open', open);
hamburger.setAttribute('aria-expanded', open);
});
document.addEventListener('click', (e) => {
if (!navLinks.contains(e.target) && !hamburger.contains(e.target)) {
navLinks.classList.remove('open');
hamburger.classList.remove('open');
hamburger.setAttribute('aria-expanded', false);
}
});
}
const langBtn = document.querySelector('.lang-btn');
const langDropdown = document.querySelector('.lang-dropdown');
if (langBtn) {
langBtn.addEventListener('click', (e) => {
e.stopPropagation();
const open = langDropdown.classList.toggle('open');
langBtn.setAttribute('aria-expanded', open);
});
document.addEventListener('click', (e) => {
if (!langDropdown.contains(e.target)) {
langDropdown.classList.remove('open');
langBtn.setAttribute('aria-expanded', false);
}
});
langDropdown.querySelectorAll('.lang-menu a').forEach(a => {
a.addEventListener('click', () => localStorage.setItem('lang-manual', '1'));
});
}
if (location.pathname === '/' && !localStorage.getItem('lang-manual')) {
const lang = (navigator.language || navigator.userLanguage || 'en').toLowerCase();
const map = [
{ prefix: 'pt', url: '/pt-br/' },
{ prefix: 'es', url: '/es/' },
{ prefix: 'fr', url: '/fr/' },
{ prefix: 'de', url: '/de/' },
];
const match = map.find(m => lang.startsWith(m.prefix));
if (match) location.replace(match.url);
}
</script>
</body>
</html>
-11
View File
@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Categories on wireguard_webadmin</title>
<link>https://wireguard-webadmin.com/categories/</link>
<description>Recent content in Categories on wireguard_webadmin</description>
<generator>Hugo</generator>
<language>en-us</language>
<atom:link href="https://wireguard-webadmin.com/categories/index.xml" rel="self" type="application/rss+xml" />
</channel>
</rss>
File diff suppressed because one or more lines are too long
-1
View File
File diff suppressed because one or more lines are too long
-339
View File
@@ -1,339 +0,0 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Categories · wireguard_webadmin</title>
<meta name="description" content="Self-hosted VPN management and Zero Trust access control.">
<link rel="alternate" hreflang="en-us" href="https://wireguard-webadmin.com/categories/">
<link rel="alternate" hreflang="pt-BR" href="https://wireguard-webadmin.com/pt-br/categories/">
<link rel="alternate" hreflang="es" href="https://wireguard-webadmin.com/es/categories/">
<link rel="alternate" hreflang="fr" href="https://wireguard-webadmin.com/fr/categories/">
<link rel="alternate" hreflang="de" href="https://wireguard-webadmin.com/de/categories/">
<link rel="alternate" hreflang="x-default" href="https://wireguard-webadmin.com/">
<meta property="og:type" content="website">
<meta property="og:url" content="https://wireguard-webadmin.com/de/categories/">
<meta property="og:title" content="Categories · wireguard_webadmin">
<meta property="og:description" content="Self-hosted VPN management and Zero Trust access control.">
<meta property="og:image" content="https://wireguard-webadmin.com/og-image.png">
<meta property="og:image:width" content="1280">
<meta property="og:image:height" content="800">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Categories · wireguard_webadmin">
<meta name="twitter:description" content="Self-hosted VPN management and Zero Trust access control.">
<meta name="twitter:image" content="https://wireguard-webadmin.com/og-image.png">
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/css/main.min.css">
</head>
<body>
<header class="site-header">
<div class="container">
<nav class="nav-inner">
<a href="/de/" class="nav-logo">wireguard_<span>webadmin</span></a>
<button class="hamburger" aria-label="Toggle menu" aria-expanded="false">
<span></span><span></span><span></span>
</button>
<ul class="nav-links">
<li>
<a href="/de/"
>
Start
</a>
</li>
<li>
<a href="/de/zero-trust/"
>
Zero Trust
</a>
</li>
<li>
<a href="/de/deployment/"
>
Installation
</a>
</li>
<li>
<a href="/de/get-involved/"
>
Mitmachen
</a>
</li>
<li>
<a href="https://github.com/eduardogsilva/wireguard_webadmin"
target="_blank" rel="noopener"
class="nav-github">
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0C5.374 0 0 5.373 0 12c0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23A11.509 11.509 0 0 1 12 5.803c1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576C20.566 21.797 24 17.3 24 12c0-6.627-5.373-12-12-12z"/></svg>
GitHub
</a>
</li>
<li class="nav-lang-sep"></li>
<li class="lang-dropdown">
<button class="lang-btn" aria-expanded="false">
🇩🇪 DE
<svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor"><path d="M2 3.5L5 6.5L8 3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/></svg>
</button>
<ul class="lang-menu">
<li>
<a href="/categories/"
hreflang="en"
class="">
<span class="lang-flag">🇬🇧</span>
<span>English</span>
</a>
</li>
<li>
<a href="/pt-br/categories/"
hreflang="pt-br"
class="">
<span class="lang-flag">🇧🇷</span>
<span>Português</span>
</a>
</li>
<li>
<a href="/es/categories/"
hreflang="es"
class="">
<span class="lang-flag">🇪🇸</span>
<span>Español</span>
</a>
</li>
<li>
<a href="/fr/categories/"
hreflang="fr"
class="">
<span class="lang-flag">🇫🇷</span>
<span>Français</span>
</a>
</li>
<li>
<a href="/de/categories/"
hreflang="de"
class="lang-active">
<span class="lang-flag">🇩🇪</span>
<span>Deutsch</span>
</a>
</li>
</ul>
</li>
</ul>
</nav>
</div>
</header>
<main>
<div class="container" style="padding: 4rem 0">
<h1>Categories</h1>
</div>
</main>
<footer class="site-footer">
<div class="container">
<div class="footer-inner">
<div class="footer-logo">wireguard_<span>webadmin</span></div>
<ul class="footer-links">
<li><a href="https://github.com/eduardogsilva/wireguard_webadmin" target="_blank" rel="noopener">GitHub</a></li>
<li><a href="https://github.com/eduardogsilva/wireguard_webadmin/discussions" target="_blank" rel="noopener">Discussions</a></li>
<li><a href="/de/zero-trust/">Zero Trust</a></li>
<li><a href="/de/deployment/">Deployment</a></li>
<li><a href="/de/get-involved/">Get Involved</a></li>
</ul>
<div class="footer-built">
entwickelt von <a href="https://github.com/eduardogsilva" target="_blank" rel="noopener">@eduardogsilva</a>
</div>
</div>
</div>
</footer>
<script>
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', () => {
const group = btn.closest('.tab-group');
group.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
group.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
btn.classList.add('active');
group.querySelector('#' + btn.dataset.tab).classList.add('active');
});
});
const hamburger = document.querySelector('.hamburger');
const navLinks = document.querySelector('.nav-links');
if (hamburger) {
hamburger.addEventListener('click', (e) => {
e.stopPropagation();
const open = navLinks.classList.toggle('open');
hamburger.classList.toggle('open', open);
hamburger.setAttribute('aria-expanded', open);
});
document.addEventListener('click', (e) => {
if (!navLinks.contains(e.target) && !hamburger.contains(e.target)) {
navLinks.classList.remove('open');
hamburger.classList.remove('open');
hamburger.setAttribute('aria-expanded', false);
}
});
}
const langBtn = document.querySelector('.lang-btn');
const langDropdown = document.querySelector('.lang-dropdown');
if (langBtn) {
langBtn.addEventListener('click', (e) => {
e.stopPropagation();
const open = langDropdown.classList.toggle('open');
langBtn.setAttribute('aria-expanded', open);
});
document.addEventListener('click', (e) => {
if (!langDropdown.contains(e.target)) {
langDropdown.classList.remove('open');
langBtn.setAttribute('aria-expanded', false);
}
});
langDropdown.querySelectorAll('.lang-menu a').forEach(a => {
a.addEventListener('click', () => localStorage.setItem('lang-manual', '1'));
});
}
if (location.pathname === '/' && !localStorage.getItem('lang-manual')) {
const lang = (navigator.language || navigator.userLanguage || 'en').toLowerCase();
const map = [
{ prefix: 'pt', url: '/pt-br/' },
{ prefix: 'es', url: '/es/' },
{ prefix: 'fr', url: '/fr/' },
{ prefix: 'de', url: '/de/' },
];
const match = map.find(m => lang.startsWith(m.prefix));
if (match) location.replace(match.url);
}
</script>
</body>
</html>
-11
View File
@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Categories on wireguard_webadmin</title>
<link>https://wireguard-webadmin.com/de/categories/</link>
<description>Recent content in Categories on wireguard_webadmin</description>
<generator>Hugo</generator>
<language>de</language>
<atom:link href="https://wireguard-webadmin.com/de/categories/index.xml" rel="self" type="application/rss+xml" />
</channel>
</rss>
+49 -22
View File
@@ -9,6 +9,7 @@
<title>Installationsanleitung · wireguard_webadmin</title>
<meta name="description" content="Schritt-für-Schritt-Anleitung für die Bereitstellung von wireguard_webadmin mit Docker Compose, Caddy und automatischem HTTPS.">
<link rel="canonical" href="https://wireguard-webadmin.com/de/deployment/">
@@ -29,25 +30,34 @@
<meta property="og:url" content="https://wireguard-webadmin.com/de/deployment/">
<meta property="og:title" content="Installationsanleitung · wireguard_webadmin">
<meta property="og:description" content="Schritt-für-Schritt-Anleitung für die Bereitstellung von wireguard_webadmin mit Docker Compose, Caddy und automatischem HTTPS.">
<meta property="og:image" content="https://wireguard-webadmin.com/og-image.png">
<meta property="og:image:width" content="1280">
<meta property="og:image:height" content="800">
<meta property="og:locale" content="de_DE">
<meta property="og:locale:alternate" content="en_US">
<meta property="og:locale:alternate" content="pt_BR">
<meta property="og:locale:alternate" content="es_ES">
<meta property="og:locale:alternate" content="fr_FR">
<meta property="og:image" content="https://wireguard-webadmin.com/images/peer_list_dark_hu_84f9807efbbcd67e.jpg">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Installationsanleitung · wireguard_webadmin">
<meta name="twitter:description" content="Schritt-für-Schritt-Anleitung für die Bereitstellung von wireguard_webadmin mit Docker Compose, Caddy und automatischem HTTPS.">
<meta name="twitter:image" content="https://wireguard-webadmin.com/og-image.png">
<meta name="twitter:image" content="https://wireguard-webadmin.com/images/peer_list_dark_hu_84f9807efbbcd67e.jpg">
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">
<link rel="preload" href="/fonts/inter-latin-wght-normal.woff2" as="font" type="font/woff2" crossorigin>
<link rel="stylesheet" href="/css/main.min.css">
<link rel="stylesheet" href="/css/main.min.09e588a4a25bba0c0a964ce43747e8b70b3bde1ddf6d8c884a5d0338d93f3447.css">
</head>
<body>
@@ -55,10 +65,10 @@
<div class="container">
<nav class="nav-inner">
<a href="/de/" class="nav-logo">wireguard_<span>webadmin</span></a>
<button class="hamburger" aria-label="Toggle menu" aria-expanded="false">
<button class="hamburger" aria-label="Toggle menu" aria-controls="site-nav" aria-expanded="false">
<span></span><span></span><span></span>
</button>
<ul class="nav-links">
<ul class="nav-links" id="site-nav">
<li>
@@ -83,6 +93,17 @@
</li>
<li>
<a href="/de/wireguard-cluster/"
>
Cluster
</a>
</li>
<li>
<a href="/de/deployment/"
@@ -119,11 +140,11 @@
<li class="nav-lang-sep"></li>
<li class="lang-dropdown">
<button class="lang-btn" aria-expanded="false">
<button class="lang-btn" aria-label="Language" aria-controls="lang-menu" aria-expanded="false">
🇩🇪 DE
<svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor"><path d="M2 3.5L5 6.5L8 3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/></svg>
</button>
<ul class="lang-menu">
<ul class="lang-menu" id="lang-menu">
@@ -373,9 +394,8 @@ TIMEZONE=America/Sao_Paulo</code></pre>
<div class="deploy-step-card">
<div class="deploy-step-num">02</div>
<div class="deploy-step-body">
<div class="deploy-step-label">Dienste stoppen und neueste Images abrufen</div>
<pre><code>docker compose down
docker compose pull</code></pre>
<div class="deploy-step-label">Dienste stoppen</div>
<pre><code>docker compose down</code></pre>
</div>
</div>
<div class="deploy-step-card">
@@ -398,8 +418,9 @@ docker compose pull</code></pre>
<div class="deploy-step-card">
<div class="deploy-step-num">05</div>
<div class="deploy-step-body">
<div class="deploy-step-label">Aktualisierten Stack starten</div>
<pre><code>docker compose up -d</code></pre>
<div class="deploy-step-label">Neueste Images abrufen und Stack starten</div>
<pre><code>docker compose pull
docker compose up -d</code></pre>
</div>
</div>
<div class="deploy-step-card">
@@ -459,10 +480,11 @@ docker compose pull</code></pre>
<div class="footer-logo">wireguard_<span>webadmin</span></div>
<ul class="footer-links">
<li><a href="https://github.com/eduardogsilva/wireguard_webadmin" target="_blank" rel="noopener">GitHub</a></li>
<li><a href="https://github.com/eduardogsilva/wireguard_webadmin/discussions" target="_blank" rel="noopener">Discussions</a></li>
<li><a href="https://github.com/eduardogsilva/wireguard_webadmin/discussions" target="_blank" rel="noopener">Diskussionen</a></li>
<li><a href="/de/zero-trust/">Zero Trust</a></li>
<li><a href="/de/deployment/">Deployment</a></li>
<li><a href="/de/get-involved/">Get Involved</a></li>
<li><a href="/de/wireguard-cluster/">Cluster</a></li>
<li><a href="/de/deployment/">Installation</a></li>
<li><a href="/de/get-involved/">Mitmachen</a></li>
</ul>
<div class="footer-built">
entwickelt von <a href="https://github.com/eduardogsilva" target="_blank" rel="noopener">@eduardogsilva</a>
@@ -519,12 +541,17 @@ if (langBtn) {
});
langDropdown.querySelectorAll('.lang-menu a').forEach(a => {
a.addEventListener('click', () => localStorage.setItem('lang-manual', '1'));
a.addEventListener('click', () => {
try { localStorage.setItem('lang-manual', '1'); } catch (err) { }
});
});
}
if (location.pathname === '/' && !localStorage.getItem('lang-manual')) {
let langManual = false;
try { langManual = !!localStorage.getItem('lang-manual'); } catch (err) { langManual = true; }
if (location.pathname === '/' && !langManual) {
const lang = (navigator.language || navigator.userLanguage || 'en').toLowerCase();
const map = [
{ prefix: 'pt', url: '/pt-br/' },
+44 -17
View File
@@ -9,6 +9,7 @@
<title>Mitmachen · wireguard_webadmin</title>
<meta name="description" content="Möglichkeiten, zu wireguard_webadmin beizutragen: Fehler melden, Code schreiben oder das Projekt einfach weiterempfehlen.">
<link rel="canonical" href="https://wireguard-webadmin.com/de/get-involved/">
@@ -29,25 +30,34 @@
<meta property="og:url" content="https://wireguard-webadmin.com/de/get-involved/">
<meta property="og:title" content="Mitmachen · wireguard_webadmin">
<meta property="og:description" content="Möglichkeiten, zu wireguard_webadmin beizutragen: Fehler melden, Code schreiben oder das Projekt einfach weiterempfehlen.">
<meta property="og:image" content="https://wireguard-webadmin.com/og-image.png">
<meta property="og:image:width" content="1280">
<meta property="og:image:height" content="800">
<meta property="og:locale" content="de_DE">
<meta property="og:locale:alternate" content="en_US">
<meta property="og:locale:alternate" content="pt_BR">
<meta property="og:locale:alternate" content="es_ES">
<meta property="og:locale:alternate" content="fr_FR">
<meta property="og:image" content="https://wireguard-webadmin.com/images/peer_list_dark_hu_84f9807efbbcd67e.jpg">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Mitmachen · wireguard_webadmin">
<meta name="twitter:description" content="Möglichkeiten, zu wireguard_webadmin beizutragen: Fehler melden, Code schreiben oder das Projekt einfach weiterempfehlen.">
<meta name="twitter:image" content="https://wireguard-webadmin.com/og-image.png">
<meta name="twitter:image" content="https://wireguard-webadmin.com/images/peer_list_dark_hu_84f9807efbbcd67e.jpg">
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">
<link rel="preload" href="/fonts/inter-latin-wght-normal.woff2" as="font" type="font/woff2" crossorigin>
<link rel="stylesheet" href="/css/main.min.css">
<link rel="stylesheet" href="/css/main.min.09e588a4a25bba0c0a964ce43747e8b70b3bde1ddf6d8c884a5d0338d93f3447.css">
</head>
<body>
@@ -55,10 +65,10 @@
<div class="container">
<nav class="nav-inner">
<a href="/de/" class="nav-logo">wireguard_<span>webadmin</span></a>
<button class="hamburger" aria-label="Toggle menu" aria-expanded="false">
<button class="hamburger" aria-label="Toggle menu" aria-controls="site-nav" aria-expanded="false">
<span></span><span></span><span></span>
</button>
<ul class="nav-links">
<ul class="nav-links" id="site-nav">
<li>
@@ -83,6 +93,17 @@
</li>
<li>
<a href="/de/wireguard-cluster/"
>
Cluster
</a>
</li>
<li>
<a href="/de/deployment/"
@@ -119,11 +140,11 @@
<li class="nav-lang-sep"></li>
<li class="lang-dropdown">
<button class="lang-btn" aria-expanded="false">
<button class="lang-btn" aria-label="Language" aria-controls="lang-menu" aria-expanded="false">
🇩🇪 DE
<svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor"><path d="M2 3.5L5 6.5L8 3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/></svg>
</button>
<ul class="lang-menu">
<ul class="lang-menu" id="lang-menu">
@@ -296,10 +317,11 @@
<div class="footer-logo">wireguard_<span>webadmin</span></div>
<ul class="footer-links">
<li><a href="https://github.com/eduardogsilva/wireguard_webadmin" target="_blank" rel="noopener">GitHub</a></li>
<li><a href="https://github.com/eduardogsilva/wireguard_webadmin/discussions" target="_blank" rel="noopener">Discussions</a></li>
<li><a href="https://github.com/eduardogsilva/wireguard_webadmin/discussions" target="_blank" rel="noopener">Diskussionen</a></li>
<li><a href="/de/zero-trust/">Zero Trust</a></li>
<li><a href="/de/deployment/">Deployment</a></li>
<li><a href="/de/get-involved/">Get Involved</a></li>
<li><a href="/de/wireguard-cluster/">Cluster</a></li>
<li><a href="/de/deployment/">Installation</a></li>
<li><a href="/de/get-involved/">Mitmachen</a></li>
</ul>
<div class="footer-built">
entwickelt von <a href="https://github.com/eduardogsilva" target="_blank" rel="noopener">@eduardogsilva</a>
@@ -356,12 +378,17 @@ if (langBtn) {
});
langDropdown.querySelectorAll('.lang-menu a').forEach(a => {
a.addEventListener('click', () => localStorage.setItem('lang-manual', '1'));
a.addEventListener('click', () => {
try { localStorage.setItem('lang-manual', '1'); } catch (err) { }
});
});
}
if (location.pathname === '/' && !localStorage.getItem('lang-manual')) {
let langManual = false;
try { langManual = !!localStorage.getItem('lang-manual'); } catch (err) { langManual = true; }
if (location.pathname === '/' && !langManual) {
const lang = (navigator.language || navigator.userLanguage || 'en').toLowerCase();
const map = [
{ prefix: 'pt', url: '/pt-br/' },
+157 -63
View File
@@ -1,15 +1,16 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta name="generator" content="Hugo 0.158.0">
<meta name="generator" content="Hugo 0.164.0">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>wireguard_webadmin — Self-hosted VPN management and Zero Trust access control.</title>
<meta name="description" content="Self-hosted VPN management and Zero Trust access control.">
<title>wireguard_webadmin — Selbst gehostete WireGuard-VPN-Verwaltung und Zero-Trust-Zugriffskontrolle.</title>
<meta name="description" content="Selbst gehostete WireGuard-VPN-Verwaltung und Zero-Trust-Zugriffskontrolle.">
<link rel="canonical" href="https://wireguard-webadmin.com/de/">
@@ -28,27 +29,36 @@
<meta property="og:type" content="website">
<meta property="og:url" content="https://wireguard-webadmin.com/de/">
<meta property="og:title" content="wireguard_webadmin — Self-hosted VPN management and Zero Trust access control.">
<meta property="og:description" content="Self-hosted VPN management and Zero Trust access control.">
<meta property="og:image" content="https://wireguard-webadmin.com/og-image.png">
<meta property="og:image:width" content="1280">
<meta property="og:image:height" content="800">
<meta property="og:title" content="wireguard_webadmin — Selbst gehostete WireGuard-VPN-Verwaltung und Zero-Trust-Zugriffskontrolle.">
<meta property="og:description" content="Selbst gehostete WireGuard-VPN-Verwaltung und Zero-Trust-Zugriffskontrolle.">
<meta property="og:locale" content="de_DE">
<meta property="og:locale:alternate" content="en_US">
<meta property="og:locale:alternate" content="pt_BR">
<meta property="og:locale:alternate" content="es_ES">
<meta property="og:locale:alternate" content="fr_FR">
<meta property="og:image" content="https://wireguard-webadmin.com/images/peer_list_dark_hu_84f9807efbbcd67e.jpg">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="wireguard_webadmin — Self-hosted VPN management and Zero Trust access control.">
<meta name="twitter:description" content="Self-hosted VPN management and Zero Trust access control.">
<meta name="twitter:image" content="https://wireguard-webadmin.com/og-image.png">
<meta name="twitter:title" content="wireguard_webadmin — Selbst gehostete WireGuard-VPN-Verwaltung und Zero-Trust-Zugriffskontrolle.">
<meta name="twitter:description" content="Selbst gehostete WireGuard-VPN-Verwaltung und Zero-Trust-Zugriffskontrolle.">
<meta name="twitter:image" content="https://wireguard-webadmin.com/images/peer_list_dark_hu_84f9807efbbcd67e.jpg">
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">
<link rel="preload" href="/fonts/inter-latin-wght-normal.woff2" as="font" type="font/woff2" crossorigin>
<link rel="stylesheet" href="/css/main.min.css">
<link rel="stylesheet" href="/css/main.min.09e588a4a25bba0c0a964ce43747e8b70b3bde1ddf6d8c884a5d0338d93f3447.css">
</head>
<body>
@@ -56,10 +66,10 @@
<div class="container">
<nav class="nav-inner">
<a href="/de/" class="nav-logo">wireguard_<span>webadmin</span></a>
<button class="hamburger" aria-label="Toggle menu" aria-expanded="false">
<button class="hamburger" aria-label="Toggle menu" aria-controls="site-nav" aria-expanded="false">
<span></span><span></span><span></span>
</button>
<ul class="nav-links">
<ul class="nav-links" id="site-nav">
<li>
@@ -84,6 +94,17 @@
</li>
<li>
<a href="/de/wireguard-cluster/"
>
Cluster
</a>
</li>
<li>
<a href="/de/deployment/"
@@ -120,11 +141,11 @@
<li class="nav-lang-sep"></li>
<li class="lang-dropdown">
<button class="lang-btn" aria-expanded="false">
<button class="lang-btn" aria-label="Language" aria-controls="lang-menu" aria-expanded="false">
🇩🇪 DE
<svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor"><path d="M2 3.5L5 6.5L8 3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/></svg>
</button>
<ul class="lang-menu">
<ul class="lang-menu" id="lang-menu">
@@ -263,12 +284,22 @@
</div>
<div class="hero-screenshot">
<div class="theme-crossfade">
<img class="crossfade-light" src="/images/peer_list_light.png" alt="wireguard_webadmin — light mode" loading="eager">
<img class="crossfade-dark" src="/images/peer_list_dark.png" alt="wireguard_webadmin — dark mode" loading="eager">
<img src="/images/peer_list_light_hu_41b4e37913d7198d.webp"
srcset="/images/peer_list_light_hu_ae642b854957e1f.webp 640w, /images/peer_list_light_hu_ff0eed683df6254f.webp 1052w, /images/peer_list_light_hu_2f8d3c386c08a62f.webp 1600w, /images/peer_list_light_hu_41b4e37913d7198d.webp 2104w"
sizes="(max-width: 1100px) 100vw, 1052px"
width="2104" height="1374"
alt="wireguard_webadmin — light mode"
loading="eager" decoding="async" class="crossfade-light" fetchpriority="low">
<img src="/images/peer_list_dark_hu_4bf4afa038dc5062.webp"
srcset="/images/peer_list_dark_hu_7da119c0ec44d949.webp 640w, /images/peer_list_dark_hu_22e4f57b9e418f74.webp 1052w, /images/peer_list_dark_hu_8a85261e6a2236cc.webp 1600w, /images/peer_list_dark_hu_4bf4afa038dc5062.webp 2104w"
sizes="(max-width: 1100px) 100vw, 1052px"
width="2104" height="1378"
alt="wireguard_webadmin — dark mode"
loading="eager" decoding="async" class="crossfade-dark" fetchpriority="high">
</div>
</div>
@@ -287,14 +318,14 @@
<div class="pillar-icon">⚙️</div>
<h3>Verwalten</h3>
<ul class="pillar-list">
<li>Mehrere WireGuard-Instanzen</li><li>Peer-Verwaltung mit Traffic-Diagrammen</li><li>Firewall-Regeln &amp; Port-Weiterleitung</li><li>DNS-Resolver mit Sperrlisten</li><li>VPN-Einladungslinks mit QR-Code</li>
<li>Mehrere WireGuard-Instanzen</li><li>Peer-Verwaltung mit Traffic-Diagrammen</li><li>Firewall-Regeln &amp; Port-Weiterleitung</li><li>DNS-Resolver mit Sperrlisten</li><li>VPN-Einladungslinks mit QR-Code</li><li>WireGuard-Cluster mit mehreren Knoten</li>
</ul>
</div>
<div class="pillar-card">
<div class="pillar-icon">🔒</div>
<h3>Schützen</h3>
<ul class="pillar-list">
<li>Zero-Trust-Anwendungs-Gateway</li><li>TOTP-Zwei-Faktor-Authentifizierung</li><li>Altcha Proof-of-Work gegen Brute Force</li><li>IP-ACL pro Anwendung</li><li>OIDC demnächst verfügbar</li>
<li>Zero-Trust-Anwendungs-Gateway</li><li>TOTP-Zwei-Faktor-Authentifizierung</li><li>Altcha Proof-of-Work gegen Brute Force</li><li>IP-ACL pro Anwendung</li><li>Zugriffsrichtlinien pro Anwendung und Route</li><li>OIDC demnächst verfügbar</li>
</ul>
</div>
<div class="pillar-card">
@@ -324,10 +355,12 @@
<a href="/de/zero-trust/" class="btn btn-outline">Mehr erfahren →</a>
</div>
<div class="spotlight-image">
<img src="/images/zero_trust_app.png" alt="Zero Trust application gateway" loading="lazy">
<img src="/images/zero_trust_app_hu_ad51322c18eb0c18.webp"
srcset="/images/zero_trust_app_hu_8b27ff07d0921ecd.webp 480w, /images/zero_trust_app_hu_9cf0f8719f62e82c.webp 800w, /images/zero_trust_app_hu_7fe66f5dc15faa3d.webp 1200w, /images/zero_trust_app_hu_ad51322c18eb0c18.webp 1600w"
sizes="(max-width: 860px) 100vw, 520px"
width="1600" height="1039"
alt="Zero Trust application gateway"
loading="lazy" decoding="async">
</div>
</div>
</div>
@@ -338,19 +371,23 @@
<div class="container">
<div class="spotlight reverse">
<div class="spotlight-content">
<div class="section-label">Sichtbarkeit</div>
<h2>Vollständige Transparenz über jeden Peer.</h2>
<p>Jeder Peer erhält eine eigene Detailansicht: Verbindungsstatus in Echtzeit, kumulierter Traffic, Bandbreitendiagramme als Zeitreihe, letzter Handshake und ein QR-Code für die sofortige erneute Bereitstellung.</p>
<p>Der Traffic-Verlauf wird pro Peer gespeichert, damit Sie die Nutzung im Zeitverlauf prüfen können und nicht nur seit dem letzten Neustart.</p>
<div class="section-label">Cluster</div>
<h2>Skalieren mit einem WireGuard-Cluster.</h2>
<p>Fügen Sie Worker-Knoten hinzu und verwalten Sie alle über ein einziges Panel. Der primäre Server hält die Konfiguration, und jeder Knoten erhält WireGuard, Firewall und DNS per automatischer Synchronisierung.</p>
<p>Betreiben Sie jede Instanz auf jedem Knoten (Spiegelmodus), damit Peers jeden Server nutzen können, oder binden Sie jede Instanz an einen Knoten (verteilter Modus). Knoten können auch Ihre App-Gateway-Anwendungen veröffentlichen.</p>
<div class="tag-list">
<span class="tag blue">Traffic-Diagramme</span><span class="tag green">Letzter Handshake</span><span class="tag ">QR-Code</span><span class="tag ">Verlauf pro Peer</span>
<span class="tag blue">Spiegelmodus</span><span class="tag green">Verteilt</span><span class="tag purple">Automatische Synchronisierung</span><span class="tag ">Health Checks</span>
</div>
<br>
<a href="/de/wireguard-cluster/" class="btn btn-outline">Mehr erfahren →</a>
</div>
<div class="spotlight-image">
<img src="/images/peer_details.png" alt="Peer details — traffic graph and metrics" loading="lazy">
<img src="/images/cluster_workers_hu_d6a3ce35efaf8802.webp"
srcset="/images/cluster_workers_hu_364e5f78ba96e8ab.webp 480w, /images/cluster_workers_hu_e4c333eb232b7f27.webp 800w, /images/cluster_workers_hu_4bb8d2a1ddb8a4df.webp 1200w, /images/cluster_workers_hu_d6a3ce35efaf8802.webp 1600w"
sizes="(max-width: 860px) 100vw, 520px"
width="1600" height="1039"
alt="WireGuard cluster workers"
loading="lazy" decoding="async">
</div>
</div>
</div>
@@ -360,6 +397,31 @@
<section>
<div class="container">
<div class="spotlight">
<div class="spotlight-content">
<div class="section-label">Sichtbarkeit</div>
<h2>Vollständige Transparenz über jeden Peer.</h2>
<p>Jeder Peer erhält eine eigene Detailansicht: Verbindungsstatus in Echtzeit, kumulierter Traffic, Bandbreitendiagramme als Zeitreihe, letzter Handshake und ein QR-Code für die sofortige erneute Bereitstellung.</p>
<p>Der Traffic-Verlauf wird pro Peer gespeichert, damit Sie die Nutzung im Zeitverlauf prüfen können und nicht nur seit dem letzten Neustart.</p>
<div class="tag-list">
<span class="tag blue">Traffic-Diagramme</span><span class="tag green">Letzter Handshake</span><span class="tag ">QR-Code</span><span class="tag ">Verlauf pro Peer</span>
</div>
</div>
<div class="spotlight-image">
<img src="/images/peer_details_hu_dcbb18e37de632a0.webp"
srcset="/images/peer_details_hu_53a5c60f4a73a070.webp 480w, /images/peer_details_hu_68f94fe6a280c19d.webp 800w, /images/peer_details_hu_40bdd3adae4ecbe7.webp 1200w, /images/peer_details_hu_dcbb18e37de632a0.webp 1600w"
sizes="(max-width: 860px) 100vw, 520px"
width="1600" height="1039"
alt="Peer details — traffic graph and metrics"
loading="lazy" decoding="async">
</div>
</div>
</div>
</section>
<section>
<div class="container">
<div class="spotlight reverse">
<div class="spotlight-content">
<div class="section-label">Automatisierung</div>
<h2>Zeitbasierte Peer-Zugriffskontrolle.</h2>
@@ -370,10 +432,12 @@
</div>
</div>
<div class="spotlight-image">
<img src="/images/scheduler.png" alt="Peer scheduling interface" loading="lazy">
<img src="/images/scheduler_hu_3f85c44e097e161f.webp"
srcset="/images/scheduler_hu_32ff737a391a47a0.webp 480w, /images/scheduler_hu_c3e2ff2e49ecfb8b.webp 800w, /images/scheduler_hu_f85d6fe4d5f99b7c.webp 1200w, /images/scheduler_hu_3f85c44e097e161f.webp 1600w"
sizes="(max-width: 860px) 100vw, 520px"
width="1600" height="1039"
alt="Peer scheduling interface"
loading="lazy" decoding="async">
</div>
</div>
</div>
@@ -393,8 +457,12 @@
<div class="screenshot-item">
<img src="/images/firewall.png" alt="Firewall rule management" loading="lazy">
<img src="/images/firewall_hu_af56a3ac9de09e7e.webp"
srcset="/images/firewall_hu_281f1f3d8679e98.webp 480w, /images/firewall_hu_d5048325867c082.webp 800w, /images/firewall_hu_af56a3ac9de09e7e.webp 1100w"
sizes="(max-width: 600px) 100vw, 540px"
width="1100" height="714"
alt="Firewall rule management"
loading="lazy" decoding="async">
<div class="screenshot-caption">
<span class="screenshot-label">Firewall</span>
<p>Instanzspezifische iptables-Regeln, Port-Weiterleitungen und ausgehende ACLs, alles über die Benutzeroberfläche verwaltet.</p>
@@ -404,8 +472,12 @@
<div class="screenshot-item">
<img src="/images/dns.png" alt="DNS management with blacklists" loading="lazy">
<img src="/images/dns_hu_8b3a35d7c52232f8.webp"
srcset="/images/dns_hu_27d1181205bcc614.webp 480w, /images/dns_hu_d10e4ea23c8ad871.webp 800w, /images/dns_hu_8b3a35d7c52232f8.webp 1100w"
sizes="(max-width: 600px) 100vw, 540px"
width="1100" height="714"
alt="DNS management with blacklists"
loading="lazy" decoding="async">
<div class="screenshot-caption">
<span class="screenshot-label">DNS</span>
<p>Integrierter Resolver mit kategoriebasierten Sperrlisten: Werbung, Malware, Tracking und nicht jugendfreie Inhalte.</p>
@@ -415,8 +487,12 @@
<div class="screenshot-item">
<img src="/images/vpn_invite.png" alt="VPN invite link with QR code" loading="lazy">
<img src="/images/vpn_invite_hu_421d6efc027117e7.webp"
srcset="/images/vpn_invite_hu_c90822e919430eac.webp 480w, /images/vpn_invite_hu_f33223666de50dcd.webp 800w, /images/vpn_invite_hu_421d6efc027117e7.webp 1100w"
sizes="(max-width: 600px) 100vw, 540px"
width="1100" height="1469"
alt="VPN invite link with QR code"
loading="lazy" decoding="async">
<div class="screenshot-caption">
<span class="screenshot-label">Einladungslinks</span>
<p>Erstellen Sie einen teilbaren Link mit QR-Code und Konfigurationsdatei. Die Person scannt oder importiert ihn direkt in ihren WireGuard-Client.</p>
@@ -426,8 +502,12 @@
<div class="screenshot-item">
<img src="/images/routing_template.png" alt="Routing templates" loading="lazy">
<img src="/images/routing_template_hu_de4bfedc96db4d16.webp"
srcset="/images/routing_template_hu_591432f85529b059.webp 480w, /images/routing_template_hu_3a7d74fd2c21fc3b.webp 800w, /images/routing_template_hu_de4bfedc96db4d16.webp 1100w"
sizes="(max-width: 600px) 100vw, 540px"
width="1100" height="714"
alt="Routing templates"
loading="lazy" decoding="async">
<div class="screenshot-caption">
<span class="screenshot-label">Routing-Vorlagen</span>
<p>Definieren Sie erlaubte IPs und Routing-Richtlinien einmal und verwenden Sie sie für Dutzende von Peers wieder.</p>
@@ -556,6 +636,22 @@
</div>
</div>
<div class="feature-item">
<div class="feature-icon">🌐</div>
<div>
<h4>Cluster</h4>
<p>Gespiegelte oder verteilte Knoten, ein Panel</p>
</div>
</div>
<div class="feature-item">
<div class="feature-icon">🔀</div>
<div>
<h4>Site-to-Site-Peers</h4>
<p>Verbindung zu entfernten WireGuard-Servern</p>
</div>
</div>
</div>
</div>
</section>
@@ -576,14 +672,6 @@
</div>
</div>
<div class="roadmap-item">
<div class="roadmap-badge wip">In Entwicklung</div>
<div>
<h4>App Gateway / Gatekeeper v2</h4>
<p>Ein leistungsfähigeres Application Gateway mit granularen Richtlinien pro Route, Sitzungsverwaltung und verbessertem Audit-Logging.</p>
</div>
</div>
<div class="roadmap-item">
<div class="roadmap-badge planned">Geplant</div>
<div>
@@ -605,10 +693,11 @@
<div class="footer-logo">wireguard_<span>webadmin</span></div>
<ul class="footer-links">
<li><a href="https://github.com/eduardogsilva/wireguard_webadmin" target="_blank" rel="noopener">GitHub</a></li>
<li><a href="https://github.com/eduardogsilva/wireguard_webadmin/discussions" target="_blank" rel="noopener">Discussions</a></li>
<li><a href="https://github.com/eduardogsilva/wireguard_webadmin/discussions" target="_blank" rel="noopener">Diskussionen</a></li>
<li><a href="/de/zero-trust/">Zero Trust</a></li>
<li><a href="/de/deployment/">Deployment</a></li>
<li><a href="/de/get-involved/">Get Involved</a></li>
<li><a href="/de/wireguard-cluster/">Cluster</a></li>
<li><a href="/de/deployment/">Installation</a></li>
<li><a href="/de/get-involved/">Mitmachen</a></li>
</ul>
<div class="footer-built">
entwickelt von <a href="https://github.com/eduardogsilva" target="_blank" rel="noopener">@eduardogsilva</a>
@@ -665,12 +754,17 @@ if (langBtn) {
});
langDropdown.querySelectorAll('.lang-menu a').forEach(a => {
a.addEventListener('click', () => localStorage.setItem('lang-manual', '1'));
a.addEventListener('click', () => {
try { localStorage.setItem('lang-manual', '1'); } catch (err) { }
});
});
}
if (location.pathname === '/' && !localStorage.getItem('lang-manual')) {
let langManual = false;
try { langManual = !!localStorage.getItem('lang-manual'); } catch (err) { langManual = true; }
if (location.pathname === '/' && !langManual) {
const lang = (navigator.language || navigator.userLanguage || 'en').toLowerCase();
const map = [
{ prefix: 'pt', url: '/pt-br/' },
+11
View File
@@ -6,6 +6,10 @@
<description>Recent content on wireguard_webadmin</description>
<generator>Hugo</generator>
<language>de</language>
<atom:link href="https://wireguard-webadmin.com/de/index.xml" rel="self" type="application/rss+xml" />
<item>
<title>Installationsanleitung</title>
@@ -21,6 +25,13 @@
<guid>https://wireguard-webadmin.com/de/get-involved/</guid>
<description>&lt;div class=&#34;involve-grid&#34;&gt;&#xA; &lt;div class=&#34;involve-card involve-card--highlight&#34;&gt;&#xA; &lt;div class=&#34;involve-card-icon&#34;&gt;⭐&lt;/div&gt;&#xA; &lt;h3&gt;Repository mit einem Stern markieren&lt;/h3&gt;&#xA; &lt;p&gt;Das Einfachste, was Sie tun können. Es hilft dem Projekt, von anderen Sysadmins entdeckt zu werden, die genau nach so etwas suchen.&lt;/p&gt;&#xA; &lt;a href=&#34;https://github.com/eduardogsilva/wireguard_webadmin&#34; target=&#34;_blank&#34; rel=&#34;noopener&#34; class=&#34;btn btn-primary&#34;&gt;Auf GitHub markieren&lt;/a&gt;&#xA; &lt;/div&gt;&#xA; &lt;div class=&#34;involve-card&#34;&gt;&#xA; &lt;div class=&#34;involve-card-icon&#34;&gt;🐛&lt;/div&gt;&#xA; &lt;h3&gt;Fehler melden&lt;/h3&gt;&#xA; &lt;p&gt;Etwas funktioniert nicht? Öffnen Sie ein Issue auf GitHub. Kein Template nötig, beschreiben Sie einfach, was Sie gesehen haben und wie man es reproduzieren kann.&lt;/p&gt;&#xA; &lt;a href=&#34;https://github.com/eduardogsilva/wireguard_webadmin/issues&#34; target=&#34;_blank&#34; rel=&#34;noopener&#34; class=&#34;btn btn-outline&#34;&gt;Issue öffnen&lt;/a&gt;&#xA; &lt;/div&gt;&#xA; &lt;div class=&#34;involve-card&#34;&gt;&#xA; &lt;div class=&#34;involve-card-icon&#34;&gt;🔧&lt;/div&gt;&#xA; &lt;h3&gt;Code beitragen&lt;/h3&gt;&#xA; &lt;p&gt;Pull Requests sind willkommen. Bei allem, was nicht ganz trivial ist, öffnen Sie bitte zuerst ein Issue, damit wir uns abstimmen können, bevor Sie Zeit in Code investieren. Gute Einstiege sind mit &lt;code&gt;good first issue&lt;/code&gt; markierte Tickets, Bugfixes mit klarer Reproduktion und zusätzliche Tests.&lt;/p&gt;</description>
</item>
<item>
<title>WireGuard-Cluster</title>
<link>https://wireguard-webadmin.com/de/wireguard-cluster/</link>
<pubDate>Mon, 01 Jan 0001 00:00:00 +0000</pubDate>
<guid>https://wireguard-webadmin.com/de/wireguard-cluster/</guid>
<description>&lt;h2 id=&#34;so-funktioniert-es&#34;&gt;So funktioniert es&lt;/h2&gt;&#xA;&lt;p&gt;Auf dem &lt;strong&gt;primären Server&lt;/strong&gt; verwalten Sie alles: Instanzen, Peers, Firewall, DNS und App-Gateway-Anwendungen.&#xA;&lt;strong&gt;Worker-Knoten&lt;/strong&gt; betreiben einen schlanken Agenten, der sich mit dem primären Server verbindet, die Konfiguration empfängt und lokal anwendet.&#xA;Worker haben weder ein eigenes Panel noch eine eigene Datenbank: Ein neuer Knoten ist in wenigen Minuten bereit.&lt;/p&gt;&#xA;&lt;div class=&#34;flow-cards&#34;&gt;&#xA; &lt;div class=&#34;flow-card&#34;&gt;&#xA; &lt;div class=&#34;flow-card-header&#34;&gt;&lt;span class=&#34;flow-card-num&#34;&gt;1&lt;/span&gt; &lt;strong&gt;Worker verbindet sich&lt;/strong&gt;&lt;/div&gt;&#xA; &lt;p&gt;Der Agent authentifiziert sich mit seinem Token und ruft den primären Server über HTTPS auf. Worker bauen nur ausgehende Verbindungen auf.&lt;/p&gt;</description>
</item>
<item>
<title>Zero-Trust-Anwendungsgateway</title>
<link>https://wireguard-webadmin.com/de/zero-trust/</link>
+6 -33
View File
@@ -28,33 +28,6 @@
hreflang="de"
href="https://wireguard-webadmin.com/de/"
/>
</url><url>
<loc>https://wireguard-webadmin.com/de/categories/</loc>
<xhtml:link
rel="alternate"
hreflang="en-us"
href="https://wireguard-webadmin.com/categories/"
/>
<xhtml:link
rel="alternate"
hreflang="pt-BR"
href="https://wireguard-webadmin.com/pt-br/categories/"
/>
<xhtml:link
rel="alternate"
hreflang="es"
href="https://wireguard-webadmin.com/es/categories/"
/>
<xhtml:link
rel="alternate"
hreflang="fr"
href="https://wireguard-webadmin.com/fr/categories/"
/>
<xhtml:link
rel="alternate"
hreflang="de"
href="https://wireguard-webadmin.com/de/categories/"
/>
</url><url>
<loc>https://wireguard-webadmin.com/de/deployment/</loc>
<xhtml:link
@@ -110,31 +83,31 @@
href="https://wireguard-webadmin.com/de/get-involved/"
/>
</url><url>
<loc>https://wireguard-webadmin.com/de/tags/</loc>
<loc>https://wireguard-webadmin.com/de/wireguard-cluster/</loc>
<xhtml:link
rel="alternate"
hreflang="en-us"
href="https://wireguard-webadmin.com/tags/"
href="https://wireguard-webadmin.com/wireguard-cluster/"
/>
<xhtml:link
rel="alternate"
hreflang="pt-BR"
href="https://wireguard-webadmin.com/pt-br/tags/"
href="https://wireguard-webadmin.com/pt-br/wireguard-cluster/"
/>
<xhtml:link
rel="alternate"
hreflang="es"
href="https://wireguard-webadmin.com/es/tags/"
href="https://wireguard-webadmin.com/es/wireguard-cluster/"
/>
<xhtml:link
rel="alternate"
hreflang="fr"
href="https://wireguard-webadmin.com/fr/tags/"
href="https://wireguard-webadmin.com/fr/wireguard-cluster/"
/>
<xhtml:link
rel="alternate"
hreflang="de"
href="https://wireguard-webadmin.com/de/tags/"
href="https://wireguard-webadmin.com/de/wireguard-cluster/"
/>
</url><url>
<loc>https://wireguard-webadmin.com/de/zero-trust/</loc>
-339
View File
@@ -1,339 +0,0 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tags · wireguard_webadmin</title>
<meta name="description" content="Self-hosted VPN management and Zero Trust access control.">
<link rel="alternate" hreflang="en-us" href="https://wireguard-webadmin.com/tags/">
<link rel="alternate" hreflang="pt-BR" href="https://wireguard-webadmin.com/pt-br/tags/">
<link rel="alternate" hreflang="es" href="https://wireguard-webadmin.com/es/tags/">
<link rel="alternate" hreflang="fr" href="https://wireguard-webadmin.com/fr/tags/">
<link rel="alternate" hreflang="de" href="https://wireguard-webadmin.com/de/tags/">
<link rel="alternate" hreflang="x-default" href="https://wireguard-webadmin.com/">
<meta property="og:type" content="website">
<meta property="og:url" content="https://wireguard-webadmin.com/de/tags/">
<meta property="og:title" content="Tags · wireguard_webadmin">
<meta property="og:description" content="Self-hosted VPN management and Zero Trust access control.">
<meta property="og:image" content="https://wireguard-webadmin.com/og-image.png">
<meta property="og:image:width" content="1280">
<meta property="og:image:height" content="800">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Tags · wireguard_webadmin">
<meta name="twitter:description" content="Self-hosted VPN management and Zero Trust access control.">
<meta name="twitter:image" content="https://wireguard-webadmin.com/og-image.png">
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/css/main.min.css">
</head>
<body>
<header class="site-header">
<div class="container">
<nav class="nav-inner">
<a href="/de/" class="nav-logo">wireguard_<span>webadmin</span></a>
<button class="hamburger" aria-label="Toggle menu" aria-expanded="false">
<span></span><span></span><span></span>
</button>
<ul class="nav-links">
<li>
<a href="/de/"
>
Start
</a>
</li>
<li>
<a href="/de/zero-trust/"
>
Zero Trust
</a>
</li>
<li>
<a href="/de/deployment/"
>
Installation
</a>
</li>
<li>
<a href="/de/get-involved/"
>
Mitmachen
</a>
</li>
<li>
<a href="https://github.com/eduardogsilva/wireguard_webadmin"
target="_blank" rel="noopener"
class="nav-github">
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0C5.374 0 0 5.373 0 12c0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23A11.509 11.509 0 0 1 12 5.803c1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576C20.566 21.797 24 17.3 24 12c0-6.627-5.373-12-12-12z"/></svg>
GitHub
</a>
</li>
<li class="nav-lang-sep"></li>
<li class="lang-dropdown">
<button class="lang-btn" aria-expanded="false">
🇩🇪 DE
<svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor"><path d="M2 3.5L5 6.5L8 3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/></svg>
</button>
<ul class="lang-menu">
<li>
<a href="/tags/"
hreflang="en"
class="">
<span class="lang-flag">🇬🇧</span>
<span>English</span>
</a>
</li>
<li>
<a href="/pt-br/tags/"
hreflang="pt-br"
class="">
<span class="lang-flag">🇧🇷</span>
<span>Português</span>
</a>
</li>
<li>
<a href="/es/tags/"
hreflang="es"
class="">
<span class="lang-flag">🇪🇸</span>
<span>Español</span>
</a>
</li>
<li>
<a href="/fr/tags/"
hreflang="fr"
class="">
<span class="lang-flag">🇫🇷</span>
<span>Français</span>
</a>
</li>
<li>
<a href="/de/tags/"
hreflang="de"
class="lang-active">
<span class="lang-flag">🇩🇪</span>
<span>Deutsch</span>
</a>
</li>
</ul>
</li>
</ul>
</nav>
</div>
</header>
<main>
<div class="container" style="padding: 4rem 0">
<h1>Tags</h1>
</div>
</main>
<footer class="site-footer">
<div class="container">
<div class="footer-inner">
<div class="footer-logo">wireguard_<span>webadmin</span></div>
<ul class="footer-links">
<li><a href="https://github.com/eduardogsilva/wireguard_webadmin" target="_blank" rel="noopener">GitHub</a></li>
<li><a href="https://github.com/eduardogsilva/wireguard_webadmin/discussions" target="_blank" rel="noopener">Discussions</a></li>
<li><a href="/de/zero-trust/">Zero Trust</a></li>
<li><a href="/de/deployment/">Deployment</a></li>
<li><a href="/de/get-involved/">Get Involved</a></li>
</ul>
<div class="footer-built">
entwickelt von <a href="https://github.com/eduardogsilva" target="_blank" rel="noopener">@eduardogsilva</a>
</div>
</div>
</div>
</footer>
<script>
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', () => {
const group = btn.closest('.tab-group');
group.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
group.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
btn.classList.add('active');
group.querySelector('#' + btn.dataset.tab).classList.add('active');
});
});
const hamburger = document.querySelector('.hamburger');
const navLinks = document.querySelector('.nav-links');
if (hamburger) {
hamburger.addEventListener('click', (e) => {
e.stopPropagation();
const open = navLinks.classList.toggle('open');
hamburger.classList.toggle('open', open);
hamburger.setAttribute('aria-expanded', open);
});
document.addEventListener('click', (e) => {
if (!navLinks.contains(e.target) && !hamburger.contains(e.target)) {
navLinks.classList.remove('open');
hamburger.classList.remove('open');
hamburger.setAttribute('aria-expanded', false);
}
});
}
const langBtn = document.querySelector('.lang-btn');
const langDropdown = document.querySelector('.lang-dropdown');
if (langBtn) {
langBtn.addEventListener('click', (e) => {
e.stopPropagation();
const open = langDropdown.classList.toggle('open');
langBtn.setAttribute('aria-expanded', open);
});
document.addEventListener('click', (e) => {
if (!langDropdown.contains(e.target)) {
langDropdown.classList.remove('open');
langBtn.setAttribute('aria-expanded', false);
}
});
langDropdown.querySelectorAll('.lang-menu a').forEach(a => {
a.addEventListener('click', () => localStorage.setItem('lang-manual', '1'));
});
}
if (location.pathname === '/' && !localStorage.getItem('lang-manual')) {
const lang = (navigator.language || navigator.userLanguage || 'en').toLowerCase();
const map = [
{ prefix: 'pt', url: '/pt-br/' },
{ prefix: 'es', url: '/es/' },
{ prefix: 'fr', url: '/fr/' },
{ prefix: 'de', url: '/de/' },
];
const match = map.find(m => lang.startsWith(m.prefix));
if (match) location.replace(match.url);
}
</script>
</body>
</html>
-11
View File
@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Tags on wireguard_webadmin</title>
<link>https://wireguard-webadmin.com/de/tags/</link>
<description>Recent content in Tags on wireguard_webadmin</description>
<generator>Hugo</generator>
<language>de</language>
<atom:link href="https://wireguard-webadmin.com/de/tags/index.xml" rel="self" type="application/rss+xml" />
</channel>
</rss>

Some files were not shown because too many files have changed in this diff Show More