change app dns bind behavior

This commit is contained in:
leo committed 2026-11-22 22:44:47 +02:00
1 parent dd50a0d05e
commit 40a8ed23cd
17 files changed
+1440 -104

No files matched your search

+299 -41
View File
@@ -6,6 +6,7 @@ import ipaddress
import re
from dataclasses import dataclass, field
from .addressing import PublicAddressResolver
from .cloudflare import CloudflareClient, Zone
from .config import Config
from .errors import ConfigError, ProxdomainError
@@ -60,6 +61,7 @@ class DomainService:
cloudflare: CloudflareClient | None = None,
webserver: WebServerManager | None = None,
state: StateStore | None = None,
dns_resolver: PublicAddressResolver | None = None,
) -> None:
self.config = config
self.state = state or StateStore(
@@ -71,6 +73,7 @@ class DomainService:
self._proxmox = proxmox
self._cloudflare = cloudflare
self._webserver = webserver
self._dns_resolver = dns_resolver
# -- lazy clients (so `list` works without API credentials) ---------
@property
@@ -93,6 +96,14 @@ class DomainService:
)
return self._webserver
@property
def dns_resolver(self) -> PublicAddressResolver:
if self._dns_resolver is None:
self._dns_resolver = PublicAddressResolver(
self.config.dns, preference=self.config.proxmox.ip_preference
)
return self._dns_resolver
# -- main workflow --------------------------------------------------
def assign(
self,
@@ -102,6 +113,7 @@ class DomainService:
subdomain: str | None = None,
port: int | None = None,
ip: str | None = None,
address: str | None = None,
proxied: bool | None = None,
force: bool = False,
dry_run: bool = False,
@@ -122,20 +134,32 @@ class DomainService:
return report.fail("domain", str(exc))
try:
address = ip or self.proxmox.guest_ip(guest)
guest_address = ip or self.proxmox.guest_ip(guest)
except ProxdomainError as exc:
return report.fail("address", str(exc))
if not address:
if not guest_address:
return report.fail(
"address",
f"no usable IP address found for {guest.label}; pass --ip, install "
"qemu-guest-agent in the VM, or set a static ip= in the guest config",
)
try:
parsed_ip = ipaddress.ip_address(address)
ipaddress.ip_address(guest_address)
except ValueError:
return report.fail("address", f"{address!r} is not a valid IP address")
report.add("address", "ok", f"{address} ({'argument' if ip else 'discovered'})")
return report.fail("address", f"{guest_address!r} is not a valid IP address")
report.add(
"address",
"ok",
f"guest {guest_address} ({'argument' if ip else 'discovered'})",
)
try:
published = self.dns_resolver.resolve(
guest_address=guest_address, override=address
)
except ProxdomainError as exc:
return report.fail("dns-address", str(exc))
report.add("dns-address", "ok", f"{published.address} ({published.source})")
report.add("domain", "ok", fqdn)
target_port = int(port or self.config.general.default_port)
@@ -155,18 +179,57 @@ class DomainService:
return report
effective_proxied = self.config.cloudflare.proxied if proxied is None else proxied
parsed_dns = ipaddress.ip_address(published.address)
proxy_note = ""
if effective_proxied and not parsed_ip.is_global:
if effective_proxied and not parsed_dns.is_global:
effective_proxied = False
proxy_note = (
f"{address} is not a public address, so the Cloudflare proxy "
f"{published.address} is not a public address, so the Cloudflare proxy "
"(orange cloud) was disabled; only the DNS record is created"
)
spec = self._site_spec(guest, fqdn, address, target_port)
spec = self._site_spec(guest, fqdn, guest_address, target_port)
record_type = "A" if parsed_dns.version == 4 else "AAAA"
# Ordering: ACME needs the name to resolve to this host before it can
# validate, so a certificate that is still missing forces DNS to be
# published first (Caddy starts ACME as soon as it reloads, so it always
# goes first there). Everywhere else the vhost is written first, so a
# failing DNS call cannot advertise a name that nothing answers for.
dns_first = zone is not None and not dry_run and self._dns_before_config(spec)
upsert = None
if dns_first:
try:
upsert = self.cloudflare.upsert_address_record(
zone.id, fqdn, published.address, proxied=effective_proxied
)
except ProxdomainError as exc:
report.fail("dns", str(exc))
report.add(
"result",
"warning",
"a Let's Encrypt certificate needs this name to resolve first, "
"so nothing was changed; fix the DNS error and re-run assign",
)
return report
report.add(
"dns",
"changed" if upsert.changed else "ok",
f"{upsert.action} {record_type} {fqdn} -> {published.address} "
f"(proxied={'yes' if effective_proxied else 'no'}; "
"published before the certificate request)",
)
try:
applied = self.webserver.apply(spec, dry_run=dry_run)
except ProxdomainError as exc:
if upsert is not None:
self.state.audit(
"assign.dns-only",
fqdn=fqdn,
vmid=guest.vmid,
content=published.address,
)
return report.fail("web-config", str(exc))
if dry_run:
status = "planned"
@@ -179,6 +242,9 @@ class DomainService:
status,
"; ".join(applied.messages) or applied.path,
)
tls_step = self._tls_step(spec)
if tls_step is not None:
report.add(*tls_step)
if proxy_note:
report.add("dns", "warning", proxy_note)
@@ -187,7 +253,8 @@ class DomainService:
)
assignment.name = guest.name
assignment.vmid = guest.vmid
assignment.ip = address
assignment.ip = guest_address
assignment.dns_ip = published.address
assignment.port = target_port
assignment.node = guest.node
assignment.kind = guest.kind
@@ -197,14 +264,15 @@ class DomainService:
assignment.zone_id = zone.id
assignment.zone_name = zone.name
record_type = "A" if parsed_ip.version == 4 else "AAAA"
record_type = "A" if parsed_dns.version == 4 else "AAAA"
if not dry_run:
self._save(assignment)
self.state.audit(
"assign.web-config",
fqdn=fqdn,
vmid=guest.vmid,
address=address,
guest_address=guest_address,
dns_address=published.address,
port=target_port,
path=applied.path,
)
@@ -215,47 +283,57 @@ class DomainService:
return report
if dry_run:
self._preview_dns(report, zone, fqdn, address, record_type, effective_proxied)
self._preview_dns(
report, zone, fqdn, published.address, record_type, effective_proxied
)
report.add("result", "planned", "dry run: nothing was changed")
report.assignment = assignment
return report
try:
upsert = self.cloudflare.upsert_address_record(
zone.id,
fqdn,
address,
proxied=effective_proxied,
)
except ProxdomainError as exc:
report.fail("dns", str(exc))
report.add(
"result",
"warning",
"the web server config is in place; fix the DNS error and re-run "
"assign (it is idempotent)",
)
report.assignment = assignment
return report
if upsert is None:
try:
upsert = self.cloudflare.upsert_address_record(
zone.id,
fqdn,
published.address,
proxied=effective_proxied,
)
except ProxdomainError as exc:
report.fail("dns", str(exc))
report.add(
"result",
"warning",
"the web server config is in place; fix the DNS error and re-run "
"assign (it is idempotent)",
)
report.assignment = assignment
return report
assignment.record_type = upsert.record.type or record_type
assignment.record_id = upsert.record.id
assignment.tls = self.config.webserver.tls.mode
self._save(assignment)
self.state.audit(
"assign.dns",
fqdn=fqdn,
record_id=upsert.record.id,
action=upsert.action,
content=address,
content=published.address,
guest_address=guest_address,
proxied=effective_proxied,
)
if not dns_first:
report.add(
"dns",
"changed" if upsert.changed else "ok",
f"{upsert.action} {record_type} {fqdn} -> {published.address} "
f"(proxied={'yes' if effective_proxied else 'no'})",
)
report.add(
"dns",
"changed" if upsert.changed else "ok",
f"{upsert.action} {record_type} {fqdn} -> {address} "
f"(proxied={'yes' if effective_proxied else 'no'})",
"result",
"ok",
f"{fqdn} -> {spec.target} (published {published.address})",
)
report.add("result", "ok", f"{fqdn} -> {spec.target}")
report.assignment = assignment
return report
@@ -358,14 +436,26 @@ class DomainService:
report.add("guest", "warning", f"{assignment.fqdn}: {exc}")
continue
try:
address = self.proxmox.guest_ip(guest) or assignment.ip
guest_address = self.proxmox.guest_ip(guest) or assignment.ip
except ProxdomainError as exc:
report.add("guest", "warning", f"{assignment.fqdn}: {exc}")
continue
if not address:
if not guest_address:
report.add("guest", "warning", f"{assignment.fqdn}: guest has no IP")
continue
spec = self._site_spec(guest, assignment.fqdn, address, assignment.port)
try:
published = self.dns_resolver.resolve(guest_address=guest_address)
except ProxdomainError as exc:
report.fail("dns-address", f"{assignment.fqdn}: {exc}")
continue
if published.address != assignment.dns_ip:
report.add(
"dns-address",
"planned" if dry_run else "changed",
f"{assignment.fqdn}: {assignment.dns_ip or '-'} -> "
f"{published.address} ({published.source})",
)
spec = self._site_spec(guest, assignment.fqdn, guest_address, assignment.port)
try:
result = self.webserver.apply(spec, dry_run=dry_run)
except ProxdomainError as exc:
@@ -380,20 +470,28 @@ class DomainService:
)
if dry_run or not assignment.zone_id:
assignment.ip = guest_address
assignment.dns_ip = published.address
continue
try:
upsert = self.cloudflare.upsert_address_record(
assignment.zone_id, assignment.fqdn, address
assignment.zone_id, assignment.fqdn, published.address
)
except ProxdomainError as exc:
report.fail("dns", f"{assignment.fqdn}: {exc}")
continue
assignment.ip = address
assignment.ip = guest_address
assignment.dns_ip = published.address
assignment.tls = self.config.webserver.tls.mode
assignment.record_type = upsert.record.type or assignment.record_type
assignment.record_id = upsert.record.id
if upsert.changed:
changed += 1
report.add("dns", "changed", f"{assignment.fqdn}: {upsert.action} -> {address}")
report.add(
"dns",
"changed",
f"{assignment.fqdn}: {upsert.action} -> {published.address}",
)
self._save(assignment)
report.add(
@@ -449,6 +547,24 @@ class DomainService:
f"{exc} (the token needs Zone:Read and DNS:Edit)",
)
if self.config.dns.target == "guest":
report.add(
"dns-target",
"ok",
"guest: each record publishes the guest's own address",
)
else:
try:
resolved = self.dns_resolver.resolve(guest_address="")
report.add(
"dns-target",
"ok",
f"target {self.config.dns.target}: {resolved.address} "
f"({resolved.source})",
)
except ProxdomainError as exc:
report.fail("dns-target", str(exc))
report.add(
"web-server",
"ok",
@@ -479,13 +595,99 @@ class DomainService:
except ProxdomainError as exc:
report.fail("web-server", str(exc))
report.add(*self._doctor_tls())
try:
items = self.state.all()
report.add("state", "ok", f"{len(items)} assignment(s) in {self.state.path}")
except ProxdomainError as exc:
report.fail("state", str(exc))
items = []
if items and self.config.webserver.tls.mode in ("letsencrypt", "certbot"):
report.add(*self._doctor_certificates(items))
return report
def _doctor_tls(self) -> tuple[str, str, str]:
tls = self.config.webserver.tls
kind = self.config.webserver.kind
if tls.mode == "none":
return (
"tls",
"skipped",
"not managed (webserver.tls.mode = 'none'); set 'letsencrypt' for "
"automatic HTTPS",
)
if tls.mode == "files":
present = self.webserver.runner.exists(tls.cert_dir)
return (
"tls",
"ok" if present else "warning",
f"files mode: reading certificates from {tls.cert_dir}"
if present
else f"files mode, but {tls.cert_dir} does not exist",
)
if kind == "caddy":
return (
"tls",
"ok",
f"letsencrypt: Caddy's ACME issuer requests certificates on demand "
f"({tls.email}) and renews them automatically",
)
if kind == "traefik":
return (
"tls",
"ok",
f"letsencrypt: Traefik certResolver "
f"{self.config.webserver.cert_resolver} (must be defined in the "
"static config with an ACME configuration)",
)
try:
binary = (tls.certbot_command or ("certbot",))[0]
probe = self.webserver.runner.run([binary, "--version"])
except ProxdomainError as exc:
return ("tls", "warning", f"cannot run certbot: {exc}")
if not probe.ok:
return (
"tls",
"warning",
f"{binary} is not installed or not executable; install certbot "
"(apt install certbot) so proxdomain can issue Let's Encrypt "
"certificates",
)
version = probe.stdout.strip() or probe.output(limit=60)
return (
"tls",
"ok",
f"letsencrypt via {binary} ({version}); webroot {tls.webroot}, "
f"renew hook '{self.webserver.renew_hook or '-'}'",
)
def _doctor_certificates(self, items: list[Assignment]) -> tuple[str, str, str]:
if self.config.webserver.kind != "nginx":
return (
"tls-certs",
"ok",
f"{len(items)} site(s) handled by "
f"{self.config.webserver.kind}, which renews certificates itself",
)
cert_dir = self.config.webserver.tls.cert_dir
missing = [
item.fqdn
for item in items
if not self.webserver.runner.exists(f"{cert_dir}/{item.fqdn}/fullchain.pem")
]
if not missing:
return (
"tls-certs",
"ok",
f"a certificate exists for all {len(items)} managed site(s)",
)
return (
"tls-certs",
"warning",
f"no certificate for {', '.join(missing)}; re-run assign for those guests",
)
def init(self, *, dry_run: bool = False) -> ServiceReport:
report = ServiceReport("init")
try:
@@ -528,6 +730,59 @@ class DomainService:
raise ProxdomainError(f"{fqdn!r} is not a valid DNS name")
return fqdn
def _dns_before_config(self, spec: SiteSpec) -> bool:
"""True when ACME needs the public record in place before the vhost."""
webserver = self.config.webserver
if webserver.tls.mode != "letsencrypt" and webserver.tls.mode != "certbot":
return False
if webserver.kind == "caddy":
# Caddy starts issuing the moment the new site block is loaded.
return True
return self._certificate_missing(spec)
def _certificate_missing(self, spec: SiteSpec) -> bool:
"""True when a certificate must still be obtained before TLS can serve."""
return self.webserver.issues_certificates and not self.webserver.certificate_present(spec)
def _tls_step(self, spec: SiteSpec) -> tuple[str, str, str] | None:
mode = self.config.webserver.tls.mode
kind = self.config.webserver.kind
if mode == "none":
return (
"tls",
"skipped",
"tls.mode = 'none'; set webserver.tls.mode = 'letsencrypt' for HTTPS",
)
if mode == "files":
if self.webserver.certificate_present(spec):
return ("tls", "ok", f"certificate files present in {spec.cert_dir}")
return (
"tls",
"warning",
f"no certificate at {spec.certificate}; the vhost will fail to load "
"once nginx is reloaded",
)
if kind == "caddy":
return (
"tls",
"ok",
"Caddy requests and renews a Let's Encrypt certificate for this site",
)
if kind == "traefik":
return (
"tls",
"ok",
f"Traefik obtains the certificate through certResolver "
f"{self.config.webserver.cert_resolver}",
)
if self.webserver.certificate_present(spec):
expiry = self.webserver.certificate_expiry(spec)
detail = f"Let's Encrypt certificate present ({spec.certificate})"
if expiry:
detail = f"Let's Encrypt certificate valid until {expiry}"
return ("tls", "ok", detail)
return ("tls", "warning", "no certificate yet; run assign again to finish issuance")
def _site_spec(
self, guest: Guest, fqdn: str, address: str, port: int
) -> SiteSpec:
@@ -543,6 +798,9 @@ class DomainService:
cert_dir=self.config.webserver.tls.cert_dir,
webroot=self.config.webserver.tls.webroot,
cert_resolver=self.config.webserver.cert_resolver,
tls_email=self.config.webserver.tls.email,
acme_ca=self.config.webserver.tls.acme_ca,
renew_hook=self.webserver.renew_hook,
)
def _find_zone(