first commit
This commit is contained in:
commit
dd50a0d05e
31 files changed
+5299
No files matched your search
Executable
+462
@@ -0,0 +1,462 @@
|
||||
"""Reverse-proxy configuration generation and safe activation.
|
||||
|
||||
Supports nginx (config file + `nginx -t` + reload), Caddy (snippet + validate +
|
||||
reload) and Traefik (dynamic file provider, reloaded automatically).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import posixpath
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from .config import WebServerConfig
|
||||
from .errors import ProxdomainError, WebServerError
|
||||
from .runner import Runner
|
||||
|
||||
FQDN_RE = re.compile(
|
||||
r"^(?=.{1,253}$)(?!-)[a-z0-9-]{1,63}(?<!-)(\.(?!-)[a-z0-9-]{1,63}(?<!-))+$"
|
||||
)
|
||||
|
||||
_EXTENSIONS = {"nginx": ".conf", "caddy": ".caddy", "traefik": ".yml"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SiteSpec:
|
||||
fqdn: str
|
||||
address: str
|
||||
port: int
|
||||
vmid: int
|
||||
node: str
|
||||
kind: str # qemu | lxc
|
||||
webserver: str
|
||||
tls_mode: str = "none"
|
||||
cert_dir: str = "/etc/letsencrypt/live"
|
||||
webroot: str = "/var/www/certbot"
|
||||
cert_resolver: str = ""
|
||||
upstream_scheme: str = "http"
|
||||
|
||||
@property
|
||||
def target(self) -> str:
|
||||
return f"{self.upstream_scheme}://{self.address}:{self.port}"
|
||||
|
||||
@property
|
||||
def certificate(self) -> str:
|
||||
return posixpath.join(self.cert_dir, self.fqdn, "fullchain.pem")
|
||||
|
||||
@property
|
||||
def private_key(self) -> str:
|
||||
return posixpath.join(self.cert_dir, self.fqdn, "privkey.pem")
|
||||
|
||||
|
||||
@dataclass
|
||||
class ApplyResult:
|
||||
path: str
|
||||
changed: bool = False
|
||||
validated: bool = False
|
||||
reloaded: bool = False
|
||||
messages: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
class WebServerManager:
|
||||
def __init__(self, config: WebServerConfig, runner: Runner) -> None:
|
||||
self.config = config
|
||||
self.runner = runner
|
||||
|
||||
# -- rendering ------------------------------------------------------
|
||||
def render(self, spec: SiteSpec) -> str:
|
||||
if spec.webserver == "nginx":
|
||||
return render_nginx(spec)
|
||||
if spec.webserver == "caddy":
|
||||
return render_caddy(spec)
|
||||
if spec.webserver == "traefik":
|
||||
return render_traefik(spec)
|
||||
raise WebServerError(f"unsupported web server: {spec.webserver!r}")
|
||||
|
||||
def site_path(self, fqdn: str) -> str:
|
||||
if not FQDN_RE.match(fqdn):
|
||||
raise WebServerError(f"refusing to use {fqdn!r} as a config file name")
|
||||
extension = _EXTENSIONS.get(self.config.kind)
|
||||
if extension is None:
|
||||
raise WebServerError(f"unsupported web server: {self.config.kind!r}")
|
||||
return f"{self.config.manage_dir}/{fqdn}{extension}"
|
||||
|
||||
# -- lifecycle ------------------------------------------------------
|
||||
def apply(self, spec: SiteSpec, *, dry_run: bool = False) -> ApplyResult:
|
||||
if spec.webserver != self.config.kind:
|
||||
raise WebServerError(
|
||||
f"site spec is for {spec.webserver}, manager is configured for {self.config.kind}"
|
||||
)
|
||||
content = self.render(spec)
|
||||
path = self.site_path(spec.fqdn)
|
||||
result = ApplyResult(path=path)
|
||||
|
||||
if dry_run:
|
||||
result.changed = self.runner.read_text(path) != content
|
||||
result.messages.append(
|
||||
("would write " if result.changed else "would keep ") + path
|
||||
)
|
||||
return result
|
||||
|
||||
self.runner.mkdir(self.config.manage_dir)
|
||||
original = self.runner.read_text(path)
|
||||
|
||||
bootstrapped = False
|
||||
if spec.tls_mode == "certbot" and not self.runner.exists(spec.certificate):
|
||||
try:
|
||||
self._serve_challenge(spec, path, result)
|
||||
self._request_certificate(spec, result)
|
||||
except WebServerError:
|
||||
if original is None:
|
||||
self.runner.remove(path)
|
||||
else:
|
||||
self.runner.write_text(path, original)
|
||||
raise
|
||||
bootstrapped = True
|
||||
|
||||
result.changed = self.runner.write_text(path, content) or bootstrapped
|
||||
if not result.changed:
|
||||
result.messages.append("config already up to date")
|
||||
return result
|
||||
result.messages.append(
|
||||
("updated " if original is not None else "created ") + path
|
||||
)
|
||||
|
||||
try:
|
||||
result.validated = self.validate()
|
||||
except WebServerError as exc:
|
||||
# Never leave a broken config on disk for the next reload to pick up.
|
||||
if original is None:
|
||||
self.runner.remove(path)
|
||||
else:
|
||||
self.runner.write_text(path, original)
|
||||
raise WebServerError(
|
||||
f"{exc}\nrolled back {path} to its previous content"
|
||||
) from exc
|
||||
|
||||
if self.config.reload_command:
|
||||
result.reloaded = self._reload()
|
||||
return result
|
||||
|
||||
def remove(self, fqdn: str, *, dry_run: bool = False) -> ApplyResult:
|
||||
path = self.site_path(fqdn)
|
||||
result = ApplyResult(path=path)
|
||||
if not self.runner.exists(path):
|
||||
result.messages.append("no config file present")
|
||||
return result
|
||||
if dry_run:
|
||||
result.changed = True
|
||||
result.messages.append(f"would remove {path}")
|
||||
return result
|
||||
|
||||
previous = self.runner.read_text(path)
|
||||
result.changed = self.runner.remove(path)
|
||||
result.messages.append(f"removed {path}")
|
||||
try:
|
||||
result.validated = self.validate()
|
||||
except WebServerError as exc:
|
||||
if previous is not None:
|
||||
self.runner.write_text(path, previous)
|
||||
raise WebServerError(
|
||||
f"{exc}\nrestored {path} after the removal broke validation"
|
||||
) from exc
|
||||
if self.config.reload_command:
|
||||
result.reloaded = self._reload()
|
||||
return result
|
||||
|
||||
def validate(self) -> bool:
|
||||
if not self.config.test_command:
|
||||
return False
|
||||
result = self.runner.run(self.config.test_command)
|
||||
if not result.ok:
|
||||
raise WebServerError(
|
||||
"web server configuration test failed "
|
||||
f"({' '.join(self.config.test_command)}):\n{result.output()}"
|
||||
)
|
||||
return True
|
||||
|
||||
def _reload(self) -> bool:
|
||||
result = self.runner.run(self.config.reload_command)
|
||||
if not result.ok:
|
||||
raise WebServerError(
|
||||
"configuration is valid and written, but reloading the web server "
|
||||
f"failed ({' '.join(self.config.reload_command)}):\n{result.output()}\n"
|
||||
"run the reload command manually; the config is already in place"
|
||||
)
|
||||
return True
|
||||
|
||||
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.write_text(path, render_nginx_challenge(spec))
|
||||
try:
|
||||
self.validate()
|
||||
except WebServerError as exc:
|
||||
raise WebServerError(
|
||||
f"cannot activate the temporary ACME vhost for {spec.fqdn}:\n{exc}"
|
||||
) from exc
|
||||
if self.config.reload_command:
|
||||
self._reload()
|
||||
result.messages.append("served the ACME challenge on port 80")
|
||||
|
||||
def _request_certificate(self, spec: SiteSpec, result: ApplyResult) -> None:
|
||||
command = list(self.config.tls.certbot_command) + [
|
||||
"-d",
|
||||
spec.fqdn,
|
||||
"--email",
|
||||
self.config.tls.email,
|
||||
]
|
||||
command.extend(self.config.tls.extra_args)
|
||||
result.messages.append(f"requesting a certificate for {spec.fqdn}")
|
||||
completed = self.runner.run(command)
|
||||
if not completed.ok:
|
||||
raise WebServerError(
|
||||
f"certbot failed for {spec.fqdn}:\n{completed.output()}\n"
|
||||
"the domain must already resolve to this host and port 80 must be "
|
||||
"reachable from the internet (set the Cloudflare record to grey cloud "
|
||||
"until the certificate is issued)"
|
||||
)
|
||||
result.messages.append(f"issued a certificate for {spec.fqdn}")
|
||||
|
||||
# -- one-time bootstrap --------------------------------------------
|
||||
def bootstrap(self, *, dry_run: bool = False) -> list[tuple[str, str]]:
|
||||
"""Create the managed directory and the include needed by the web server."""
|
||||
steps: list[tuple[str, str]] = []
|
||||
kind = self.config.kind
|
||||
manage_dir = self.config.manage_dir
|
||||
|
||||
if dry_run:
|
||||
steps.append(("planned", f"create directory {manage_dir}"))
|
||||
else:
|
||||
self.runner.mkdir(manage_dir)
|
||||
steps.append(("ok", f"directory {manage_dir} is ready"))
|
||||
|
||||
if kind == "nginx":
|
||||
steps.extend(self._bootstrap_nginx(manage_dir, dry_run))
|
||||
elif kind == "caddy":
|
||||
steps.extend(self._bootstrap_caddy(manage_dir, dry_run))
|
||||
else:
|
||||
steps.append(
|
||||
(
|
||||
"note",
|
||||
"Traefik's file provider only watches directories that are already "
|
||||
"configured in its static config; make sure "
|
||||
f"{manage_dir} is one of them",
|
||||
)
|
||||
)
|
||||
|
||||
if self.config.tls.mode == "certbot":
|
||||
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"))
|
||||
return steps
|
||||
|
||||
def _bootstrap_nginx(self, manage_dir: str, dry_run: bool) -> list[tuple[str, str]]:
|
||||
parent = posixpath.dirname(manage_dir.rstrip("/"))
|
||||
include_file = f"{manage_dir}.conf"
|
||||
if posixpath.basename(parent) != "conf.d":
|
||||
return [
|
||||
(
|
||||
"note",
|
||||
f"{manage_dir} is not inside an nginx conf.d directory; add "
|
||||
f"'include {manage_dir}/*.conf;' to the http{{}} block manually",
|
||||
)
|
||||
]
|
||||
|
||||
include_line = f"include {manage_dir}/*.conf;"
|
||||
if _directory_has_include(self.runner, parent, include_line):
|
||||
return [("ok", f"nginx already includes {manage_dir}/*.conf")]
|
||||
|
||||
content = (
|
||||
"# Managed by proxdomain: pulls in generated virtual hosts.\n"
|
||||
f"{include_line}\n"
|
||||
)
|
||||
if dry_run:
|
||||
return [("planned", f"write {include_file} with '{include_line}'")]
|
||||
self.runner.write_text(include_file, content)
|
||||
return [
|
||||
("ok", f"wrote {include_file} with '{include_line}'"),
|
||||
("next", "run: nginx -t && systemctl reload nginx"),
|
||||
]
|
||||
|
||||
def _bootstrap_caddy(self, manage_dir: str, dry_run: bool) -> list[tuple[str, str]]:
|
||||
caddyfile = "/etc/caddy/Caddyfile"
|
||||
import_line = f"import {manage_dir}/*.caddy"
|
||||
current = self.runner.read_text(caddyfile)
|
||||
if current is None:
|
||||
return [
|
||||
(
|
||||
"note",
|
||||
f"{caddyfile} not found; add '{import_line}' to your Caddyfile manually",
|
||||
)
|
||||
]
|
||||
if import_line in current:
|
||||
return [("ok", f"Caddyfile already imports {manage_dir}/*.caddy")]
|
||||
updated = current.rstrip("\n") + f"\n\n# proxdomain managed sites\n{import_line}\n"
|
||||
if dry_run:
|
||||
return [("planned", f"append '{import_line}' to {caddyfile}")]
|
||||
self.runner.write_text(caddyfile, updated)
|
||||
return [
|
||||
("ok", f"appended '{import_line}' to {caddyfile}"),
|
||||
("next", "run: caddy validate --config /etc/caddy/Caddyfile && systemctl reload caddy"),
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# renderers
|
||||
# ---------------------------------------------------------------------------
|
||||
def render_nginx(spec: SiteSpec) -> str:
|
||||
header = [
|
||||
"# Managed by proxdomain. Manual edits are overwritten on the next sync.",
|
||||
f"# {spec.fqdn} -> {spec.target} ({spec.kind} {spec.vmid} on {spec.node})",
|
||||
"",
|
||||
]
|
||||
if spec.tls_mode == "none":
|
||||
body = [
|
||||
"server {",
|
||||
" listen 80;",
|
||||
" listen [::]:80;",
|
||||
f" server_name {spec.fqdn};",
|
||||
"",
|
||||
_nginx_proxy(spec, indent=" "),
|
||||
"}",
|
||||
]
|
||||
return "\n".join(header + body) + "\n"
|
||||
|
||||
body = [
|
||||
"server {",
|
||||
" listen 80;",
|
||||
" listen [::]:80;",
|
||||
f" server_name {spec.fqdn};",
|
||||
"",
|
||||
" location /.well-known/acme-challenge/ {",
|
||||
f" root {spec.webroot};",
|
||||
" }",
|
||||
"",
|
||||
" location / {",
|
||||
" return 301 https://$host$request_uri;",
|
||||
" }",
|
||||
"}",
|
||||
"",
|
||||
"server {",
|
||||
" listen 443 ssl;",
|
||||
" listen [::]:443 ssl;",
|
||||
f" server_name {spec.fqdn};",
|
||||
"",
|
||||
f" ssl_certificate {spec.certificate};",
|
||||
f" ssl_certificate_key {spec.private_key};",
|
||||
" ssl_protocols TLSv1.2 TLSv1.3;",
|
||||
" ssl_session_cache shared:SSL:10m;",
|
||||
" ssl_session_timeout 1h;",
|
||||
"",
|
||||
_nginx_proxy(spec, indent=" "),
|
||||
"}",
|
||||
]
|
||||
return "\n".join(header + body) + "\n"
|
||||
|
||||
|
||||
def render_nginx_challenge(spec: SiteSpec) -> str:
|
||||
"""HTTP-only vhost used while waiting for the first certificate."""
|
||||
header = [
|
||||
"# Managed by proxdomain: temporary HTTP vhost used to answer the ACME challenge.",
|
||||
"# Replaced by the TLS vhost as soon as the certificate exists.",
|
||||
f"# {spec.fqdn} -> {spec.target} ({spec.kind} {spec.vmid} on {spec.node})",
|
||||
"",
|
||||
]
|
||||
body = [
|
||||
"server {",
|
||||
" listen 80;",
|
||||
" listen [::]:80;",
|
||||
f" server_name {spec.fqdn};",
|
||||
"",
|
||||
" location /.well-known/acme-challenge/ {",
|
||||
f" root {spec.webroot};",
|
||||
" }",
|
||||
"",
|
||||
_nginx_proxy(spec, indent=" "),
|
||||
"}",
|
||||
]
|
||||
return "\n".join(header + body) + "\n"
|
||||
|
||||
|
||||
def _nginx_proxy(spec: SiteSpec, *, indent: str) -> str:
|
||||
inner = indent + " "
|
||||
lines = [
|
||||
f"{indent}location / {{",
|
||||
f"{inner}proxy_pass {spec.target};",
|
||||
f"{inner}proxy_http_version 1.1;",
|
||||
f"{inner}proxy_set_header Host $host;",
|
||||
f"{inner}proxy_set_header X-Real-IP $remote_addr;",
|
||||
f"{inner}proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;",
|
||||
f"{inner}proxy_set_header X-Forwarded-Proto $scheme;",
|
||||
# $http_connection forwards "Upgrade" for WebSocket and "keep-alive" otherwise,
|
||||
# so no shared map{} entry is required in the http{} block.
|
||||
f"{inner}proxy_set_header Upgrade $http_upgrade;",
|
||||
f"{inner}proxy_set_header Connection $http_connection;",
|
||||
f"{inner}proxy_read_timeout 3600s;",
|
||||
f"{indent}}}",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def render_caddy(spec: SiteSpec) -> str:
|
||||
lines = [
|
||||
"# Managed by proxdomain. Manual edits are overwritten on the next sync.",
|
||||
f"# {spec.fqdn} -> {spec.target} ({spec.kind} {spec.vmid} on {spec.node})",
|
||||
"",
|
||||
f"{spec.fqdn} {{",
|
||||
"\tencode gzip",
|
||||
]
|
||||
if spec.tls_mode == "files":
|
||||
lines.append(f"\ttls {spec.certificate} {spec.private_key}")
|
||||
lines.append(f"\treverse_proxy {spec.target}")
|
||||
lines.append("}")
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def render_traefik(spec: SiteSpec) -> str:
|
||||
key = "proxdomain-" + re.sub(r"[^a-z0-9]+", "-", spec.fqdn).strip("-")
|
||||
lines = [
|
||||
"# Managed by proxdomain. Manual edits are overwritten on the next sync.",
|
||||
f"# {spec.fqdn} -> {spec.target} ({spec.kind} {spec.vmid} on {spec.node})",
|
||||
"http:",
|
||||
" routers:",
|
||||
f" {key}:",
|
||||
" entryPoints:",
|
||||
" - websecure",
|
||||
f" rule: \"Host(`{spec.fqdn}`)\"",
|
||||
f" service: {key}",
|
||||
]
|
||||
if spec.cert_resolver:
|
||||
lines += [" tls:", f" certResolver: {spec.cert_resolver}"]
|
||||
else:
|
||||
lines += [" tls: {}"]
|
||||
lines += [
|
||||
" services:",
|
||||
f" {key}:",
|
||||
" loadBalancer:",
|
||||
" servers:",
|
||||
f" - url: \"{spec.target}\"",
|
||||
]
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def _directory_has_include(runner: Runner, directory: str, include_line: str) -> bool:
|
||||
"""Check whether any *.conf directly in `directory` already contains the include."""
|
||||
if not runner.exists(directory):
|
||||
return False
|
||||
try:
|
||||
result = runner.run(
|
||||
[
|
||||
"grep",
|
||||
"-RFl",
|
||||
"--include=*.conf",
|
||||
include_line,
|
||||
directory,
|
||||
]
|
||||
)
|
||||
except ProxdomainError:
|
||||
return False
|
||||
return result.ok
|
||||
Reference in new issue
Block a user