diff --git a/app_gateway/caddy_config_export.py b/app_gateway/caddy_config_export.py index f4c9017..8136f65 100644 --- a/app_gateway/caddy_config_export.py +++ b/app_gateway/caddy_config_export.py @@ -2,7 +2,7 @@ import json import os from app_gateway.models import ( - AccessPolicy, Application, ApplicationPolicy, RESERVED_APP_NAME + AccessPolicy, Application, ApplicationHost, ApplicationPolicy, RESERVED_APP_NAME ) from gatekeeper.models import ( AuthMethod, GatekeeperGroup, GatekeeperIPAddress, GatekeeperUser @@ -130,6 +130,26 @@ def build_routes_data(): return {'entries': entries} +def build_tls_data(): + hosts = {} + dns_credentials = {} + for application_host in ApplicationHost.objects.select_related('dns_credential'): + host_entry = {'certificate_type': application_host.certificate_type} + dns_credential = application_host.dns_credential + if application_host.certificate_type == 'dns_challenge' and dns_credential: + host_entry['dns_credential'] = dns_credential.name + dns_credentials[dns_credential.name] = { + 'provider': dns_credential.provider, + 'credentials': dns_credential.credentials, + } + hosts[application_host.hostname.lower()] = host_entry + + return { + 'hosts': hosts, + 'dns_credentials': dns_credentials, + } + + def export_caddy_config(output_dir): os.makedirs(output_dir, exist_ok=True) @@ -137,6 +157,7 @@ def export_caddy_config(output_dir): '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(): diff --git a/app_gateway/dns_providers.py b/app_gateway/dns_providers.py new file mode 100644 index 0000000..7dac29a --- /dev/null +++ b/app_gateway/dns_providers.py @@ -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()] diff --git a/app_gateway/forms.py b/app_gateway/forms.py index db0cce4..50b8de8 100644 --- a/app_gateway/forms.py +++ b/app_gateway/forms.py @@ -1,3 +1,4 @@ +import re from urllib.parse import urlparse from crispy_forms.helper import FormHelper @@ -6,9 +7,11 @@ 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 ) +from app_gateway.setup_defaults import is_ip_address class ApplicationForm(forms.ModelForm): @@ -74,26 +77,45 @@ class ApplicationForm(forms.ModelForm): class ApplicationHostForm(forms.ModelForm): class Meta: model = ApplicationHost - fields = ['hostname'] + fields = ['hostname', 'certificate_type', 'dns_credential'] labels = { 'hostname': _('Hostname'), + 'certificate_type': _('Certificate'), + 'dns_credential': _('DNS Credential'), } 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.')) + + 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 challenge.')) + else: + cleaned_data['dns_credential'] = None + return cleaned_data def __init__(self, *args, **kwargs): cancel_url = kwargs.pop('cancel_url', '#') + self.is_reserved = kwargs.pop('is_reserved', False) super().__init__(*args, **kwargs) + self.fields['dns_credential'].required = False + if self.is_reserved: + self.fields['hostname'].disabled = True self.helper = FormHelper() self.helper.layout = Layout( @@ -101,6 +123,11 @@ class ApplicationHostForm(forms.ModelForm): Div('hostname', css_class='col-md-12'), css_class='row' ), + Div( + Div('certificate_type', css_class='col-xl-6'), + Div('dns_credential', css_class='col-xl-6'), + css_class='row' + ), Div( Div( Submit('submit', _('Save'), css_class='btn btn-primary'), @@ -316,3 +343,91 @@ 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'] + labels = { + 'display_name': _('Name'), + 'provider': _('Provider'), + } + + 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( + Submit('submit', _('Save'), css_class='btn btn-primary'), + HTML(f'{_("Cancel")}'), + css_class='col-md-12' + ), + css_class='row' + ) + ) + + @staticmethod + def credential_field_name(provider, field_name): + return f'{provider}_{field_name}' + + 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 diff --git a/app_gateway/migrations/0009_dns_challenge_credentials.py b/app_gateway/migrations/0009_dns_challenge_credentials.py new file mode 100644 index 0000000..9b9f12f --- /dev/null +++ b/app_gateway/migrations/0009_dns_challenge_credentials.py @@ -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'), + ), + ] diff --git a/app_gateway/migrations/0010_set_self_signed_for_ip_hosts.py b/app_gateway/migrations/0010_set_self_signed_for_ip_hosts.py new file mode 100644 index 0000000..0e20c93 --- /dev/null +++ b/app_gateway/migrations/0010_set_self_signed_for_ip_hosts.py @@ -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), + ] diff --git a/app_gateway/models.py b/app_gateway/models.py index 5184c88..41a8310 100644 --- a/app_gateway/models.py +++ b/app_gateway/models.py @@ -3,10 +3,41 @@ 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 gatekeeper.models import GatekeeperGroup, AuthMethod, _unique_slug RESERVED_APP_NAME = 'wireguard_webadmin' +CERTIFICATE_TYPE_CHOICES = ( + ('self_signed', _('Self-signed')), + ('http_challenge', _('HTTP challenge')), + ('dns_challenge', _('DNS challenge')), +) + + +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) + + created = models.DateTimeField(auto_now_add=True) + updated = models.DateTimeField(auto_now=True) + uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) + + 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) @@ -35,6 +66,10 @@ 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' + ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) diff --git a/app_gateway/setup_defaults.py b/app_gateway/setup_defaults.py index 461c34f..cfe2613 100644 --- a/app_gateway/setup_defaults.py +++ b/app_gateway/setup_defaults.py @@ -1,7 +1,57 @@ +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 @@ -26,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) diff --git a/app_gateway/urls.py b/app_gateway/urls.py index d0d4e6a..44973a5 100644 --- a/app_gateway/urls.py +++ b/app_gateway/urls.py @@ -28,6 +28,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'), ] diff --git a/app_gateway/views.py b/app_gateway/views.py index 7c2fff4..fe8a777 100644 --- a/app_gateway/views.py +++ b/app_gateway/views.py @@ -1,4 +1,3 @@ -import ipaddress import os from django.conf import settings @@ -13,10 +12,11 @@ from django.views.decorators.http import require_POST from app_gateway.caddy_config_export import export_caddy_config 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 user_manager.models import UserAcl @@ -32,6 +32,7 @@ def view_app_gateway_list(request): hosts = ApplicationHost.objects.all().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,6 +41,7 @@ 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, } @@ -58,20 +60,12 @@ def view_application_details(request): 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, 'page_title': _('Application Details'), } return render(request, 'app_gateway/application_details.html', context) @@ -170,11 +164,14 @@ 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 + ) if form.is_valid(): host = form.save(commit=False) host.application = application @@ -182,10 +179,29 @@ def view_manage_application_host(request): messages.success(request, _('Application Host saved successfully.')) return redirect(cancel_url) + form_description_content = _(''' +
Defines how the TLS certificate for this hostname is issued.
+If an ACME certificate cannot be issued, a self-signed certificate is used until the next successful attempt.
+ ''') + if is_reserved: + form_description_content += _(''' +| {% trans 'Name' %} | +{% trans 'Provider' %} | +{% trans 'Hosts' %} | +{% trans 'Actions' %} | +
|---|---|---|---|
| {{ dns_credential.display_name|default:dns_credential.name }} | +{{ dns_credential.get_provider_display }} | +{{ dns_credential.hosts.count }} | ++ + + + + + + | +