diff --git a/app_gateway/caddy_config_export.py b/app_gateway/caddy_config_export.py index 2efbcf1..ae79c5c 100644 --- a/app_gateway/caddy_config_export.py +++ b/app_gateway/caddy_config_export.py @@ -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, diff --git a/app_gateway/forms.py b/app_gateway/forms.py index 0a78fb7..2a02258 100644 --- a/app_gateway/forms.py +++ b/app_gateway/forms.py @@ -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') diff --git a/app_gateway/migrations/0014_dnschallengecredential_delegation_domain.py b/app_gateway/migrations/0014_dnschallengecredential_delegation_domain.py new file mode 100644 index 0000000..869b10e --- /dev/null +++ b/app_gateway/migrations/0014_dnschallengecredential_delegation_domain.py @@ -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), + ), + ] diff --git a/app_gateway/models.py b/app_gateway/models.py index 1c16613..3eccde2 100644 --- a/app_gateway/models.py +++ b/app_gateway/models.py @@ -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'] diff --git a/app_gateway/tests.py b/app_gateway/tests.py index 8efd6f4..ddf9af3 100644 --- a/app_gateway/tests.py +++ b/app_gateway/tests.py @@ -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]) diff --git a/app_gateway/views.py b/app_gateway/views.py index ec736f0..da3a8b1 100644 --- a/app_gateway/views.py +++ b/app_gateway/views.py @@ -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):

Defines how the TLS certificate for this hostname is issued.

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.

@@ -310,13 +310,22 @@ def view_manage_application_host(request): ''') + 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) diff --git a/containers/caddy/process_config.py b/containers/caddy/process_config.py index b574f08..6eb6bd2 100644 --- a/containers/caddy/process_config.py +++ b/containers/caddy/process_config.py @@ -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()] = [ diff --git a/templates/app_gateway/app_gateway_list.html b/templates/app_gateway/app_gateway_list.html index 6b5c125..1213a32 100644 --- a/templates/app_gateway/app_gateway_list.html +++ b/templates/app_gateway/app_gateway_list.html @@ -128,8 +128,7 @@ - {{ host.get_certificate_type_display }} - {% if host.dns_credential %}({{ host.dns_credential }}){% endif %} + {% include 'app_gateway/host_certificate.html' %} {% endfor %} @@ -204,6 +203,7 @@ {% trans 'Name' %} {% trans 'Provider' %} + {% trans 'Delegation domain' %} {% trans 'Hosts' %} {% trans 'Actions' %} @@ -213,6 +213,7 @@ {{ dns_credential.display_name|default:dns_credential.name }} {{ dns_credential.get_provider_display }} + {{ dns_credential.delegation_domain|default:'-' }} {{ dns_credential.hosts.count }} {% endblock %} + +{% block page_custom_head %} + +{% endblock %} + +{% block custom_page_scripts %} + +{% endblock %} diff --git a/templates/app_gateway/application_details.html b/templates/app_gateway/application_details.html index caabbb0..4449143 100644 --- a/templates/app_gateway/application_details.html +++ b/templates/app_gateway/application_details.html @@ -84,11 +84,7 @@ {{ host.hostname }} - {{ host.get_certificate_type_display }} - {% if host.dns_credential %}({{ host.dns_credential }}){% endif %} - {% if host.certificate_type != 'self_signed' and not host.certificate_fallback %} - ({% trans 'no fallback' %}) - {% endif %} + {% include 'app_gateway/host_certificate.html' %} {% if caddy_enabled %} @@ -188,7 +184,20 @@ {% endblock %} +{% block page_custom_head %} + +{% endblock %} + {% block custom_page_scripts %} + {% if caddy_enabled and hosts %} +{% endblock %} diff --git a/templates/app_gateway/dns_credential_form.html b/templates/app_gateway/dns_credential_form.html index c19887e..d52bb93 100644 --- a/templates/app_gateway/dns_credential_form.html +++ b/templates/app_gateway/dns_credential_form.html @@ -28,6 +28,15 @@ API Token with the Zone / Zone / Read and Zone / DNS / Edit permissions. {% endblocktrans %}

{% trans 'Secret values are never displayed after saving. Leave them blank when editing to keep the current value.' %}

+
{% trans 'Delegation domain' %}
+

{% 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 %}

+

_acme-challenge.app.example.com CNAME app.example.com.acme.example.net

+

{% 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.' %}

diff --git a/templates/app_gateway/dns_delegation_alert.html b/templates/app_gateway/dns_delegation_alert.html new file mode 100644 index 0000000..fd1e0b7 --- /dev/null +++ b/templates/app_gateway/dns_delegation_alert.html @@ -0,0 +1,9 @@ +{% load i18n %} +
+
{% trans 'CNAME record required' %}
+

{% 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 %}

+
+
diff --git a/templates/app_gateway/host_certificate.html b/templates/app_gateway/host_certificate.html new file mode 100644 index 0000000..4978bf8 --- /dev/null +++ b/templates/app_gateway/host_certificate.html @@ -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 %} + {% trans 'fallback' %} + {% else %} + {% trans 'no fallback' %} + {% endif %} + +{% endif %} +{% endwith %}