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)
+29 -14
View File
@@ -40,6 +40,7 @@ DISABLE_DNS_CHALLENGE = os.environ.get("DISABLE_DNS_CHALLENGE", "") == "1"
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",
@@ -100,21 +101,23 @@ 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
return "certificate_file", certificate_file, certificate_fallback, None
if certificate_type == "self_signed" or certificate_fallback:
return "self_signed", None, True
return "self_signed", None, True, None
return None
def get_host_tls(host, tls_data):
"""
Return (certificate_type, dns_credential_name, certificate_fallback) for a host.
Hosts not listed use the HTTP challenge with fallback. On cluster nodes the second item is the
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(), {})
@@ -125,14 +128,19 @@ def get_host_tls(host, tls_data):
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
return certificate_type, dns_credential, certificate_fallback, override_domain
def group_hosts_by_tls(hosts, tls_data):
@@ -174,7 +182,7 @@ def build_caddyfile(apps, auth_policies, routes, tls_data=None):
lines.append(" }")
lines.append("")
def emit_tls(certificate_type, dns_credential, certificate_fallback):
def emit_tls(certificate_type, dns_credential, certificate_fallback, override_domain=None):
if certificate_type == "self_signed":
lines.append(" tls internal")
lines.append("")
@@ -195,6 +203,9 @@ def build_caddyfile(apps, auth_policies, routes, tls_data=None):
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(" }")
@@ -268,7 +279,7 @@ def build_caddyfile(apps, auth_policies, routes, tls_data=None):
lines.append(" }")
lines.append("")
def emit_site_block(app, hosts, certificate_type, dns_credential, certificate_fallback):
def emit_site_block(app, hosts, host_tls):
upstream = app.get("upstream", "")
# tls_insecure_skip_verify is only valid for https upstreams
allow_invalid_cert = app.get("allow_invalid_cert", False) and upstream.startswith("https://")
@@ -279,7 +290,7 @@ def build_caddyfile(apps, auth_policies, routes, tls_data=None):
safe_hosts = [_safe_value(h) for h in hosts]
lines.append(f"{', '.join(safe_hosts)} {{")
emit_tls(certificate_type, dns_credential, certificate_fallback)
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")
@@ -340,14 +351,14 @@ def build_caddyfile(apps, auth_policies, routes, tls_data=None):
if not hosts or not app.get("upstream", ""):
continue
for (certificate_type, dns_credential, certificate_fallback), group_hosts in group_hosts_by_tls(hosts, tls_data):
emit_site_block(app, group_hosts, certificate_type, dns_credential, certificate_fallback)
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 (certificate_type, dns_credential, certificate_fallback), group_hosts in group_hosts_by_tls(certificate_only_hosts, 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(certificate_type, dns_credential, certificate_fallback)
emit_tls(*host_tls)
lines.append(" respond 404")
lines.append("}")
lines.append("")
@@ -365,10 +376,14 @@ def build_tls_state(apps, tls_data):
host_tls = get_host_tls(host, tls_data)
if host_tls is None:
continue
certificate_type, certificate_reference, certificate_fallback = host_tls
certificate_type, certificate_reference, certificate_fallback, override_domain = host_tls
credential_hash = ""
if certificate_type == "dns_challenge":
credential_data = json.dumps(tls_data["dns_credentials"][certificate_reference], sort_keys=True)
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()] = [
+19 -2
View File
@@ -128,8 +128,7 @@
</a>
</td>
<td>
{{ host.get_certificate_type_display }}
{% if host.dns_credential %}<small class="text-muted">({{ host.dns_credential }})</small>{% endif %}
{% include 'app_gateway/host_certificate.html' %}
</td>
</tr>
{% endfor %}
@@ -204,6 +203,7 @@
<tr>
<th>{% trans 'Name' %}</th>
<th>{% trans 'Provider' %}</th>
<th>{% trans 'Delegation domain' %}</th>
<th>{% trans 'Hosts' %}</th>
<th>{% trans 'Actions' %}</th>
</tr>
@@ -213,6 +213,7 @@
<tr>
<td>{{ dns_credential.display_name|default:dns_credential.name }}</td>
<td>{{ dns_credential.get_provider_display }}</td>
<td>{{ dns_credential.delegation_domain|default:'-' }}</td>
<td>{{ dns_credential.hosts.count }}</td>
<td style="width: 15%">
<a href="{% url 'manage_dns_credential' %}?uuid={{ dns_credential.uuid }}"
@@ -241,3 +242,19 @@
</div>
</div>
{% endblock %}
{% block page_custom_head %}
<style>
.tooltip-inner.host-certificate-tooltip {
max-width: 420px;
}
</style>
{% endblock %}
{% block custom_page_scripts %}
<script>
$(function () {
$('[data-toggle="tooltip"]').tooltip();
});
</script>
{% endblock %}
+14 -5
View File
@@ -84,11 +84,7 @@
<tr>
<td>{{ host.hostname }}</td>
<td>
{{ host.get_certificate_type_display }}
{% if host.dns_credential %}<small class="text-muted">({{ host.dns_credential }})</small>{% endif %}
{% if host.certificate_type != 'self_signed' and not host.certificate_fallback %}
<small class="text-muted">({% trans 'no fallback' %})</small>
{% endif %}
{% include 'app_gateway/host_certificate.html' %}
</td>
{% if caddy_enabled %}
<td class="certificate-status" data-host-uuid="{{ host.uuid }}">
@@ -188,7 +184,20 @@
</div>
{% endblock %}
{% block page_custom_head %}
<style>
.tooltip-inner.host-certificate-tooltip {
max-width: 420px;
}
</style>
{% endblock %}
{% block custom_page_scripts %}
<script>
$(function () {
$('[data-toggle="tooltip"]').tooltip();
});
</script>
{% if caddy_enabled and hosts %}
<script>
$(document).ready(function () {
@@ -0,0 +1,128 @@
{% extends 'generic_form.html' %}
{% load i18n %}
{% block custom_page_scripts %}
{{ block.super }}
<div class="modal fade" id="dnsDelegationModal" tabindex="-1" aria-labelledby="dnsDelegationModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="dnsDelegationModalLabel">{% trans 'CNAME record required' %}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="{% trans 'Close' %}">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<p>{% blocktrans trimmed %}
Make sure this record exists in the DNS zone of the hostname. The certificate is requested as
soon as the configuration is applied, and without the record it cannot be issued.
{% endblocktrans %}</p>
<div class="dns-delegation-record"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">{% trans 'Back' %}</button>
<button type="button" class="btn btn-primary" id="dnsDelegationConfirm">{% trans 'I created the record, save' %}</button>
</div>
</div>
</div>
</div>
{{ delegation_domains|json_script:'dns-delegation-domains' }}
<script>
$(document).ready(function () {
var delegationDomains = JSON.parse(document.getElementById('dns-delegation-domains').textContent);
var initialRecord = "{{ initial_delegation_record|escapejs }}";
var labels = {
type: "{% trans 'Type'|escapejs %}",
name: "{% trans 'Name'|escapejs %}",
target: "{% trans 'Target'|escapejs %}",
copy: "{% trans 'Copy'|escapejs %}"
};
var $form = $('#id_hostname').closest('form');
var confirmed = false;
function challengeBase(hostname) {
hostname = hostname.trim().toLowerCase().replace(/\.+$/, '');
return hostname.indexOf('*.') === 0 ? hostname.substring(2) : hostname;
}
function currentRecord() {
var hostname = challengeBase($('#id_hostname').val() || '');
var delegationDomain = delegationDomains[$('#id_dns_credential').val()];
if ($('#id_certificate_type').val() !== 'dns_challenge' || !delegationDomain || !hostname) {
return null;
}
// Hostnames inside the delegation domain are validated directly
if (hostname === delegationDomain || hostname.endsWith('.' + delegationDomain)) {
return null;
}
return {name: '_acme-challenge.' + hostname, target: hostname + '.' + delegationDomain};
}
function recordField(label, value) {
var $group = $('<div class="input-group input-group-sm mb-2"></div>');
$group.append($('<div class="input-group-prepend"></div>').append(
$('<span class="input-group-text" style="min-width: 5em"></span>').text(label)
));
var $input = $('<input type="text" class="form-control text-monospace" readonly>').val(value);
$group.append($input);
var $button = $('<button type="button" class="btn btn-outline-secondary"></button>')
.attr('title', labels.copy).html('<i class="far fa-copy"></i>');
$button.on('click', function () {
$input.trigger('select');
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(value);
} else {
document.execCommand('copy');
}
});
$group.append($('<div class="input-group-append"></div>').append($button));
return $group;
}
function renderRecord(record) {
$('.dns-delegation-record').each(function () {
$(this).empty()
.append(recordField(labels.type, 'CNAME'))
.append(recordField(labels.name, record.name))
.append(recordField(labels.target, record.target));
});
}
function updateAlert() {
var record = currentRecord();
$('#dns-delegation-alert').toggleClass('d-none', !record);
if (record) {
renderRecord(record);
}
}
$('#id_hostname').on('input', updateAlert);
$('#id_certificate_type, #id_dns_credential').on('change', updateAlert);
updateAlert();
// Ask for confirmation only when the required record is new or changed
$form.on('submit', function (event) {
var record = currentRecord();
if (confirmed || !record || record.name + ' ' + record.target === initialRecord) {
return;
}
event.preventDefault();
renderRecord(record);
$('#dnsDelegationModal').modal('show');
});
$('#dnsDelegationConfirm').on('click', function () {
confirmed = true;
$('#dnsDelegationModal').modal('hide');
// The submit button is named "submit", which hides the form.submit() method
var form = $form[0];
if (form.requestSubmit) {
form.requestSubmit();
} else {
HTMLFormElement.prototype.submit.call(form);
}
});
});
</script>
{% endblock %}
@@ -28,6 +28,15 @@
API Token with the <strong>Zone / Zone / Read</strong> and <strong>Zone / DNS / Edit</strong> permissions.
{% endblocktrans %}</p>
<p>{% trans 'Secret values are never displayed after saving. Leave them blank when editing to keep the current value.' %}</p>
<h5>{% trans 'Delegation domain' %}</h5>
<p>{% blocktrans trimmed %}
Use a delegation domain when the zone of the hostnames is not managed by this provider, or
to keep the token restricted to a zone used only for certificate validation. The challenge
record is created in the delegation domain, and each hostname needs a CNAME record pointing
to it:
{% endblocktrans %}</p>
<p><code>_acme-challenge.app.example.com CNAME app.example.com.acme.example.net</code></p>
<p>{% trans 'The token must be able to edit the DNS records of the delegation domain zone. The required record of each host is shown when the host is edited and in the host list.' %}</p>
</div>
</div>
</div>
@@ -0,0 +1,9 @@
{% load i18n %}
<div id="dns-delegation-alert" class="alert alert-warning d-none">
<h5><i class="icon fas fa-exclamation-triangle"></i> {% trans 'CNAME record required' %}</h5>
<p class="mb-2">{% blocktrans trimmed %}
This DNS credential uses a delegation domain. Create this record in the DNS zone of the hostname
before saving, otherwise the certificate cannot be issued:
{% endblocktrans %}</p>
<div class="dns-delegation-record"></div>
</div>
@@ -0,0 +1,20 @@
{% load i18n %}{% with record=host.dns_delegation_record %}
{{ host.certificate_label }}
{% if host.certificate_type != 'self_signed' %}
{% if host.certificate_fallback %}
<span class="badge badge-secondary">{% trans 'fallback' %}</span>
{% else %}
<span class="badge badge-warning">{% trans 'no fallback' %}</span>
{% endif %}
<i class="fas fa-info-circle text-muted ml-1" data-toggle="tooltip" data-html="true"
data-template='<div class="tooltip" role="tooltip"><div class="arrow"></div><div class="tooltip-inner host-certificate-tooltip"></div></div>'
title="{% filter force_escape %}
<div class='text-left'>
{% if host.dns_credential %}<strong>{% trans 'DNS Credential' %}:</strong> {{ host.dns_credential }}<br>{% endif %}
{% if record %}<strong>{% trans 'Required record' %}:</strong><br><code>{{ record.0 }}</code><br>CNAME <code>{{ record.1 }}</code><br>{% endif %}
<strong>{% trans 'Fallback' %}:</strong>
{% if host.certificate_fallback %}{% trans 'self-signed certificate while the trusted certificate cannot be issued' %}{% else %}{% trans 'disabled, the connection fails until the certificate is issued' %}{% endif %}
</div>
{% endfilter %}"></i>
{% endif %}
{% endwith %}