mirror of
https://github.com/eduardogsilva/wireguard_webadmin.git
synced 2026-11-21 04:23:15 +01:00
Add per-host certificate type and DNS challenge support to App Gateway
Each application host now selects how its TLS certificate is issued: self-signed, ACME HTTP challenge, or ACME DNS challenge using a stored DNS credential. ACME modes fall back to the internal CA when issuance fails, so hosts stay reachable with a browser warning instead of a TLS error. - Add DnsChallengeCredential model and provider registry (Cloudflare) - Add certificate_type and dns_credential to ApplicationHost - Sync WireGuard WebAdmin hosts from .env into the reserved application - Export per-host TLS settings to tls.json, read only by Caddy - Group hosts by certificate settings into separate Caddy site blocks - Build Caddy with the Cloudflare DNS module using xcaddy - Regenerate the Caddyfile without DNS challenge if validation fails
This commit is contained in:
@@ -2,7 +2,7 @@ import json
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
from app_gateway.models import (
|
from app_gateway.models import (
|
||||||
AccessPolicy, Application, ApplicationPolicy, RESERVED_APP_NAME
|
AccessPolicy, Application, ApplicationHost, ApplicationPolicy, RESERVED_APP_NAME
|
||||||
)
|
)
|
||||||
from gatekeeper.models import (
|
from gatekeeper.models import (
|
||||||
AuthMethod, GatekeeperGroup, GatekeeperIPAddress, GatekeeperUser
|
AuthMethod, GatekeeperGroup, GatekeeperIPAddress, GatekeeperUser
|
||||||
@@ -130,6 +130,26 @@ def build_routes_data():
|
|||||||
return {'entries': entries}
|
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):
|
def export_caddy_config(output_dir):
|
||||||
os.makedirs(output_dir, exist_ok=True)
|
os.makedirs(output_dir, exist_ok=True)
|
||||||
|
|
||||||
@@ -137,6 +157,7 @@ def export_caddy_config(output_dir):
|
|||||||
'applications.json': build_applications_data,
|
'applications.json': build_applications_data,
|
||||||
'auth_policies.json': build_auth_policies_data,
|
'auth_policies.json': build_auth_policies_data,
|
||||||
'routes.json': build_routes_data,
|
'routes.json': build_routes_data,
|
||||||
|
'tls.json': build_tls_data,
|
||||||
}
|
}
|
||||||
|
|
||||||
for filename, builder in file_map.items():
|
for filename, builder in file_map.items():
|
||||||
|
|||||||
@@ -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()]
|
||||||
+118
-3
@@ -1,3 +1,4 @@
|
|||||||
|
import re
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
from crispy_forms.helper import FormHelper
|
from crispy_forms.helper import FormHelper
|
||||||
@@ -6,9 +7,11 @@ from django import forms
|
|||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
|
from app_gateway.dns_providers import DNS_PROVIDERS
|
||||||
from app_gateway.models import (
|
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):
|
class ApplicationForm(forms.ModelForm):
|
||||||
@@ -74,26 +77,45 @@ class ApplicationForm(forms.ModelForm):
|
|||||||
class ApplicationHostForm(forms.ModelForm):
|
class ApplicationHostForm(forms.ModelForm):
|
||||||
class Meta:
|
class Meta:
|
||||||
model = ApplicationHost
|
model = ApplicationHost
|
||||||
fields = ['hostname']
|
fields = ['hostname', 'certificate_type', 'dns_credential']
|
||||||
labels = {
|
labels = {
|
||||||
'hostname': _('Hostname'),
|
'hostname': _('Hostname'),
|
||||||
|
'certificate_type': _('Certificate'),
|
||||||
|
'dns_credential': _('DNS Credential'),
|
||||||
}
|
}
|
||||||
|
|
||||||
def clean(self):
|
def clean(self):
|
||||||
cleaned_data = super().clean()
|
cleaned_data = super().clean()
|
||||||
hostname = (cleaned_data.get('hostname') or '').strip()
|
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', ' ')):
|
if any(c in hostname for c in ('{', '}', '\n', '\r', '\x00', ' ')):
|
||||||
self.add_error('hostname', _('Hostname contains invalid characters.'))
|
self.add_error('hostname', _('Hostname contains invalid characters.'))
|
||||||
|
|
||||||
webadmin_hostnames = [host.lower() for host in settings.ALLOWED_HOSTS]
|
webadmin_hostnames = [host.lower() for host in settings.ALLOWED_HOSTS]
|
||||||
if hostname.lower() in webadmin_hostnames:
|
if hostname.lower() in webadmin_hostnames:
|
||||||
self.add_error('hostname', _('This hostname is already used by WireGuard WebAdmin.'))
|
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
|
return cleaned_data
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
cancel_url = kwargs.pop('cancel_url', '#')
|
cancel_url = kwargs.pop('cancel_url', '#')
|
||||||
|
self.is_reserved = kwargs.pop('is_reserved', False)
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
|
self.fields['dns_credential'].required = False
|
||||||
|
if self.is_reserved:
|
||||||
|
self.fields['hostname'].disabled = True
|
||||||
|
|
||||||
self.helper = FormHelper()
|
self.helper = FormHelper()
|
||||||
self.helper.layout = Layout(
|
self.helper.layout = Layout(
|
||||||
@@ -101,6 +123,11 @@ class ApplicationHostForm(forms.ModelForm):
|
|||||||
Div('hostname', css_class='col-md-12'),
|
Div('hostname', css_class='col-md-12'),
|
||||||
css_class='row'
|
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(
|
||||||
Div(
|
Div(
|
||||||
Submit('submit', _('Save'), css_class='btn btn-primary'),
|
Submit('submit', _('Save'), css_class='btn btn-primary'),
|
||||||
@@ -316,3 +343,91 @@ class ApplicationRouteForm(forms.ModelForm):
|
|||||||
else:
|
else:
|
||||||
cleaned_data['path_prefix'] = path_prefix
|
cleaned_data['path_prefix'] = path_prefix
|
||||||
return cleaned_data
|
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'<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(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
|
||||||
|
|||||||
@@ -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),
|
||||||
|
]
|
||||||
@@ -3,10 +3,41 @@ import uuid
|
|||||||
from django.db import models
|
from django.db import models
|
||||||
from django.utils.translation import gettext_lazy as _
|
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
|
from gatekeeper.models import GatekeeperGroup, AuthMethod, _unique_slug
|
||||||
|
|
||||||
RESERVED_APP_NAME = 'wireguard_webadmin'
|
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):
|
class Application(models.Model):
|
||||||
name = models.SlugField(max_length=64, unique=True)
|
name = models.SlugField(max_length=64, unique=True)
|
||||||
@@ -35,6 +66,10 @@ class Application(models.Model):
|
|||||||
class ApplicationHost(models.Model):
|
class ApplicationHost(models.Model):
|
||||||
application = models.ForeignKey(Application, on_delete=models.CASCADE, related_name='hosts')
|
application = models.ForeignKey(Application, on_delete=models.CASCADE, related_name='hosts')
|
||||||
hostname = models.CharField(max_length=255, unique=True)
|
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)
|
created = models.DateTimeField(auto_now_add=True)
|
||||||
updated = models.DateTimeField(auto_now=True)
|
updated = models.DateTimeField(auto_now=True)
|
||||||
|
|||||||
@@ -1,7 +1,57 @@
|
|||||||
|
import ipaddress
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
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):
|
def create_default_entries(**kwargs):
|
||||||
from app_gateway.models import AccessPolicy, Application, ApplicationPolicy, RESERVED_APP_NAME
|
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():
|
if not ApplicationPolicy.objects.filter(application=app).exists():
|
||||||
ApplicationPolicy.objects.create(application=app, default_policy=public_policy)
|
ApplicationPolicy.objects.create(application=app, default_policy=public_policy)
|
||||||
logger.info("Assigned default policy 'Public' to application '%s'", RESERVED_APP_NAME)
|
logger.info("Assigned default policy 'Public' to application '%s'", RESERVED_APP_NAME)
|
||||||
|
|
||||||
|
sync_webadmin_hosts(app)
|
||||||
|
|||||||
@@ -28,6 +28,10 @@ urlpatterns = [
|
|||||||
path('route/manage/', views.view_manage_application_route, name='manage_application_route'),
|
path('route/manage/', views.view_manage_application_route, name='manage_application_route'),
|
||||||
path('route/delete/', views.view_delete_application_route, name='delete_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
|
# Config Export
|
||||||
path('export/caddy/', views.view_export_caddy_config, name='export_caddy_config'),
|
path('export/caddy/', views.view_export_caddy_config, name='export_caddy_config'),
|
||||||
]
|
]
|
||||||
|
|||||||
+85
-13
@@ -1,4 +1,3 @@
|
|||||||
import ipaddress
|
|
||||||
import os
|
import os
|
||||||
|
|
||||||
from django.conf import settings
|
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.caddy_config_export import export_caddy_config
|
||||||
from app_gateway.forms import (
|
from app_gateway.forms import (
|
||||||
ApplicationForm, ApplicationHostForm, AccessPolicyForm,
|
ApplicationForm, ApplicationHostForm, AccessPolicyForm,
|
||||||
ApplicationPolicyForm, ApplicationRouteForm
|
ApplicationPolicyForm, ApplicationRouteForm, DnsChallengeCredentialForm
|
||||||
)
|
)
|
||||||
from app_gateway.models import (
|
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 app_gateway.setup_defaults import create_default_entries
|
||||||
from user_manager.models import UserAcl
|
from user_manager.models import UserAcl
|
||||||
@@ -32,6 +32,7 @@ def view_app_gateway_list(request):
|
|||||||
hosts = ApplicationHost.objects.all().order_by('hostname')
|
hosts = ApplicationHost.objects.all().order_by('hostname')
|
||||||
access_policies = AccessPolicy.objects.all().order_by('name')
|
access_policies = AccessPolicy.objects.all().order_by('name')
|
||||||
app_policies = ApplicationPolicy.objects.all().order_by('application__name')
|
app_policies = ApplicationPolicy.objects.all().order_by('application__name')
|
||||||
|
dns_credentials = DnsChallengeCredential.objects.all().order_by('name')
|
||||||
|
|
||||||
tab = request.GET.get('tab', 'applications')
|
tab = request.GET.get('tab', 'applications')
|
||||||
|
|
||||||
@@ -40,6 +41,7 @@ def view_app_gateway_list(request):
|
|||||||
'hosts': hosts,
|
'hosts': hosts,
|
||||||
'access_policies': access_policies,
|
'access_policies': access_policies,
|
||||||
'app_policies': app_policies,
|
'app_policies': app_policies,
|
||||||
|
'dns_credentials': dns_credentials,
|
||||||
'active_tab': tab,
|
'active_tab': tab,
|
||||||
'caddy_enabled': settings.CADDY_ENABLED,
|
'caddy_enabled': settings.CADDY_ENABLED,
|
||||||
}
|
}
|
||||||
@@ -58,20 +60,12 @@ def view_application_details(request):
|
|||||||
routes = application.routes.all().order_by('order', 'path_prefix')
|
routes = application.routes.all().order_by('order', 'path_prefix')
|
||||||
|
|
||||||
is_reserved = application.name == RESERVED_APP_NAME
|
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 = {
|
context = {
|
||||||
'application': application,
|
'application': application,
|
||||||
'hosts': hosts,
|
'hosts': hosts,
|
||||||
'routes': routes,
|
'routes': routes,
|
||||||
'is_reserved': is_reserved,
|
'is_reserved': is_reserved,
|
||||||
'django_hostnames': django_hostnames,
|
|
||||||
'page_title': _('Application Details'),
|
'page_title': _('Application Details'),
|
||||||
}
|
}
|
||||||
return render(request, 'app_gateway/application_details.html', context)
|
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'
|
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.'))
|
messages.error(request, _('The WireGuard WebAdmin application cannot be modified.'))
|
||||||
return redirect(cancel_url)
|
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():
|
if form.is_valid():
|
||||||
host = form.save(commit=False)
|
host = form.save(commit=False)
|
||||||
host.application = application
|
host.application = application
|
||||||
@@ -182,10 +179,29 @@ def view_manage_application_host(request):
|
|||||||
messages.success(request, _('Application Host saved successfully.'))
|
messages.success(request, _('Application Host saved successfully.'))
|
||||||
return redirect(cancel_url)
|
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>Self-signed</strong>: A certificate issued by the internal Caddy CA. Browsers will show a security warning.</li>
|
||||||
|
<li><strong>HTTP challenge</strong>: A trusted ACME certificate validated through HTTP. The hostname must point to this server and ports 80/443 must be reachable from the internet.</li>
|
||||||
|
<li><strong>DNS challenge</strong>: A trusted ACME certificate validated through a DNS record created using the selected DNS credential. The server does not need to be reachable from the internet.</li>
|
||||||
|
</ul>
|
||||||
|
<p>If an ACME certificate cannot be issued, a self-signed certificate is used until the next successful attempt.</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>
|
||||||
|
''')
|
||||||
|
|
||||||
context = {
|
context = {
|
||||||
'form': form,
|
'form': form,
|
||||||
'title': title,
|
'title': title,
|
||||||
'page_title': title,
|
'page_title': title,
|
||||||
|
'form_description': {'size': 'col-lg-6', 'content': form_description_content},
|
||||||
}
|
}
|
||||||
return render(request, 'generic_form.html', context)
|
return render(request, 'generic_form.html', context)
|
||||||
|
|
||||||
@@ -455,6 +471,62 @@ def view_delete_application_route(request):
|
|||||||
return render(request, 'generic_delete_confirmation.html', context)
|
return render(request, 'generic_delete_confirmation.html', context)
|
||||||
|
|
||||||
|
|
||||||
|
@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():
|
||||||
|
form.save()
|
||||||
|
messages.success(request, _('DNS Credential saved successfully.'))
|
||||||
|
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.'))
|
||||||
|
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
|
@login_required
|
||||||
@require_POST
|
@require_POST
|
||||||
def view_export_caddy_config(request):
|
def view_export_caddy_config(request):
|
||||||
|
|||||||
@@ -1,5 +1,16 @@
|
|||||||
|
# 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
|
FROM caddy:2
|
||||||
|
|
||||||
|
COPY --from=builder /usr/bin/caddy /usr/bin/caddy
|
||||||
|
|
||||||
RUN apk add --no-cache \
|
RUN apk add --no-cache \
|
||||||
python3 \
|
python3 \
|
||||||
inotify-tools \
|
inotify-tools \
|
||||||
|
|||||||
@@ -10,8 +10,17 @@ CADDYFILE_PATH="${CADDYFILE_PATH:-/etc/caddy/Caddyfile}"
|
|||||||
echo "==> Generating wireguard_webadmin.json..."
|
echo "==> Generating wireguard_webadmin.json..."
|
||||||
"$PYTHON" "${SCRIPT_DIR}/export_wireguard_webadmin_config.py"
|
"$PYTHON" "${SCRIPT_DIR}/export_wireguard_webadmin_config.py"
|
||||||
|
|
||||||
|
generate_caddyfile() {
|
||||||
|
"$PYTHON" "${SCRIPT_DIR}/process_config.py"
|
||||||
|
# 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"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
echo "==> Processing config files..."
|
echo "==> Processing config files..."
|
||||||
"$PYTHON" "${SCRIPT_DIR}/process_config.py"
|
generate_caddyfile
|
||||||
|
|
||||||
echo "==> Starting Caddy..."
|
echo "==> Starting Caddy..."
|
||||||
caddy run --config "$CADDYFILE_PATH" --adapter caddyfile &
|
caddy run --config "$CADDYFILE_PATH" --adapter caddyfile &
|
||||||
@@ -25,7 +34,7 @@ while true; do
|
|||||||
sleep 1
|
sleep 1
|
||||||
|
|
||||||
echo "==> Config change detected, reprocessing..."
|
echo "==> Config change detected, reprocessing..."
|
||||||
"$PYTHON" "${SCRIPT_DIR}/process_config.py"
|
generate_caddyfile
|
||||||
|
|
||||||
echo "==> Reloading Caddy..."
|
echo "==> Reloading Caddy..."
|
||||||
caddy reload --config "$CADDYFILE_PATH" --adapter caddyfile 2>/dev/null || echo "Warning: Caddy reload failed, will retry on next change."
|
caddy reload --config "$CADDYFILE_PATH" --adapter caddyfile 2>/dev/null || echo "Warning: Caddy reload failed, will retry on next change."
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ Expected input files in /caddy_json_export/:
|
|||||||
- applications.json (optional, exported from Django)
|
- applications.json (optional, exported from Django)
|
||||||
- auth_policies.json (optional, exported from Django)
|
- auth_policies.json (optional, exported from Django)
|
||||||
- routes.json (optional, exported from Django)
|
- routes.json (optional, exported from Django)
|
||||||
|
- tls.json (optional, exported from Django)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
@@ -19,6 +20,11 @@ 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_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_PORTAL_PATH = os.environ.get("AUTH_GATEWAY_EXTERNAL_PATH", "/auth-gateway")
|
||||||
AUTH_GATEWAY_CHECK_URI = "/auth/check"
|
AUTH_GATEWAY_CHECK_URI = "/auth/check"
|
||||||
|
CERTIFICATE_TYPES = ("self_signed", "http_challenge", "dns_challenge")
|
||||||
|
DEFAULT_CERTIFICATE_TYPE = "http_challenge"
|
||||||
|
ACME_DNS_RESOLVERS = "1.1.1.1 1.0.0.1"
|
||||||
|
# Set by entrypoint.sh when the generated Caddyfile fails validation
|
||||||
|
DISABLE_DNS_CHALLENGE = os.environ.get("DISABLE_DNS_CHALLENGE", "") == "1"
|
||||||
AUTH_IDENTITY_HEADERS = (
|
AUTH_IDENTITY_HEADERS = (
|
||||||
"X-Auth-User",
|
"X-Auth-User",
|
||||||
"X-Auth-Email",
|
"X-Auth-Email",
|
||||||
@@ -66,7 +72,41 @@ def _safe_value(val: str) -> str:
|
|||||||
return re.sub(r"[\r\n\x00]", "", val)
|
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_host_tls(host, tls_data):
|
||||||
|
"""Return (certificate_type, dns_credential_name) for a host. Hosts not listed use the HTTP challenge."""
|
||||||
|
host_tls = tls_data.get("hosts", {}).get(host.lower(), {})
|
||||||
|
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
|
||||||
|
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
|
||||||
|
return certificate_type, dns_credential
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
||||||
|
groups.setdefault(get_host_tls(host, tls_data), []).append(host)
|
||||||
|
return groups.items()
|
||||||
|
|
||||||
|
|
||||||
|
def build_caddyfile(apps, auth_policies, routes, tls_data=None):
|
||||||
|
tls_data = tls_data or {}
|
||||||
policies = auth_policies.get("policies", {}) if auth_policies else {}
|
policies = auth_policies.get("policies", {}) if auth_policies else {}
|
||||||
route_entries = routes.get("entries", {}) if routes else {}
|
route_entries = routes.get("entries", {}) if routes else {}
|
||||||
lines = []
|
lines = []
|
||||||
@@ -82,6 +122,30 @@ def build_caddyfile(apps, auth_policies, routes):
|
|||||||
lines.append(" }")
|
lines.append(" }")
|
||||||
lines.append("")
|
lines.append("")
|
||||||
|
|
||||||
|
def emit_tls(certificate_type, dns_credential):
|
||||||
|
if certificate_type == "self_signed":
|
||||||
|
lines.append(" tls internal")
|
||||||
|
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(" }")
|
||||||
|
lines.append(f" resolvers {ACME_DNS_RESOLVERS}")
|
||||||
|
lines.append(" }")
|
||||||
|
else:
|
||||||
|
lines.append(" issuer acme")
|
||||||
|
# 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=" "):
|
def emit_identity_header_sanitization(indent=" "):
|
||||||
for header_name in AUTH_IDENTITY_HEADERS:
|
for header_name in AUTH_IDENTITY_HEADERS:
|
||||||
lines.append(f"{indent}request_header -{header_name}")
|
lines.append(f"{indent}request_header -{header_name}")
|
||||||
@@ -142,21 +206,18 @@ def build_caddyfile(apps, auth_policies, routes):
|
|||||||
lines.append(" }")
|
lines.append(" }")
|
||||||
lines.append("")
|
lines.append("")
|
||||||
|
|
||||||
for app in apps:
|
def emit_site_block(app, hosts, certificate_type, dns_credential):
|
||||||
hosts = app.get("hosts", [])
|
|
||||||
upstream = app.get("upstream", "")
|
upstream = app.get("upstream", "")
|
||||||
# tls_insecure_skip_verify is only valid for https upstreams
|
# tls_insecure_skip_verify is only valid for https upstreams
|
||||||
allow_invalid_cert = app.get("allow_invalid_cert", False) and upstream.startswith("https://")
|
allow_invalid_cert = app.get("allow_invalid_cert", False) and upstream.startswith("https://")
|
||||||
static_routes = app.get("static_routes", [])
|
static_routes = app.get("static_routes", [])
|
||||||
app_id = app.get("id", "")
|
app_id = app.get("id", "")
|
||||||
|
|
||||||
if not hosts or not upstream:
|
|
||||||
continue
|
|
||||||
|
|
||||||
base, upstream_path = split_upstream(upstream)
|
base, upstream_path = split_upstream(upstream)
|
||||||
|
|
||||||
safe_hosts = [_safe_value(h) for h in hosts]
|
safe_hosts = [_safe_value(h) for h in hosts]
|
||||||
lines.append(f"{', '.join(safe_hosts)} {{")
|
lines.append(f"{', '.join(safe_hosts)} {{")
|
||||||
|
emit_tls(certificate_type, dns_credential)
|
||||||
lines.append(" # Security: overwrite client-supplied forwarding headers with verified values")
|
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-For {http.request.remote.host}")
|
||||||
lines.append(" request_header -X-Forwarded-Host")
|
lines.append(" request_header -X-Forwarded-Host")
|
||||||
@@ -182,7 +243,7 @@ def build_caddyfile(apps, auth_policies, routes):
|
|||||||
emit_reverse_proxy(base, upstream_path, indent=" ", allow_invalid_cert=allow_invalid_cert)
|
emit_reverse_proxy(base, upstream_path, indent=" ", allow_invalid_cert=allow_invalid_cert)
|
||||||
lines.append("}")
|
lines.append("}")
|
||||||
lines.append("")
|
lines.append("")
|
||||||
continue
|
return
|
||||||
|
|
||||||
route_list = sorted(app_route_data.get("routes", []), key=lambda route: len(route.get("path_prefix", "")), reverse=True)
|
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):
|
for route_index, route in enumerate(route_list):
|
||||||
@@ -212,6 +273,14 @@ def build_caddyfile(apps, auth_policies, routes):
|
|||||||
lines.append("}")
|
lines.append("}")
|
||||||
lines.append("")
|
lines.append("")
|
||||||
|
|
||||||
|
for app in apps:
|
||||||
|
hosts = app.get("hosts", [])
|
||||||
|
if not hosts or not app.get("upstream", ""):
|
||||||
|
continue
|
||||||
|
|
||||||
|
for (certificate_type, dns_credential), group_hosts in group_hosts_by_tls(hosts, tls_data):
|
||||||
|
emit_site_block(app, group_hosts, certificate_type, dns_credential)
|
||||||
|
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
@@ -219,8 +288,9 @@ def main():
|
|||||||
apps = collect_all_applications()
|
apps = collect_all_applications()
|
||||||
auth_policies = load_json("auth_policies.json")
|
auth_policies = load_json("auth_policies.json")
|
||||||
routes = load_json("routes.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)
|
os.makedirs(os.path.dirname(CADDYFILE_PATH), exist_ok=True)
|
||||||
with open(CADDYFILE_PATH, "w", encoding="utf-8") as caddyfile:
|
with open(CADDYFILE_PATH, "w", encoding="utf-8") as caddyfile:
|
||||||
caddyfile.write(caddyfile_content)
|
caddyfile.write(caddyfile_content)
|
||||||
|
|||||||
@@ -19,6 +19,12 @@
|
|||||||
{% trans 'Access Policies' %}
|
{% trans 'Access Policies' %}
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
|
<li class="nav-item">
|
||||||
|
<a class="nav-link {% if active_tab == 'dns_credentials' %}active{% endif %}"
|
||||||
|
href="{% url 'app_gateway_list' %}?tab=dns_credentials" role="tab">
|
||||||
|
{% trans 'DNS Credentials' %}
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
<div class="tab-content mt-4">
|
<div class="tab-content mt-4">
|
||||||
@@ -108,6 +114,7 @@
|
|||||||
<tr>
|
<tr>
|
||||||
<th>{% trans 'Hostname' %}</th>
|
<th>{% trans 'Hostname' %}</th>
|
||||||
<th>{% trans 'Application' %}</th>
|
<th>{% trans 'Application' %}</th>
|
||||||
|
<th>{% trans 'Certificate' %}</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
@@ -119,6 +126,10 @@
|
|||||||
{{ host.application }}
|
{{ host.application }}
|
||||||
</a>
|
</a>
|
||||||
</td>
|
</td>
|
||||||
|
<td>
|
||||||
|
{{ host.get_certificate_type_display }}
|
||||||
|
{% if host.dns_credential %}<small class="text-muted">({{ host.dns_credential }})</small>{% endif %}
|
||||||
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -178,6 +189,51 @@
|
|||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
|
{% elif active_tab == 'dns_credentials' %}
|
||||||
|
<div class="mb-3">
|
||||||
|
<a href="{% url 'manage_dns_credential' %}" class="btn btn-outline-primary btn-sm">
|
||||||
|
<i class="fas fa-plus"></i> {% trans 'Add DNS Credential' %}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if dns_credentials %}
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-striped table-hover">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>{% trans 'Name' %}</th>
|
||||||
|
<th>{% trans 'Provider' %}</th>
|
||||||
|
<th>{% trans 'Hosts' %}</th>
|
||||||
|
<th>{% trans 'Actions' %}</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for dns_credential in dns_credentials %}
|
||||||
|
<tr>
|
||||||
|
<td>{{ dns_credential.display_name|default:dns_credential.name }}</td>
|
||||||
|
<td>{{ dns_credential.get_provider_display }}</td>
|
||||||
|
<td>{{ dns_credential.hosts.count }}</td>
|
||||||
|
<td style="width: 15%">
|
||||||
|
<a href="{% url 'manage_dns_credential' %}?uuid={{ dns_credential.uuid }}"
|
||||||
|
class="btn btn-sm btn-info" title="{% trans 'Edit' %}">
|
||||||
|
<i class="fas fa-edit"></i>
|
||||||
|
</a>
|
||||||
|
<a href="{% url 'delete_dns_credential' %}?uuid={{ dns_credential.uuid }}"
|
||||||
|
class="btn btn-sm btn-danger" title="{% trans 'Delete' %}">
|
||||||
|
<i class="fas fa-trash"></i>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="alert alert-info">
|
||||||
|
{% trans 'No DNS Credentials found.' %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -67,28 +67,28 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{% if hosts or django_hostnames %}
|
{% if hosts %}
|
||||||
<div class="table-responsive">
|
<div class="table-responsive">
|
||||||
<table class="table table-striped table-hover">
|
<table class="table table-striped table-hover">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>{% trans 'Hostname' %}</th>
|
<th>{% trans 'Hostname' %}</th>
|
||||||
|
<th>{% trans 'Certificate' %}</th>
|
||||||
<th>{% trans 'Actions' %}</th>
|
<th>{% trans 'Actions' %}</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for hostname in django_hostnames %}
|
|
||||||
<tr class="text-muted">
|
|
||||||
<td>{{ hostname }}</td>
|
|
||||||
<td style="width: 15%"></td>
|
|
||||||
</tr>
|
|
||||||
{% endfor %}
|
|
||||||
{% for host in hosts %}
|
{% for host in hosts %}
|
||||||
<tr>
|
<tr>
|
||||||
<td>{{ host.hostname }}</td>
|
<td>{{ host.hostname }}</td>
|
||||||
|
<td>
|
||||||
|
{{ host.get_certificate_type_display }}
|
||||||
|
{% if host.dns_credential %}<small class="text-muted">({{ host.dns_credential }})</small>{% endif %}
|
||||||
|
</td>
|
||||||
<td style="width: 15%">
|
<td style="width: 15%">
|
||||||
{% if is_reserved %}
|
{% if is_reserved %}
|
||||||
<a class="btn btn-sm btn-secondary disabled" aria-disabled="true" tabindex="-1" title="{% trans 'This application cannot be modified' %}">
|
<a href="{% url 'manage_application_host' %}?uuid={{ host.uuid }}"
|
||||||
|
class="btn btn-sm btn-info" title="{% trans 'Edit' %}">
|
||||||
<i class="fas fa-edit"></i>
|
<i class="fas fa-edit"></i>
|
||||||
</a>
|
</a>
|
||||||
<a class="btn btn-sm btn-secondary disabled" aria-disabled="true" tabindex="-1" title="{% trans 'This application cannot be modified' %}">
|
<a class="btn btn-sm btn-secondary disabled" aria-disabled="true" tabindex="-1" title="{% trans 'This application cannot be modified' %}">
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
{% extends 'base.html' %}
|
||||||
|
{% load crispy_forms_tags %}
|
||||||
|
{% load i18n %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class='row'>
|
||||||
|
<div class='col-lg-6'>
|
||||||
|
<div class="card card-primary card-outline">
|
||||||
|
<div class="card-header">
|
||||||
|
<h3 class="card-title">{{ page_title }}</h3>
|
||||||
|
</div>
|
||||||
|
<div class="card-body row">
|
||||||
|
<div class="col-lg-12">
|
||||||
|
{% crispy form %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class='col-lg-6'>
|
||||||
|
<div class="card card-primary card-outline">
|
||||||
|
<div class="card-body row">
|
||||||
|
<div class="col-lg-12">
|
||||||
|
<h5>{% trans 'DNS Credential' %}</h5>
|
||||||
|
<p>{% trans 'Credentials used to create the DNS records required by the ACME DNS challenge.' %}</p>
|
||||||
|
<p>{% blocktrans trimmed %}
|
||||||
|
Use a token restricted to editing DNS records of the zones you need. For Cloudflare, create an
|
||||||
|
API Token with the <strong>Zone / DNS / Edit</strong> permission.
|
||||||
|
{% endblocktrans %}</p>
|
||||||
|
<p>{% trans 'Secret values are never displayed after saving. Leave them blank when editing to keep the current value.' %}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block custom_page_scripts %}
|
||||||
|
<script>
|
||||||
|
$(document).ready(function () {
|
||||||
|
function toggleProviderFields() {
|
||||||
|
var provider = $('#id_provider').val();
|
||||||
|
$('.provider-group').hide();
|
||||||
|
if (provider) {
|
||||||
|
$('.provider-' + provider).show();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$('#id_provider').change(toggleProviderFields);
|
||||||
|
toggleProviderFields();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
{% endblock %}
|
||||||
Reference in New Issue
Block a user