change app dns bind behavior
This commit is contained in:
1 parent
dd50a0d05e
commit
40a8ed23cd
17 files changed
+1440
-104
No files matched your search
@@ -7,5 +7,5 @@ reverse-proxy config for nginx, Caddy or Traefik.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
__version__ = "0.1.0"
|
||||
__version__ = "0.3.0"
|
||||
__all__ = ["__version__"]
|
||||
Executable
+204
@@ -0,0 +1,204 @@
|
||||
"""Decide which address the public DNS record points at.
|
||||
|
||||
Reverse proxies normally run on the Proxmox host, so the record must publish the
|
||||
host's public address while the vhost keeps proxying to the guest's private one.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import socket
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable, Sequence
|
||||
|
||||
from . import __version__
|
||||
from .config import DnsConfig
|
||||
from .errors import ProxdomainError
|
||||
from .http import Transport, UrllibTransport
|
||||
|
||||
HostnameResolver = Callable[[str], Sequence[str]]
|
||||
TextFetcher = Callable[[str], str]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ResolvedAddress:
|
||||
address: str
|
||||
source: str
|
||||
|
||||
|
||||
class PublicAddressResolver:
|
||||
"""Resolve the address to publish, according to `[dns] target`.
|
||||
|
||||
The host result is cached for the lifetime of the resolver (one sync run),
|
||||
so a batch of assignments performs at most one detection request.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: DnsConfig,
|
||||
*,
|
||||
preference: str = "ipv4",
|
||||
transport: Transport | None = None,
|
||||
fetch_text: TextFetcher | None = None,
|
||||
hostname_resolver: HostnameResolver | None = None,
|
||||
) -> None:
|
||||
self.config = config
|
||||
self.preference = preference
|
||||
self._transport = transport
|
||||
self._fetch_text = fetch_text
|
||||
self._hostname_resolver = hostname_resolver or system_hostname_addresses
|
||||
self._host_cache: ResolvedAddress | None = None
|
||||
|
||||
def resolve(
|
||||
self, *, guest_address: str = "", override: str | None = None
|
||||
) -> ResolvedAddress:
|
||||
if override:
|
||||
return ResolvedAddress(_require_ip(override, "the --address override"), "command line")
|
||||
if self.config.target == "guest":
|
||||
return ResolvedAddress(_require_ip(guest_address, "the guest address"), "guest")
|
||||
if self.config.target == "fixed":
|
||||
return ResolvedAddress(
|
||||
_require_ip(self.config.address, "dns.address"), "dns.address"
|
||||
)
|
||||
if self._host_cache is None:
|
||||
self._host_cache = self._resolve_host()
|
||||
return self._host_cache
|
||||
|
||||
# -- host resolution ------------------------------------------------
|
||||
def _resolve_host(self) -> ResolvedAddress:
|
||||
if self.config.address:
|
||||
return ResolvedAddress(
|
||||
_require_ip(self.config.address, "dns.address"), "dns.address"
|
||||
)
|
||||
if self.config.hostname:
|
||||
return self._from_hostname()
|
||||
return self._detect()
|
||||
|
||||
def _from_hostname(self) -> ResolvedAddress:
|
||||
hostname = self.config.hostname
|
||||
try:
|
||||
raw = self._hostname_resolver(hostname)
|
||||
except OSError as exc:
|
||||
raise ProxdomainError(
|
||||
f"cannot resolve dns.hostname {hostname}: {exc}; "
|
||||
"set dns.address instead"
|
||||
) from exc
|
||||
parsed: list[ipaddress._BaseAddress] = []
|
||||
for value in raw:
|
||||
try:
|
||||
parsed.append(ipaddress.ip_address(str(value)))
|
||||
except ValueError:
|
||||
continue
|
||||
public = [address for address in parsed if address.is_global]
|
||||
chosen = _pick(public or parsed, self.preference)
|
||||
if chosen is None:
|
||||
raise ProxdomainError(
|
||||
f"dns.hostname {hostname} did not resolve to a "
|
||||
f"{self.preference} address; set dns.address instead"
|
||||
)
|
||||
return ResolvedAddress(str(chosen), f"hostname {hostname}")
|
||||
|
||||
def _detect(self) -> ResolvedAddress:
|
||||
urls = self._detect_urls()
|
||||
if not urls:
|
||||
raise ProxdomainError(
|
||||
"dns.target = 'host' has no dns.address, dns.hostname or detection URL; "
|
||||
"set dns.address"
|
||||
)
|
||||
failures: list[str] = []
|
||||
for url in urls:
|
||||
try:
|
||||
text = self._get(url)
|
||||
except ProxdomainError as exc:
|
||||
failures.append(str(exc))
|
||||
continue
|
||||
candidate = extract_address(text)
|
||||
if candidate is None:
|
||||
failures.append(f"{url} returned no IP address")
|
||||
continue
|
||||
address = ipaddress.ip_address(candidate)
|
||||
if not address.is_global:
|
||||
failures.append(f"{url} returned the non-public address {candidate}")
|
||||
continue
|
||||
return ResolvedAddress(str(address), f"detected via {url}")
|
||||
raise ProxdomainError(
|
||||
"cannot determine the Proxmox host's public address: "
|
||||
+ "; ".join(failures)
|
||||
+ "; set dns.address (or dns.hostname) in the config, or pass --address"
|
||||
)
|
||||
|
||||
def _detect_urls(self) -> list[str]:
|
||||
if self.preference == "ipv4":
|
||||
candidates = [self.config.detect_url_v4]
|
||||
elif self.preference == "ipv6":
|
||||
candidates = [self.config.detect_url_v6]
|
||||
else:
|
||||
candidates = [self.config.detect_url_v4, self.config.detect_url_v6]
|
||||
return [url for url in candidates if url]
|
||||
|
||||
def _get(self, url: str) -> str:
|
||||
if self._fetch_text is not None:
|
||||
return self._fetch_text(url)
|
||||
transport = self._transport or UrllibTransport()
|
||||
try:
|
||||
response = transport.request(
|
||||
"GET",
|
||||
url,
|
||||
{
|
||||
"User-Agent": f"proxdomain/{__version__}",
|
||||
"Accept": "text/plain",
|
||||
},
|
||||
None,
|
||||
self.config.detect_timeout,
|
||||
)
|
||||
except ProxdomainError:
|
||||
raise
|
||||
except Exception as exc: # pragma: no cover - defensive around urllib
|
||||
raise ProxdomainError(f"cannot reach {url}: {exc}") from exc
|
||||
if response.status >= 400:
|
||||
raise ProxdomainError(f"GET {url} -> HTTP {response.status}")
|
||||
return response.text()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
def extract_address(text: str) -> str | None:
|
||||
"""Accept `203.0.113.10`, `ip=203.0.113.10` (Cloudflare trace) or a sentence."""
|
||||
for line in text.splitlines():
|
||||
candidate_line = line.strip()
|
||||
if not candidate_line:
|
||||
continue
|
||||
if candidate_line.startswith("ip="):
|
||||
candidates = [candidate_line[3:]]
|
||||
else:
|
||||
candidates = candidate_line.replace("=", " ").split()
|
||||
for candidate in candidates:
|
||||
candidate = candidate.strip().strip("\"'")
|
||||
try:
|
||||
return str(ipaddress.ip_address(candidate))
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def system_hostname_addresses(hostname: str) -> list[str]:
|
||||
infos = socket.getaddrinfo(hostname, None, type=socket.SOCK_STREAM)
|
||||
seen: list[str] = []
|
||||
for info in infos:
|
||||
value = str(info[4][0])
|
||||
if value not in seen:
|
||||
seen.append(value)
|
||||
return seen
|
||||
|
||||
|
||||
def _pick(addresses: Sequence[ipaddress._BaseAddress], preference: str):
|
||||
wanted = 4 if preference == "ipv4" else 6 if preference == "ipv6" else None
|
||||
if wanted is not None:
|
||||
addresses = [address for address in addresses if address.version == wanted]
|
||||
return addresses[0] if addresses else None
|
||||
|
||||
|
||||
def _require_ip(value: str, label: str) -> str:
|
||||
try:
|
||||
return str(ipaddress.ip_address(str(value).strip()))
|
||||
except ValueError as exc:
|
||||
raise ProxdomainError(f"{label} is not a valid IP address: {value!r}") from exc
|
||||
+10
-4
@@ -65,7 +65,11 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
help="subdomain label (app) or full name (app.example.com); default: from domain_template",
|
||||
)
|
||||
assign.add_argument("--port", type=int, help="backend port on the guest (default: general.default_port)")
|
||||
assign.add_argument("--ip", help="override the discovered guest IP")
|
||||
assign.add_argument("--ip", help="override the guest IP used as the proxy target")
|
||||
assign.add_argument(
|
||||
"--address",
|
||||
help="override the published DNS address (default: the Proxmox host public IP)",
|
||||
)
|
||||
assign.add_argument(
|
||||
"--proxied",
|
||||
dest="proxied",
|
||||
@@ -161,6 +165,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
subdomain=args.subdomain,
|
||||
port=args.port,
|
||||
ip=args.ip,
|
||||
address=args.address,
|
||||
proxied=args.proxied,
|
||||
force=args.force,
|
||||
dry_run=args.dry_run,
|
||||
@@ -226,14 +231,15 @@ def _list(service: DomainService, json_output: bool) -> int:
|
||||
print("no managed domains yet (run: proxdomain assign --vmid <id>)")
|
||||
return 0
|
||||
|
||||
headers = ("FQDN", "VMID", "NODE", "IP", "PORT", "DNS")
|
||||
headers = ("FQDN", "VMID", "NODE", "TARGET", "PUBLISHED", "TLS", "RECORD")
|
||||
rows = [
|
||||
(
|
||||
item.fqdn,
|
||||
str(item.vmid),
|
||||
item.node,
|
||||
item.ip or "-",
|
||||
str(item.port),
|
||||
f"{item.ip or '-'}:{item.port}",
|
||||
item.dns_ip or "-",
|
||||
item.tls or "none",
|
||||
"yes" if item.record_id else "-",
|
||||
)
|
||||
for item in items
|
||||
|
||||
+102
-19
@@ -2,7 +2,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import os
|
||||
import re
|
||||
import tomllib
|
||||
from dataclasses import dataclass, replace
|
||||
from pathlib import Path
|
||||
@@ -18,7 +20,7 @@ DEFAULT_CONFIG_PATHS = (
|
||||
|
||||
WEBSERVER_KINDS = ("nginx", "caddy", "traefik")
|
||||
WEBSERVER_MODES = ("local", "ssh")
|
||||
TLS_MODES = ("none", "files", "certbot")
|
||||
TLS_MODES = ("none", "files", "certbot", "letsencrypt")
|
||||
IP_PREFERENCES = ("auto", "ipv4", "ipv6")
|
||||
|
||||
# Web server defaults live here so `config.example.toml` and the docs stay honest.
|
||||
@@ -52,6 +54,23 @@ class GeneralConfig:
|
||||
default_port: int = 80
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DnsConfig:
|
||||
"""What the public DNS record points at.
|
||||
|
||||
guest - the guest's own address (useful when guests hold public IPs)
|
||||
host - the Proxmox host's public address, which runs the reverse proxy
|
||||
fixed - the literal address in dns.address
|
||||
"""
|
||||
|
||||
target: str = "host" # guest | host | fixed
|
||||
address: str = ""
|
||||
hostname: str = ""
|
||||
detect_url_v4: str = "https://ipv4.icanhazip.com"
|
||||
detect_url_v6: str = "https://ipv6.icanhazip.com"
|
||||
detect_timeout: float = 5.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProxmoxConfig:
|
||||
api_url: str
|
||||
@@ -70,13 +89,11 @@ class ProxmoxConfig:
|
||||
|
||||
def resolve_secret(self) -> str:
|
||||
if self.token_secret_env:
|
||||
value = os.environ.get(self.token_secret_env, "")
|
||||
if not value:
|
||||
raise ConfigError(
|
||||
f"environment variable {self.token_secret_env} "
|
||||
"(proxmox.token_secret_env) is empty or unset"
|
||||
)
|
||||
return value
|
||||
return _env_secret(
|
||||
self.token_secret_env,
|
||||
setting="proxmox.token_secret_env",
|
||||
alternative="proxmox.token_secret",
|
||||
)
|
||||
if self.token_secret_file:
|
||||
path = Path(self.token_secret_file).expanduser()
|
||||
try:
|
||||
@@ -108,13 +125,11 @@ class CloudflareConfig:
|
||||
|
||||
def resolve_token(self) -> str:
|
||||
if self.api_token_env:
|
||||
value = os.environ.get(self.api_token_env, "")
|
||||
if not value:
|
||||
raise ConfigError(
|
||||
f"environment variable {self.api_token_env} "
|
||||
"(cloudflare.api_token_env) is empty or unset"
|
||||
)
|
||||
return value
|
||||
return _env_secret(
|
||||
self.api_token_env,
|
||||
setting="cloudflare.api_token_env",
|
||||
alternative="cloudflare.api_token",
|
||||
)
|
||||
if self.api_token_file:
|
||||
path = Path(self.api_token_file).expanduser()
|
||||
try:
|
||||
@@ -136,13 +151,17 @@ class CloudflareConfig:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TlsConfig:
|
||||
mode: str = "none" # none | files | certbot
|
||||
mode: str = "none" # none | files | certbot | letsencrypt
|
||||
cert_dir: str = "/etc/letsencrypt/live"
|
||||
webroot: str = "/var/www/certbot"
|
||||
certbot_command: tuple[str, ...] = (
|
||||
"certbot", "certonly", "--webroot", "-w", "/var/www/certbot", "-n", "--agree-tos",
|
||||
)
|
||||
email: str = ""
|
||||
# Alternative ACME directory (staging, Pebble, ...). Empty = Let's Encrypt production.
|
||||
acme_ca: str = ""
|
||||
# Command run after each renewal; empty = the web server's reload command.
|
||||
renew_hook: str = ""
|
||||
extra_args: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@@ -195,6 +214,7 @@ class Config:
|
||||
proxmox: ProxmoxConfig
|
||||
cloudflare: CloudflareConfig
|
||||
webserver: WebServerConfig
|
||||
dns: DnsConfig = DnsConfig()
|
||||
watch: WatchConfig = WatchConfig()
|
||||
state: StateConfig = StateConfig()
|
||||
source: Path | None = None
|
||||
@@ -245,6 +265,7 @@ def parse_config(raw: Mapping[str, Any], *, source: Path | None = None) -> Confi
|
||||
watch_raw = _table(raw, "watch")
|
||||
state_raw = _table(raw, "state")
|
||||
tls_raw = _table(webserver_raw, "tls", prefix="webserver")
|
||||
dns_raw = _table(raw, "dns")
|
||||
|
||||
general = GeneralConfig(
|
||||
base_domain=_str(general_raw, "base_domain", required=True, prefix="general"),
|
||||
@@ -320,10 +341,16 @@ def parse_config(raw: Mapping[str, Any], *, source: Path | None = None) -> Confi
|
||||
certbot_command=_str_tuple(tls_raw, "certbot_command", prefix="webserver.tls")
|
||||
or TlsConfig.certbot_command,
|
||||
email=_str(tls_raw, "email", "", prefix="webserver.tls"),
|
||||
acme_ca=_str(tls_raw, "acme_ca", "", prefix="webserver.tls"),
|
||||
renew_hook=_str(tls_raw, "renew_hook", "", prefix="webserver.tls"),
|
||||
extra_args=_str_tuple(tls_raw, "extra_args", prefix="webserver.tls"),
|
||||
)
|
||||
if tls.mode == "certbot" and not tls.email:
|
||||
raise ConfigError("webserver.tls.email is required when tls.mode = 'certbot'")
|
||||
if tls.mode in ("certbot", "letsencrypt") and not tls.email:
|
||||
raise ConfigError(
|
||||
"webserver.tls.email is required when tls.mode is 'certbot' or 'letsencrypt'"
|
||||
)
|
||||
if tls.acme_ca and not tls.acme_ca.startswith(("http://", "https://")):
|
||||
raise ConfigError("webserver.tls.acme_ca must start with https://")
|
||||
|
||||
webserver = WebServerConfig(
|
||||
kind=kind,
|
||||
@@ -346,19 +373,45 @@ def parse_config(raw: Mapping[str, Any], *, source: Path | None = None) -> Confi
|
||||
if kind != "nginx" and tls.mode == "certbot":
|
||||
raise ConfigError(
|
||||
"webserver.tls.mode = 'certbot' is only supported with kind = 'nginx'; "
|
||||
"use 'none' (Caddy manages certificates itself) or 'files'"
|
||||
"use 'letsencrypt' (automatic for Caddy/Traefik) or 'files'"
|
||||
)
|
||||
if kind == "traefik" and tls.mode == "files":
|
||||
raise ConfigError(
|
||||
"webserver.tls.mode = 'files' is not supported with kind = 'traefik'; "
|
||||
"set webserver.cert_resolver instead"
|
||||
)
|
||||
if kind == "traefik" and tls.mode == "letsencrypt" and not webserver.cert_resolver:
|
||||
raise ConfigError(
|
||||
"webserver.cert_resolver is required when kind = 'traefik' and "
|
||||
"tls.mode = 'letsencrypt'"
|
||||
)
|
||||
|
||||
state = StateConfig(
|
||||
path=_str(state_raw, "path", StateConfig.path, prefix="state"),
|
||||
audit_path=_str(state_raw, "audit_path", "", prefix="state"),
|
||||
lock_timeout=_float(state_raw, "lock_timeout", 10.0, prefix="state"),
|
||||
)
|
||||
|
||||
dns = DnsConfig(
|
||||
target=_choice(dns_raw, "target", "host", ("guest", "host", "fixed"), prefix="dns"),
|
||||
address=_str(dns_raw, "address", "", prefix="dns"),
|
||||
hostname=_str(dns_raw, "hostname", "", prefix="dns"),
|
||||
detect_url_v4=_str(dns_raw, "detect_url_v4", DnsConfig.detect_url_v4, prefix="dns"),
|
||||
detect_url_v6=_str(dns_raw, "detect_url_v6", DnsConfig.detect_url_v6, prefix="dns"),
|
||||
detect_timeout=_float(dns_raw, "detect_timeout", 5.0, prefix="dns"),
|
||||
)
|
||||
if dns.address:
|
||||
try:
|
||||
ipaddress.ip_address(dns.address)
|
||||
except ValueError as exc:
|
||||
raise ConfigError(f"dns.address is not a valid IP address: {dns.address!r}") from exc
|
||||
if dns.target == "fixed" and not dns.address:
|
||||
raise ConfigError("dns.address is required when dns.target = 'fixed'")
|
||||
if dns.detect_timeout <= 0:
|
||||
raise ConfigError("dns.detect_timeout must be greater than zero")
|
||||
for key, value in (("detect_url_v4", dns.detect_url_v4), ("detect_url_v6", dns.detect_url_v6)):
|
||||
if value and not value.startswith(("http://", "https://")):
|
||||
raise ConfigError(f"dns.{key} must start with http:// or https://")
|
||||
watch = WatchConfig(
|
||||
enabled=_bool(watch_raw, "enabled", False, prefix="watch"),
|
||||
interval=max(5, _int(watch_raw, "interval", 60, prefix="watch")),
|
||||
@@ -372,6 +425,7 @@ def parse_config(raw: Mapping[str, Any], *, source: Path | None = None) -> Confi
|
||||
proxmox=proxmox,
|
||||
cloudflare=cloudflare,
|
||||
webserver=webserver,
|
||||
dns=dns,
|
||||
watch=watch,
|
||||
state=state,
|
||||
source=source,
|
||||
@@ -386,6 +440,35 @@ def with_overrides(config: Config, **overrides: Any) -> Config:
|
||||
# ---------------------------------------------------------------------------
|
||||
# helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
_ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
||||
_UUID_RE = re.compile(
|
||||
r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
|
||||
)
|
||||
|
||||
|
||||
def _env_secret(name: str, *, setting: str, alternative: str) -> str:
|
||||
"""Read a secret from the environment variable named by a config setting."""
|
||||
name = name.strip()
|
||||
if not _ENV_NAME_RE.match(name):
|
||||
hint = ""
|
||||
if _UUID_RE.match(name):
|
||||
hint = (
|
||||
"; this looks like the token value itself — put the secret in "
|
||||
f"{alternative} (or a *_file setting) and set {setting} to the "
|
||||
"variable NAME, for example PROXDOMAIN_PVE_TOKEN"
|
||||
)
|
||||
raise ConfigError(
|
||||
f"{setting} must be the name of an environment variable, not {name!r}{hint}"
|
||||
)
|
||||
value = os.environ.get(name, "")
|
||||
if not value:
|
||||
raise ConfigError(
|
||||
f"{setting} points at environment variable {name}, which is empty or "
|
||||
f"unset; export {name} before running proxdomain"
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def _table(raw: Mapping[str, Any], key: str, *, prefix: str = "") -> Mapping[str, Any]:
|
||||
value = raw.get(key, {})
|
||||
if not isinstance(value, Mapping):
|
||||
|
||||
+299
-41
@@ -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(
|
||||
|
||||
@@ -28,7 +28,9 @@ class Assignment:
|
||||
kind: str
|
||||
name: str = ""
|
||||
ip: str = ""
|
||||
dns_ip: str = ""
|
||||
port: int = 80
|
||||
tls: str = "none"
|
||||
webserver: str = ""
|
||||
zone_id: str = ""
|
||||
zone_name: str = ""
|
||||
@@ -55,7 +57,9 @@ class Assignment:
|
||||
kind=kind,
|
||||
name=str(payload.get("name") or ""),
|
||||
ip=str(payload.get("ip") or ""),
|
||||
dns_ip=str(payload.get("dns_ip") or ""),
|
||||
port=int(payload.get("port") or 80),
|
||||
tls=str(payload.get("tls") or "none"),
|
||||
webserver=str(payload.get("webserver") or ""),
|
||||
zone_id=str(payload.get("zone_id") or ""),
|
||||
zone_name=str(payload.get("zone_name") or ""),
|
||||
|
||||
+88
-4
@@ -20,6 +20,12 @@ FQDN_RE = re.compile(
|
||||
|
||||
_EXTENSIONS = {"nginx": ".conf", "caddy": ".caddy", "traefik": ".yml"}
|
||||
|
||||
# Let's Encrypt production directory; overridable through webserver.tls.acme_ca.
|
||||
LETSENCRYPT_DIRECTORY = "https://acme-v02.api.letsencrypt.org/directory"
|
||||
|
||||
# Modes where proxdomain itself obtains a certificate (nginx + certbot).
|
||||
CERTBOT_MODES = ("certbot", "letsencrypt")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SiteSpec:
|
||||
@@ -34,6 +40,9 @@ class SiteSpec:
|
||||
cert_dir: str = "/etc/letsencrypt/live"
|
||||
webroot: str = "/var/www/certbot"
|
||||
cert_resolver: str = ""
|
||||
tls_email: str = ""
|
||||
acme_ca: str = ""
|
||||
renew_hook: str = ""
|
||||
upstream_scheme: str = "http"
|
||||
|
||||
@property
|
||||
@@ -63,6 +72,41 @@ class WebServerManager:
|
||||
self.config = config
|
||||
self.runner = runner
|
||||
|
||||
# -- TLS -------------------------------------------------------------
|
||||
@property
|
||||
def tls_mode(self) -> str:
|
||||
return self.config.tls.mode
|
||||
|
||||
@property
|
||||
def issues_certificates(self) -> bool:
|
||||
"""True when proxdomain runs certbot itself (nginx only)."""
|
||||
return self.config.kind == "nginx" and self.tls_mode in CERTBOT_MODES
|
||||
|
||||
@property
|
||||
def renew_hook(self) -> str:
|
||||
"""Command certbot runs after a renewal, so the server picks up the new cert."""
|
||||
return self.config.tls.renew_hook or " ".join(self.config.reload_command)
|
||||
|
||||
def certificate_present(self, spec: SiteSpec) -> bool:
|
||||
return self.runner.exists(spec.certificate)
|
||||
|
||||
def certificate_expiry(self, spec: SiteSpec) -> str:
|
||||
"""Return the notAfter date of an existing certificate, or ''."""
|
||||
if not self.certificate_present(spec):
|
||||
return ""
|
||||
try:
|
||||
result = self.runner.run(
|
||||
["openssl", "x509", "-noout", "-enddate", "-in", spec.certificate]
|
||||
)
|
||||
except ProxdomainError:
|
||||
return ""
|
||||
if not result.ok:
|
||||
return ""
|
||||
for line in result.stdout.splitlines():
|
||||
if line.startswith("notAfter="):
|
||||
return line.split("=", 1)[1].strip()
|
||||
return ""
|
||||
|
||||
# -- rendering ------------------------------------------------------
|
||||
def render(self, spec: SiteSpec) -> str:
|
||||
if spec.webserver == "nginx":
|
||||
@@ -102,11 +146,12 @@ class WebServerManager:
|
||||
original = self.runner.read_text(path)
|
||||
|
||||
bootstrapped = False
|
||||
if spec.tls_mode == "certbot" and not self.runner.exists(spec.certificate):
|
||||
if self.issues_certificates and not self.certificate_present(spec):
|
||||
try:
|
||||
self._serve_challenge(spec, path, result)
|
||||
self._request_certificate(spec, result)
|
||||
except WebServerError:
|
||||
except ProxdomainError:
|
||||
# Do not leave the temporary HTTP vhost behind.
|
||||
if original is None:
|
||||
self.runner.remove(path)
|
||||
else:
|
||||
@@ -187,6 +232,7 @@ class WebServerManager:
|
||||
|
||||
def _serve_challenge(self, spec: SiteSpec, path: str, result: ApplyResult) -> None:
|
||||
"""Activate an HTTP-only vhost so certbot's webroot plugin can answer."""
|
||||
self.runner.mkdir(self.config.tls.webroot)
|
||||
self.runner.write_text(path, render_nginx_challenge(spec))
|
||||
try:
|
||||
self.validate()
|
||||
@@ -200,14 +246,26 @@ class WebServerManager:
|
||||
|
||||
def _request_certificate(self, spec: SiteSpec, result: ApplyResult) -> None:
|
||||
command = list(self.config.tls.certbot_command) + [
|
||||
"--keep-until-expiring",
|
||||
"-d",
|
||||
spec.fqdn,
|
||||
"--email",
|
||||
self.config.tls.email,
|
||||
]
|
||||
if self.config.tls.acme_ca:
|
||||
command += ["--server", self.config.tls.acme_ca]
|
||||
if self.renew_hook:
|
||||
command += ["--deploy-hook", self.renew_hook]
|
||||
command.extend(self.config.tls.extra_args)
|
||||
result.messages.append(f"requesting a certificate for {spec.fqdn}")
|
||||
completed = self.runner.run(command)
|
||||
try:
|
||||
completed = self.runner.run(command)
|
||||
except ProxdomainError as exc:
|
||||
raise WebServerError(
|
||||
f"cannot run certbot for {spec.fqdn}: {exc}\n"
|
||||
"install it (apt install certbot) or set "
|
||||
"webserver.tls.certbot_command to its full path"
|
||||
) from exc
|
||||
if not completed.ok:
|
||||
raise WebServerError(
|
||||
f"certbot failed for {spec.fqdn}:\n{completed.output()}\n"
|
||||
@@ -244,13 +302,29 @@ class WebServerManager:
|
||||
)
|
||||
)
|
||||
|
||||
if self.config.tls.mode == "certbot":
|
||||
if self.issues_certificates:
|
||||
webroot = self.config.tls.webroot
|
||||
if dry_run:
|
||||
steps.append(("planned", f"create ACME webroot {webroot}"))
|
||||
else:
|
||||
self.runner.mkdir(webroot)
|
||||
steps.append(("ok", f"ACME webroot {webroot} is ready"))
|
||||
if self.tls_mode == "letsencrypt" and self.config.kind in ("caddy", "traefik"):
|
||||
steps.append(
|
||||
(
|
||||
"ok",
|
||||
f"{self.config.kind} obtains and renews Let's Encrypt certificates "
|
||||
"for every managed site",
|
||||
)
|
||||
)
|
||||
if self.tls_mode == "letsencrypt" and self.config.kind == "nginx":
|
||||
steps.append(
|
||||
(
|
||||
"next",
|
||||
"certbot's systemd timer renews certificates; verify with "
|
||||
"'systemctl list-timers | grep certbot'",
|
||||
)
|
||||
)
|
||||
return steps
|
||||
|
||||
def _bootstrap_nginx(self, manage_dir: str, dry_run: bool) -> list[tuple[str, str]]:
|
||||
@@ -411,6 +485,16 @@ def render_caddy(spec: SiteSpec) -> str:
|
||||
]
|
||||
if spec.tls_mode == "files":
|
||||
lines.append(f"\ttls {spec.certificate} {spec.private_key}")
|
||||
elif spec.tls_mode == "letsencrypt":
|
||||
# Pin the issuer: without this Caddy may fall back to ZeroSSL.
|
||||
lines.append("\ttls {")
|
||||
lines.append("\t\tissuer acme {")
|
||||
if spec.tls_email:
|
||||
lines.append(f"\t\t\temail {spec.tls_email}")
|
||||
if spec.acme_ca:
|
||||
lines.append(f"\t\t\tdir {spec.acme_ca}")
|
||||
lines.append("\t\t}")
|
||||
lines.append("\t}")
|
||||
lines.append(f"\treverse_proxy {spec.target}")
|
||||
lines.append("}")
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
Reference in new issue
Block a user