Add DNS challenge delegation to a support domain

This commit is contained in:
Eduardo Silva
2026-11-22 11:47:11 -03:00
parent ee711954e8
commit 0cd9e8901e
13 changed files with 520 additions and 30 deletions
+3
View File
@@ -204,6 +204,9 @@ def build_tls_data(worker=None):
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,
+36 -2
View File
@@ -9,11 +9,14 @@ 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, DnsChallengeCredential
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:
@@ -150,6 +153,10 @@ class ApplicationHostForm(forms.ModelForm):
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.'))
@@ -178,6 +185,7 @@ class ApplicationHostForm(forms.ModelForm):
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(
@@ -404,10 +412,17 @@ class ApplicationRouteForm(forms.ModelForm):
class DnsChallengeCredentialForm(forms.ModelForm):
class Meta:
model = DnsChallengeCredential
fields = ['display_name', 'provider']
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):
@@ -447,6 +462,10 @@ class DnsChallengeCredentialForm(forms.ModelForm):
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'),
@@ -461,6 +480,21 @@ class DnsChallengeCredentialForm(forms.ModelForm):
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')
@@ -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),
),
]
+43
View File
@@ -15,17 +15,39 @@ CERTIFICATE_TYPE_CHOICES = (
('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)
@@ -97,6 +119,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']
+172 -2
View File
@@ -1,4 +1,5 @@
import contextlib
import hashlib
import importlib.util
import io
import json
@@ -9,10 +10,11 @@ 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 export_caddy_config
from app_gateway.forms import ApplicationForm, ApplicationHostForm
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
)
@@ -435,3 +437,171 @@ class GatewayAutoApplyTests(TestCase):
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])
+20 -5
View File
@@ -40,7 +40,7 @@ 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')
@@ -68,7 +68,7 @@ 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
@@ -295,7 +295,7 @@ def view_manage_application_host(request):
<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.</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>
@@ -310,13 +310,22 @@ def view_manage_application_host(request):
</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
@@ -635,8 +644,14 @@ def view_manage_dns_credential(request):
form = DnsChallengeCredentialForm(request.POST or None, instance=dns_credential, cancel_url=cancel_url)
if form.is_valid():
form.save()
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)