commit dd50a0d05ef93c258aa81f0b86fb0835e24a4577 Author: leo Date: Fri Nov 20 15:16:41 2026 +0200 first commit diff --git a/.gitignore b/.gitignore new file mode 100755 index 0000000..28073d3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +__pycache__/ +*.py[cod] +*.egg-info/ +build/ +dist/ +.venv/ +venv/ + +# local configuration and runtime state +proxdomain.toml +*.token +state.json +audit.jsonl diff --git a/LICENSE b/LICENSE new file mode 100755 index 0000000..98746d8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 proxdomain contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100755 index 0000000..2cea576 --- /dev/null +++ b/README.md @@ -0,0 +1,306 @@ +# proxdomain + +Give a Proxmox VM or LXC container a public domain name — automatically. + +`proxdomain` reads the guest from the Proxmox VE API, creates or updates the +Cloudflare DNS record, writes a reverse-proxy vhost on the Proxmox host, tests +the configuration, and reloads the web server. Re-running is idempotent, and a +broken config is rolled back before the reload. + +``` +$ proxdomain assign --vmid 101 +assign: ok + [ok ] guest web01 (qemu 101 on pve) + [ok ] address 10.0.0.5 (discovered) + [ok ] domain web01.example.com + [ok ] zone example.com (023e105f4ecef8ad9ca31a8372d0c353) + [ok ] web-config created /etc/nginx/conf.d/proxdomain.d/web01.example.com.conf + [warn] dns 10.0.0.5 is not a public address, so the Cloudflare proxy + (orange cloud) was disabled; only the DNS record is created + [done] dns created A web01.example.com -> 10.0.0.5 (proxied=no) + [ok ] result web01.example.com -> http://10.0.0.5:80 +``` + +## What it does + +1. **Proxmox** — finds the guest (`--vmid` or `--name`), then resolves its IP from + the QEMU guest agent, the LXC runtime interfaces, or the static `ip=` in the + guest config (in that order). +2. **Cloudflare** — discovers the zone by walking up from the FQDN, then creates + or patches the `A`/`AAAA` record. `proxied`, TTL and comment come from the + config; private/loopback targets automatically get a grey cloud. +3. **Web server** — renders one file per domain (`nginx`, `Caddy` or `Traefik` + file provider) into a managed directory, runs the config test, and reloads. + If the test fails, the previous file is restored. +4. **State** — records the assignment in `state.json` plus an append-only + `audit.jsonl`, so `list`, `sync` and `remove` know what is managed. + +The app never creates VMs and never installs a web server; it wires an existing +one to existing guests. + +## Requirements + +* Python **3.11+** (no third-party packages, no build step) +* Proxmox VE 7/8 with an API token +* A Cloudflare zone and an API token with `Zone:Read` + `DNS:Edit` +* nginx, Caddy or Traefik already installed on the Proxmox host + +Windows and macOS can drive a remote host with `webserver.mode = "ssh"`; local +mode writes to POSIX paths such as `/etc/nginx/...` and is meant for the PVE host. + +## Install + +On the Proxmox host (recommended: run locally as root via systemd): + +```bash +install -d /opt/proxdomain +# copy this repository to /opt/proxdomain, then: +python3 -m venv /opt/proxdomain/.venv +/opt/proxdomain/.venv/bin/pip install /opt/proxdomain +ln -s /opt/proxdomain/.venv/bin/proxdomain /usr/local/bin/proxdomain +``` + +Or run it straight from the checkout without installing: + +```bash +python3 -m proxdomain --help +``` + +The only runtime dependency is the Python standard library, so copying the +folder and running `python3 -m proxdomain` also works. + +## Credentials + +### Proxmox API token + +```bash +pveum role add Proxdomain -privs "VM.Audit VM.Monitor" +pveum user add automation@pve --comment "proxdomain" +pveum acl modify / --roles Proxdomain --users automation@pve +pveum user token add automation@pve proxdomain --privsep 0 +``` + +The token secret is shown once. `VM.Audit` lists guests; `VM.Monitor` is needed +for the guest-agent IP query. Put the token in the environment, not in the file: + +```bash +export PROXDOMAIN_PVE_TOKEN='00000000-0000-0000-0000-000000000000' +``` + +### Cloudflare API token + +Create a token with **Zone → Zone:Read** and **Zone → DNS:Edit**, limited to the +zone(s) you use, then: + +```bash +export PROXDOMAIN_CF_TOKEN='...' +``` + +## Configure + +```bash +cp config.example.toml /etc/proxdomain/config.toml +$EDITOR /etc/proxdomain/config.toml +``` + +Minimum edits: `general.base_domain`, `proxmox.api_url`, `proxmox.token_id`, +`webserver.manage_dir` (defaults are fine for nginx). Every setting is documented +in [`config.example.toml`](config.example.toml). + +The config is read from `--config`, then `$PROXDOMAIN_CONFIG`, then +`./proxdomain.toml`, then `/etc/proxdomain/config.toml`. + +Then create the managed directory and the include line: + +```bash +proxdomain init --dry-run # see what would change +proxdomain init +``` + +For nginx this writes `/etc/nginx/conf.d/proxdomain.d.conf` containing + +```nginx +include /etc/nginx/conf.d/proxdomain.d/*.conf; +``` + +which is picked up by the stock `include /etc/nginx/conf.d/*.conf;`, so no edit +to `nginx.conf` is needed. For Caddy it appends +`import /etc/caddy/proxdomain.d/*.caddy` to the Caddyfile once. For Traefik it +creates the directory and reminds you to register it with the file provider. + +Check everything before the first assignment: + +```bash +proxdomain doctor +``` + +## Usage + +```bash +# preview: read-only, no DNS write, no config change +proxdomain assign --vmid 101 --dry-run + +# assign using . +proxdomain assign --vmid 101 + +# pick the name and backend port explicitly +proxdomain assign --name "web01" --subdomain app --port 8080 + +# a full name under another zone the token can read +proxdomain assign --vmid 101 --subdomain app.example.net + +# guest IP discovery is wrong? override it, or force the orange cloud +proxdomain assign --vmid 101 --ip 10.0.0.5 --proxied + +# after changing template/port/TLS settings, re-apply every site +proxdomain sync --dry-run +proxdomain sync + +proxdomain list +proxdomain list --json + +proxdomain remove --fqdn web01.example.com --yes +proxdomain remove --vmid 101 --yes +``` + +`--json` on any command prints the step list as JSON, which is handy for +scripting around exit codes: + +* `0` — everything succeeded +* `1` — the action failed (DNS, web server, or lookup) +* `2` — usage or configuration error + +## Automatic assignment for new guests + +Tag a guest `proxdomain` in the Proxmox UI (or set `watch.tag`), then: + +```bash +proxdomain watch --once # list candidates only +proxdomain watch --once --auto-assign # assign them +proxdomain watch # long-running loop +``` + +`watch` only considers guests that are not already in the state file, carry the +tag, and (by default) are running. `--all-new` drops the tag filter. Nothing is +assigned unless `--auto-assign` is passed or `watch.auto_assign = true`, so a +misconfigured timer cannot silently publish guest names. + +Run it from systemd with the included units: + +```bash +cp deploy/proxdomain-watch.service deploy/proxdomain-watch.timer /etc/systemd/system/ +systemctl daemon-reload +systemctl enable --now proxdomain-watch.timer +``` + +`/etc/proxdomain/env` holds the two secrets and is read by the unit: + +```bash +install -m 600 /dev/null /etc/proxdomain/env +cat >/etc/proxdomain/env <<'EOF' +PROXDOMAIN_PVE_TOKEN=... +PROXDOMAIN_CF_TOKEN=... +EOF +``` + +Or in cron: `*/2 * * * * /usr/local/bin/proxdomain watch --once --auto-assign`. + +## TLS + +| `webserver.tls.mode` | What is written | When to use | +| --- | --- | --- | +| `none` (default) | Proxy on `:80` | Cloudflare orange cloud terminates TLS, or plain HTTP on the LAN | +| `files` | `:80` redirect + `:443` vhost with `cert_dir//{fullchain,privkey}.pem` | Certificates already exist (wildcard, acme.sh, another certbot) | +| `certbot` (nginx only) | Temporary HTTP vhost → `certbot certonly --webroot` → TLS vhost | Let the app obtain the certificate | + +For `certbot`, the domain must resolve to the host and port 80 must be reachable +from the internet. Keep the Cloudflare record grey-clouded until the certificate +is issued, otherwise Cloudflare's edge answers the challenge. Caddy manages its +own certificates, so `none`/`files` are the only meaningful modes there; for +Traefik set `webserver.cert_resolver`. + +With a proxied (orange cloud) record, Cloudflare connects to the origin on the +standard HTTP/HTTPS ports. Publish the reverse proxy on 80/443, not on an +arbitrary high port, or disable proxying for that record. + +## How an assignment is ordered + +Web config first, DNS second: the vhost is valid and loaded before the name +starts resolving, so a failure never leaves a public name pointing at an +unconfigured proxy. + +* Config test fails → the new file is removed (or the old one restored) and the + error is reported; DNS is untouched. +* Reload fails after a valid test → the config is kept (it is valid) and the + error tells you to reload manually; the next run finishes the job. +* DNS fails after the vhost is in place → the assignment is stored with no record + id, the command exits non-zero, and re-running `assign` completes it. + +`state.json` is written through a lock (`state.json.lock`) and `audit.jsonl` +records every config/DNS/remove action with a UTC timestamp. + +## Security notes + +* API tokens are read from `PROXDOMAIN_PVE_TOKEN` / `PROXDOMAIN_CF_TOKEN` or a + file, never written to the state or audit log. +* The tool edits only files inside `webserver.manage_dir` (validated FQDN file + names), plus the one-time include file created by `init`. +* Local mode runs as root on the PVE host and can reload nginx. SSH mode needs + `sudo -n` for the same commands; see [`deploy/sudoers.example`](deploy/sudoers.example) + for the caveat — a `tee` rule into `/etc` is effectively root, which is why + local mode is the recommended deployment. +* The Cloudflare proxy is disabled automatically when the target address is not + public, so a private IP is never advertised as an orange-cloud origin. + +## Troubleshooting + +| Symptom | Cause / fix | +| --- | --- | +| `no usable IP address found` | Install and start `qemu-guest-agent` in the VM, set a static `ip=` in the guest/cloud-init config, or pass `--ip`. | +| `401/403` from Proxmox | Token ACL or `--privsep`. Grant `VM.Audit VM.Monitor` on `/` (or at least `/vms`). | +| `no Cloudflare zone found` | `general.base_domain` must be inside the zone, and the token must include that zone under Zone Resources. | +| `401/403` from Cloudflare | Token needs `Zone:Read` + `DNS:Edit`; check it was not restricted to another account. | +| `web server configuration test failed` | The message includes `nginx -t` output. The file was rolled back; nothing was reloaded. | +| `reloading the web server failed` | The config is valid and written. Run the reload command from `webserver.reload_command` manually. | +| `certbot failed` | Port 80 unreachable, DNS not pointing at the host yet, or the record is orange-clouded. Use grey cloud until issuance succeeds. | +| Cloudflare 522/521 | The origin address or port is unreachable from Cloudflare. Check the guest firewall and that the proxy listens on 80/443. | +| Config written but site 404s | Another server block claims that `server_name`; check `nginx -T` ordering. | +| `state file is locked` | Another run is in progress. Remove `state.json.lock` only if no proxdomain process is running. | + +## Layout + +``` +proxdomain/ + cli.py argparse commands and output + config.py TOML parsing, per-kind defaults, secret resolution + http.py urllib JSON client with retries and an injectable transport + proxmox.py guest inventory, tag parsing, IP resolution + cloudflare.py zone discovery, A/AAAA upsert, delete + webserver.py nginx/Caddy/Traefik renderers, validate + rollback, bootstrap + runner.py LocalRunner / SSHRunner (atomic writes, sudo -n) + service.py orchestration and reports + state.py state.json, locking, audit log +tests/ test suite against fake HTTP/SSH layers +deploy/ systemd units and a sudoers example +``` + +## Development + +```bash +python run_tests.py # unittest suite, no network, no root +python -m proxdomain --help +``` + +Tests use an in-memory HTTP transport and an in-memory runner, so they cover +zone discovery, record create/update/no-op, IP filtering, config rollback, +certbot ordering and the full assign/remove/sync flows without touching a real +Proxmox host or Cloudflare account. + +## Limits + +* One `A`/`AAAA` record per name; no CNAME, wildcard or Cloudflare Tunnel setup. +* The record type follows `proxmox.ip_preference`; a stale record of the other + type is left alone and reported in `list` as managed separately. +* Removal only knows about assignments in `state.json`; deleting the state file + orphans generated config files (they are still visible on disk). +* No ACME DNS-01; webroot/HTTP-01 and existing certificates only. diff --git a/config.example.toml b/config.example.toml new file mode 100755 index 0000000..1018a3a --- /dev/null +++ b/config.example.toml @@ -0,0 +1,97 @@ +# proxdomain configuration +# Copy to /etc/proxdomain/config.toml (or ./proxdomain.toml) and edit. +# Secrets are read from environment variables or files, never from this file. + +[general] +# Registrable domain managed in Cloudflare. Zone discovery walks up from the +# guest name until it finds a zone the token can read. +base_domain = "example.com" +# Placeholders: {hostname} {vmid} {node} {kind} {base_domain} +# Keep {hostname} or {vmid} so every guest gets a unique name. +domain_template = "{hostname}.{base_domain}" +# Backend port used when `assign` is called without --port. +default_port = 80 + +[proxmox] +# Proxmox VE API endpoint (note the /api2/json suffix and port 8006). +api_url = "https://pve.example.com:8006/api2/json" +# API token identifier: user@realm!tokenname +token_id = "automation@pve!proxdomain" +# Preferred: export PROXDOMAIN_PVE_TOKEN in the service environment. +token_secret_env = "PROXDOMAIN_PVE_TOKEN" +# Alternatives (uncomment one): +# token_secret_file = "/etc/proxdomain/pve.token" +# token_secret = "00000000-0000-0000-0000-000000000000" +# Set to false only for a self-signed PVE certificate you cannot replace. +verify_tls = true +timeout = 20 +# Addresses that are never published (loopback/link-local are always skipped). +exclude_networks = ["127.0.0.0/8", "169.254.0.0/16", "172.17.0.0/16"] +# auto | ipv4 | ipv6 +ip_preference = "ipv4" + +[cloudflare] +api_url = "https://api.cloudflare.com/client/v4" +# Preferred: export PROXDOMAIN_CF_TOKEN +api_token_env = "PROXDOMAIN_CF_TOKEN" +# api_token_file = "/etc/proxdomain/cloudflare.token" +# api_token = "..." +# Orange cloud. Automatically disabled (with a warning) for non-public IPs. +proxied = true +# 1 = automatic, otherwise 60..86400 seconds. +ttl = 1 +record_comment = "managed by proxdomain" +timeout = 20 +retries = 2 + +[webserver] +kind = "nginx" # nginx | caddy | traefik +mode = "local" # local (run on the PVE host) | ssh (manage it remotely) +# Directory holding one file per domain. `proxdomain init` creates it. +manage_dir = "/etc/nginx/conf.d/proxdomain.d" +# Defaults per kind are filled in when omitted: +# nginx test: nginx -t reload: systemctl reload nginx +# caddy test: caddy validate --config ... reload: systemctl reload caddy +# traefik test/reload: none (file provider reloads itself) +# test_command = ["nginx", "-t"] +# reload_command = ["systemctl", "reload", "nginx"] + +# Only for mode = "ssh": the PVE host to manage. +# ssh_host = "root@pve.example.com" +# ssh_port = 22 +# ssh_identity_file = "/root/.ssh/proxdomain_ed25519" +# ssh_options = ["StrictHostKeyChecking=accept-new"] +# Prefix for privileged remote commands; -n fails fast instead of prompting. +# sudo = "sudo -n" + +# Required by kind = "traefik" when you want its ACME resolver used. +# cert_resolver = "letsencrypt" + +[webserver.tls] +# none - proxy listens on :80 (Cloudflare terminates TLS, or plain HTTP) +# files - serve :443 using cert_dir//{fullchain,privkey}.pem +# certbot - obtain the certificate with certbot (nginx only); the app first +# activates an HTTP vhost to answer the ACME challenge +mode = "none" +cert_dir = "/etc/letsencrypt/live" +webroot = "/var/www/certbot" +# Required for mode = "certbot": +# email = "ops@example.com" +# certbot_command = ["certbot", "certonly", "--webroot", "-w", "/var/www/certbot", "-n", "--agree-tos"] +# extra_args = ["--deploy-hook", "systemctl reload nginx"] + +[watch] +# Used by `proxdomain watch`; the command itself is safe to run from cron/systemd. +enabled = false +interval = 60 +# Only guests carrying this Proxmox tag are candidates. +tag = "proxdomain" +# false = list candidates only; pass --auto-assign (or set true) to assign. +auto_assign = false +require_running = true + +[state] +path = "/var/lib/proxdomain/state.json" +# Defaults to audit.jsonl next to the state file. +# audit_path = "/var/log/proxdomain/audit.jsonl" +lock_timeout = 10 diff --git a/deploy/proxdomain-watch.service b/deploy/proxdomain-watch.service new file mode 100755 index 0000000..c449966 --- /dev/null +++ b/deploy/proxdomain-watch.service @@ -0,0 +1,19 @@ +[Unit] +Description=proxdomain: assign domains to new Proxmox guests +Documentation=file:///opt/proxdomain/README.md +After=network-online.target pve-cluster.service +Wants=network-online.target + +[Service] +Type=oneshot +# Secrets live here, not in the config file: +# PROXDOMAIN_PVE_TOKEN=... +# PROXDOMAIN_CF_TOKEN=... +EnvironmentFile=-/etc/proxdomain/env +Environment=PROXDOMAIN_CONFIG=/etc/proxdomain/config.toml +ExecStart=/usr/local/bin/proxdomain watch --once --auto-assign +# The service only talks to the PVE API and local nginx; it needs no home. +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true +ReadWritePaths=/etc/nginx/conf.d/proxdomain.d /var/lib/proxdomain /var/www/certbot diff --git a/deploy/proxdomain-watch.timer b/deploy/proxdomain-watch.timer new file mode 100755 index 0000000..51e7261 --- /dev/null +++ b/deploy/proxdomain-watch.timer @@ -0,0 +1,11 @@ +[Unit] +Description=Run proxdomain watch every two minutes + +[Timer] +OnBootSec=2min +OnUnitActiveSec=2min +AccuracySec=15s +Persistent=true + +[Install] +WantedBy=timers.target diff --git a/deploy/sudoers.example b/deploy/sudoers.example new file mode 100755 index 0000000..3e6d23f --- /dev/null +++ b/deploy/sudoers.example @@ -0,0 +1,15 @@ +# Example sudoers entry for `webserver.mode = "ssh"` (managing nginx on a +# remote Proxmox host from another machine). +# +# WARNING: `tee`/`mv` into /etc as root makes this account root-equivalent. +# Running proxdomain locally on the Proxmox host (mode = "local", root systemd +# unit) avoids handing out that much power. Prefer that unless you have a +# specific reason to manage the host remotely. +# +# Install with: visudo -f /etc/sudoers.d/proxdomain + +proxdomain ALL=(root) NOPASSWD: \ + /usr/bin/mkdir, /usr/bin/tee, /usr/bin/chmod, /usr/bin/mv, /usr/bin/rm, \ + /usr/bin/test, /usr/bin/cat, /usr/bin/grep, \ + /usr/bin/nginx, /usr/bin/caddy, /usr/bin/certbot, \ + /usr/bin/systemctl reload nginx, /usr/bin/systemctl reload caddy diff --git a/proxdomain/__init__.py b/proxdomain/__init__.py new file mode 100755 index 0000000..2211ba8 --- /dev/null +++ b/proxdomain/__init__.py @@ -0,0 +1,11 @@ +"""proxdomain — assign a public domain to Proxmox VMs/containers. + +The package is intentionally dependency free (Python 3.11+ standard library): +it speaks the Proxmox VE and Cloudflare v4 HTTP APIs directly and writes +reverse-proxy config for nginx, Caddy or Traefik. +""" + +from __future__ import annotations + +__version__ = "0.1.0" +__all__ = ["__version__"] diff --git a/proxdomain/__main__.py b/proxdomain/__main__.py new file mode 100755 index 0000000..463ef45 --- /dev/null +++ b/proxdomain/__main__.py @@ -0,0 +1,10 @@ +"""`python -m proxdomain` entry point.""" + +from __future__ import annotations + +import sys + +from .cli import main + +if __name__ == "__main__": + sys.exit(main()) diff --git a/proxdomain/cli.py b/proxdomain/cli.py new file mode 100755 index 0000000..088fe7f --- /dev/null +++ b/proxdomain/cli.py @@ -0,0 +1,291 @@ +"""Command line interface: assign, remove, list, sync, watch, doctor, init.""" + +from __future__ import annotations + +import argparse +import json +import sys +import time + +from . import __version__ +from .config import load_config +from .errors import ConfigError, ProxdomainError +from .service import DomainService, ServiceReport + +_STATUS = { + "ok": "ok", + "changed": "done", + "planned": "plan", + "warning": "warn", + "skipped": "skip", + "error": "FAIL", +} + + +def build_parser() -> argparse.ArgumentParser: + common = argparse.ArgumentParser(add_help=False) + common.add_argument( + "-c", + "--config", + default=argparse.SUPPRESS, + help="path to proxdomain.toml (default: ./proxdomain.toml or /etc/proxdomain/config.toml)", + ) + common.add_argument( + "--json", + action="store_true", + default=argparse.SUPPRESS, + help="print machine-readable JSON", + ) + + parser = argparse.ArgumentParser( + prog="proxdomain", + description=( + "Give a Proxmox VM/CT a public domain: creates the Cloudflare DNS " + "record and the reverse-proxy entry on the Proxmox host." + ), + parents=[common], + ) + parser.add_argument("--version", action="version", version=f"proxdomain {__version__}") + sub = parser.add_subparsers(dest="command", metavar="command") + + assign = sub.add_parser( + "assign", + parents=[common], + help="assign a domain to a VM/CT and wire up DNS + reverse proxy", + description=( + "Resolve the guest, pick its IP, create or update the Cloudflare " + "A/AAAA record and write the web server config. Safe to re-run." + ), + ) + target = assign.add_mutually_exclusive_group(required=True) + target.add_argument("--vmid", type=int, help="Proxmox guest ID") + target.add_argument("--name", help="Proxmox guest name (exact, then substring)") + assign.add_argument( + "--subdomain", + 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( + "--proxied", + dest="proxied", + action=argparse.BooleanOptionalAction, + default=None, + help="Cloudflare orange cloud (default: cloudflare.proxied)", + ) + assign.add_argument("--force", action="store_true", help="take over a domain owned by another guest") + assign.add_argument("--dry-run", action="store_true", help="show what would change, touch nothing") + + remove = sub.add_parser( + "remove", + parents=[common], + help="remove the DNS record and proxy config for an assignment", + ) + which = remove.add_mutually_exclusive_group(required=True) + which.add_argument("--fqdn", help="domain to remove") + which.add_argument("--vmid", type=int, help="guest whose assignment should be removed") + remove.add_argument("--yes", action="store_true", help="confirm the deletion") + remove.add_argument("--dry-run", action="store_true", help="show what would be removed") + + sub.add_parser( + "list", + parents=[common], + help="list managed domains", + ) + + sync = sub.add_parser( + "sync", + parents=[common], + help="re-apply DNS + config for every managed domain (after IP or config changes)", + ) + sync.add_argument("--dry-run", action="store_true") + + watch = sub.add_parser( + "watch", + parents=[common], + help="assign domains to newly created guests (cron/systemd or long-running)", + ) + watch.add_argument("--once", action="store_true", help="single pass, then exit") + watch.add_argument("--interval", type=int, help="seconds between passes") + watch.add_argument("--tag", help="only guests carrying this Proxmox tag") + watch.add_argument("--all-new", action="store_true", help="ignore tags, consider every new guest") + watch.add_argument( + "--auto-assign", + action="store_true", + help="actually assign; without it watch only lists candidates", + ) + watch.add_argument("--dry-run", action="store_true", help="plan every assignment") + + sub.add_parser( + "doctor", + parents=[common], + help="check config, Proxmox, Cloudflare and web server access", + ) + + init = sub.add_parser( + "init", + parents=[common], + help="create the managed config directory and the web server include", + ) + init.add_argument("--dry-run", action="store_true") + + return parser + + +def main(argv: list[str] | None = None) -> int: + parser = build_parser() + args = parser.parse_args(argv) + command = args.command + if command is None: + parser.print_help() + return 2 + + json_output = bool(getattr(args, "json", False)) + try: + config = load_config(getattr(args, "config", None)) + except ConfigError as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + + try: + service = DomainService(config) + except (ConfigError, ProxdomainError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + + try: + if command == "assign": + report = service.assign( + vmid=args.vmid, + name=args.name, + subdomain=args.subdomain, + port=args.port, + ip=args.ip, + proxied=args.proxied, + force=args.force, + dry_run=args.dry_run, + ) + return _finish(report, json_output) + + if command == "remove": + report = service.remove( + fqdn=args.fqdn, + vmid=args.vmid, + confirm=args.yes, + dry_run=args.dry_run, + ) + return _finish(report, json_output) + + if command == "list": + return _list(service, json_output) + + if command == "sync": + return _finish(service.sync(dry_run=args.dry_run), json_output) + + if command == "watch": + return _watch(service, args, json_output) + + if command == "doctor": + return _finish(service.doctor(), json_output) + + if command == "init": + return _finish(service.init(dry_run=args.dry_run), json_output) + + parser.print_help() + return 2 + except ProxdomainError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + except KeyboardInterrupt: + print("interrupted", file=sys.stderr) + return 130 + + +# --------------------------------------------------------------------------- +def _finish(report: ServiceReport, json_output: bool) -> int: + print_report(report, json_output=json_output) + return 0 if report.ok else 1 + + +def print_report(report: ServiceReport, *, json_output: bool = False) -> None: + if json_output: + print(json.dumps(report.to_dict(), indent=2)) + return + print(f"{report.action}: {'ok' if report.ok else 'FAILED'}") + for step in report.steps: + label = _STATUS.get(step.status, step.status) + print(f" [{label:<4}] {step.name:<12} {step.detail}") + + +def _list(service: DomainService, json_output: bool) -> int: + items = service.state.all() + if json_output: + print(json.dumps([item.to_dict() for item in items], indent=2)) + return 0 + if not items: + print("no managed domains yet (run: proxdomain assign --vmid )") + return 0 + + headers = ("FQDN", "VMID", "NODE", "IP", "PORT", "DNS") + rows = [ + ( + item.fqdn, + str(item.vmid), + item.node, + item.ip or "-", + str(item.port), + "yes" if item.record_id else "-", + ) + for item in items + ] + widths = [len(header) for header in headers] + for row in rows: + for index, value in enumerate(row): + widths[index] = max(widths[index], len(value)) + print(" ".join(header.ljust(widths[i]) for i, header in enumerate(headers))) + print(" ".join("-" * width for width in widths)) + for row in rows: + print(" ".join(value.ljust(widths[i]) for i, value in enumerate(row))) + return 0 + + +def _watch(service: DomainService, args: argparse.Namespace, json_output: bool) -> int: + auto = bool(args.auto_assign or service.config.watch.auto_assign) + interval = args.interval or service.config.watch.interval + tag = "" if args.all_new else (args.tag if args.tag is not None else None) + failures = 0 + + while True: + try: + candidates = service.watch_candidates( + tag=tag, require_running=service.config.watch.require_running + ) + except ProxdomainError as exc: + print(f"error: {exc}", file=sys.stderr) + if args.once: + return 1 + candidates = [] + failures += 1 + + if not candidates: + print("[ok ] no new guests to assign") + for guest in candidates: + if not auto: + tags = ",".join(guest.tags) or "-" + print( + f"[new ] {guest.label} tags={tags} -> " + f"proxdomain assign --vmid {guest.vmid}" + ) + continue + report = service.assign(vmid=guest.vmid, dry_run=args.dry_run) + print_report(report, json_output=json_output) + if not report.ok: + failures += 1 + + if args.once: + break + try: + time.sleep(max(5, interval)) + except KeyboardInterrupt: + break + return 0 if failures == 0 else 1 diff --git a/proxdomain/cloudflare.py b/proxdomain/cloudflare.py new file mode 100755 index 0000000..abce121 --- /dev/null +++ b/proxdomain/cloudflare.py @@ -0,0 +1,234 @@ +"""Cloudflare v4 DNS client (A/AAAA records) with zone discovery.""" + +from __future__ import annotations + +import ipaddress +from dataclasses import dataclass + +from .config import CloudflareConfig +from .errors import ApiError, ProxdomainError +from .http import JsonClient, Transport, UrllibTransport + + +@dataclass(frozen=True) +class DnsRecord: + id: str + name: str + type: str + content: str + proxied: bool = False + ttl: int = 1 + + @classmethod + def from_api(cls, payload: dict) -> "DnsRecord": + return cls( + id=str(payload.get("id") or ""), + name=str(payload.get("name") or ""), + type=str(payload.get("type") or ""), + content=str(payload.get("content") or ""), + proxied=bool(payload.get("proxied") or False), + ttl=int(payload.get("ttl") or 1), + ) + + +@dataclass(frozen=True) +class Zone: + id: str + name: str + + +@dataclass(frozen=True) +class UpsertResult: + action: str # created | updated | unchanged + record: DnsRecord + previous: DnsRecord | None = None + + @property + def changed(self) -> bool: + return self.action != "unchanged" + + +class CloudflareClient: + def __init__( + self, + config: CloudflareConfig, + *, + http: JsonClient | None = None, + transport: Transport | None = None, + ) -> None: + self.config = config + if http is None: + http = JsonClient( + config.api_url, + transport=transport or UrllibTransport(), + timeout=config.timeout, + retries=config.retries, + ) + self.http = http + self.http.default_headers["Authorization"] = f"Bearer {config.resolve_token()}" + self._zone_cache: dict[str, Zone | None] = {} + + # -- token / zones -------------------------------------------------- + def verify_token(self) -> str: + data = self.http.get("/user/tokens/verify") + result = data.get("result") if isinstance(data, dict) else None + return str((result or {}).get("status") or "unknown") + + def list_zones(self) -> list[Zone]: + zones: list[Zone] = [] + page = 1 + while page <= 10: + data = self.http.get("/zones", {"per_page": 50, "page": page}) + rows = _result_list(data) + zones.extend(Zone(id=str(z["id"]), name=str(z["name"])) for z in rows if z.get("id")) + info = data.get("result_info") if isinstance(data, dict) else None + total_pages = int((info or {}).get("total_pages") or 1) + if page >= total_pages or not rows: + break + page += 1 + return zones + + def find_zone(self, fqdn: str, base_domain: str | None = None) -> Zone: + candidates = _zone_candidates(fqdn, base_domain) + for candidate in candidates: + if candidate in self._zone_cache: + cached = self._zone_cache[candidate] + if cached is not None: + return cached + continue + data = self.http.get("/zones", {"name": candidate, "per_page": 50}) + rows = _result_list(data) + zone = None + for row in rows: + if str(row.get("name", "")).lower() == candidate.lower() and row.get("id"): + zone = Zone(id=str(row["id"]), name=str(row["name"])) + break + self._zone_cache[candidate] = zone + if zone is not None: + return zone + raise ProxdomainError( + "no Cloudflare zone found for " + f"{fqdn} (tried: {', '.join(candidates)}); " + "check general.base_domain and that the token can read the zone" + ) + + # -- records -------------------------------------------------------- + def list_records( + self, zone_id: str, *, name: str | None = None, rtype: str | None = None + ) -> list[DnsRecord]: + params = {"per_page": 100} + if name: + params["name"] = name + if rtype: + params["type"] = rtype + data = self.http.get(f"/zones/{zone_id}/dns_records", params) + records = [] + for row in _result_list(data): + if not isinstance(row, dict) or not row.get("id"): + continue + record = DnsRecord.from_api(row) + if name and record.name.lower() != name.lower(): + continue + if rtype and record.type.upper() != rtype.upper(): + continue + records.append(record) + return records + + def upsert_address_record( + self, + zone_id: str, + fqdn: str, + address: str, + *, + proxied: bool | None = None, + ttl: int | None = None, + comment: str | None = None, + ) -> UpsertResult: + rtype = _record_type(address) + proxied = self.config.proxied if proxied is None else proxied + ttl = self.config.ttl if ttl is None else ttl + # Cloudflare forces TTL 1 (automatic) on proxied records; compare against + # that value so a configured 300 does not trigger a PATCH on every run. + ttl = 1 if proxied else ttl + comment = self.config.record_comment if comment is None else comment + + existing = self.list_records(zone_id, name=fqdn, rtype=rtype) + if existing: + current = existing[0] + same_content = current.content == address + same_proxy = current.proxied == proxied + same_ttl = current.ttl == ttl + if same_content and same_proxy and same_ttl: + return UpsertResult("unchanged", current) + payload = { + "type": rtype, + "name": fqdn, + "content": address, + "ttl": ttl, + "proxied": proxied, + } + if comment: + payload["comment"] = comment + data = self.http.patch(f"/zones/{zone_id}/dns_records/{current.id}", payload) + return UpsertResult("updated", _record_from_response(data, current), current) + + payload = { + "type": rtype, + "name": fqdn, + "content": address, + "ttl": ttl, + "proxied": proxied, + } + if comment: + payload["comment"] = comment + data = self.http.post(f"/zones/{zone_id}/dns_records", payload) + return UpsertResult("created", _record_from_response(data, None)) + + def delete_record(self, zone_id: str, record_id: str) -> bool: + try: + self.http.delete(f"/zones/{zone_id}/dns_records/{record_id}") + except ApiError as exc: + if exc.status == 404: + return False + raise + return True + + +# --------------------------------------------------------------------------- +def _record_type(address: str) -> str: + try: + version = ipaddress.ip_address(address).version + except ValueError as exc: + raise ProxdomainError(f"not a valid IP address: {address!r}") from exc + return "A" if version == 4 else "AAAA" + + +def _record_from_response(data: object, previous: DnsRecord | None) -> DnsRecord: + if isinstance(data, dict): + inner = data.get("result", data) + if isinstance(inner, dict) and inner.get("id"): + return DnsRecord.from_api(inner) + if previous is not None: + return previous + raise ProxdomainError("Cloudflare returned an unexpected DNS record payload") + + +def _result_list(data: object) -> list[dict]: + if isinstance(data, dict) and isinstance(data.get("result"), list): + return [row for row in data["result"] if isinstance(row, dict)] + return [] + + +def _zone_candidates(fqdn: str, base_domain: str | None) -> list[str]: + fqdn = fqdn.strip().lower().rstrip(".") + labels = fqdn.split(".") + suffixes = [".".join(labels[i:]) for i in range(len(labels) - 1)] + ordered: list[str] = [] + if base_domain: + base = base_domain.strip().lower().rstrip(".") + if fqdn == base or fqdn.endswith("." + base): + ordered.append(base) + for suffix in reversed(suffixes): # shortest first (closest to the apex) + if suffix not in ordered: + ordered.append(suffix) + return ordered diff --git a/proxdomain/config.py b/proxdomain/config.py new file mode 100755 index 0000000..617a2a9 --- /dev/null +++ b/proxdomain/config.py @@ -0,0 +1,475 @@ +"""Configuration loading and validation (TOML, standard library only).""" + +from __future__ import annotations + +import os +import tomllib +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Any, Mapping + +from .errors import ConfigError + +ENV_CONFIG = "PROXDOMAIN_CONFIG" +DEFAULT_CONFIG_PATHS = ( + Path("proxdomain.toml"), + Path("/etc/proxdomain/config.toml"), +) + +WEBSERVER_KINDS = ("nginx", "caddy", "traefik") +WEBSERVER_MODES = ("local", "ssh") +TLS_MODES = ("none", "files", "certbot") +IP_PREFERENCES = ("auto", "ipv4", "ipv6") + +# Web server defaults live here so `config.example.toml` and the docs stay honest. +_KIND_DEFAULTS: dict[str, dict[str, Any]] = { + "nginx": { + "manage_dir": "/etc/nginx/conf.d/proxdomain.d", + "test_command": ("nginx", "-t"), + "reload_command": ("systemctl", "reload", "nginx"), + "cert_resolver": "", + }, + "caddy": { + "manage_dir": "/etc/caddy/proxdomain.d", + "test_command": ("caddy", "validate", "--config", "/etc/caddy/Caddyfile", "--adapter", "caddyfile"), + "reload_command": ("systemctl", "reload", "caddy"), + "cert_resolver": "", + }, + "traefik": { + "manage_dir": "/etc/traefik/dynamic", + # The file provider watches its directory; no reload needed. + "test_command": (), + "reload_command": (), + "cert_resolver": "letsencrypt", + }, +} + + +@dataclass(frozen=True) +class GeneralConfig: + base_domain: str + domain_template: str = "{hostname}.{base_domain}" + default_port: int = 80 + + +@dataclass(frozen=True) +class ProxmoxConfig: + api_url: str + token_id: str + token_secret: str | None = None + token_secret_env: str | None = None + token_secret_file: str | None = None + verify_tls: bool = True + timeout: float = 20.0 + exclude_networks: tuple[str, ...] = ( + "127.0.0.0/8", + "169.254.0.0/16", + "172.17.0.0/16", + ) + ip_preference: str = "ipv4" + + 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 + if self.token_secret_file: + path = Path(self.token_secret_file).expanduser() + try: + value = path.read_text(encoding="utf-8").strip() + except OSError as exc: + raise ConfigError(f"cannot read proxmox.token_secret_file {path}: {exc}") from exc + if not value: + raise ConfigError(f"proxmox.token_secret_file {path} is empty") + return value + if self.token_secret: + return self.token_secret + raise ConfigError( + "no Proxmox API token secret configured; set proxmox.token_secret_env " + "(recommended), proxmox.token_secret_file or proxmox.token_secret" + ) + + +@dataclass(frozen=True) +class CloudflareConfig: + api_url: str = "https://api.cloudflare.com/client/v4" + api_token: str | None = None + api_token_env: str | None = "PROXDOMAIN_CF_TOKEN" + api_token_file: str | None = None + proxied: bool = True + ttl: int = 1 + record_comment: str = "managed by proxdomain" + timeout: float = 20.0 + retries: int = 2 + + 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 + if self.api_token_file: + path = Path(self.api_token_file).expanduser() + try: + value = path.read_text(encoding="utf-8").strip() + except OSError as exc: + raise ConfigError( + f"cannot read cloudflare.api_token_file {path}: {exc}" + ) from exc + if not value: + raise ConfigError(f"cloudflare.api_token_file {path} is empty") + return value + if self.api_token: + return self.api_token + raise ConfigError( + "no Cloudflare API token configured; set cloudflare.api_token_env " + "(recommended), cloudflare.api_token_file or cloudflare.api_token" + ) + + +@dataclass(frozen=True) +class TlsConfig: + mode: str = "none" # none | files | certbot + 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 = "" + extra_args: tuple[str, ...] = () + + +@dataclass(frozen=True) +class WebServerConfig: + kind: str = "nginx" + mode: str = "local" # local | ssh + manage_dir: str = "" + test_command: tuple[str, ...] = () + reload_command: tuple[str, ...] = () + ssh_host: str = "" + ssh_port: int = 22 + ssh_identity_file: str = "" + ssh_options: tuple[str, ...] = () + sudo: str = "sudo -n" + cert_resolver: str = "" + tls: TlsConfig = TlsConfig() + + def command(self, name: str) -> tuple[str, ...]: + return self.test_command if name == "test" else self.reload_command + + +@dataclass(frozen=True) +class WatchConfig: + enabled: bool = False + interval: int = 60 + tag: str = "proxdomain" + auto_assign: bool = False + require_running: bool = True + + +@dataclass(frozen=True) +class StateConfig: + path: str = "/var/lib/proxdomain/state.json" + audit_path: str = "" + lock_timeout: float = 10.0 + + def resolved_audit_path(self) -> str: + if self.audit_path: + return self.audit_path + # POSIX-style join: the state path describes the Proxmox host, so the + # derived path must not depend on the platform running the CLI. + parent = self.path.rsplit("/", 1)[0] if "/" in self.path else "." + return f"{parent}/audit.jsonl" + + +@dataclass(frozen=True) +class Config: + general: GeneralConfig + proxmox: ProxmoxConfig + cloudflare: CloudflareConfig + webserver: WebServerConfig + watch: WatchConfig = WatchConfig() + state: StateConfig = StateConfig() + source: Path | None = None + + +# --------------------------------------------------------------------------- +# loading +# --------------------------------------------------------------------------- +def resolve_config_path(explicit: str | os.PathLike[str] | None = None) -> Path: + candidates: list[Path] = [] + if explicit: + candidates.append(Path(explicit).expanduser()) + elif os.environ.get(ENV_CONFIG): + candidates.append(Path(os.environ[ENV_CONFIG]).expanduser()) + else: + candidates.extend(DEFAULT_CONFIG_PATHS) + + for candidate in candidates: + if candidate.is_file(): + return candidate + searched = ", ".join(str(c) for c in candidates) + raise ConfigError( + f"no configuration file found (searched: {searched}); " + "copy config.example.toml to proxdomain.toml or pass --config" + ) + + +def load_config(path: str | os.PathLike[str] | None = None) -> Config: + config_path = resolve_config_path(path) + try: + with config_path.open("rb") as handle: + raw = tomllib.load(handle) + except OSError as exc: + raise ConfigError(f"cannot read {config_path}: {exc}") from exc + except tomllib.TOMLDecodeError as exc: + raise ConfigError(f"{config_path} is not valid TOML: {exc}") from exc + return parse_config(raw, source=config_path) + + +def parse_config(raw: Mapping[str, Any], *, source: Path | None = None) -> Config: + if not isinstance(raw, Mapping): + raise ConfigError("configuration root must be a TOML table") + + general_raw = _table(raw, "general") + proxmox_raw = _table(raw, "proxmox") + cloudflare_raw = _table(raw, "cloudflare") + webserver_raw = _table(raw, "webserver") + watch_raw = _table(raw, "watch") + state_raw = _table(raw, "state") + tls_raw = _table(webserver_raw, "tls", prefix="webserver") + + general = GeneralConfig( + base_domain=_str(general_raw, "base_domain", required=True, prefix="general"), + domain_template=_str( + general_raw, "domain_template", "{hostname}.{base_domain}", prefix="general" + ), + default_port=_port(general_raw, "default_port", 80, prefix="general"), + ) + if not general.base_domain or "." not in general.base_domain: + raise ConfigError("general.base_domain must be a registrable domain such as example.com") + if "{hostname}" not in general.domain_template and "{vmid}" not in general.domain_template: + raise ConfigError( + "general.domain_template must contain {hostname} or {vmid} so each guest gets a name" + ) + + proxmox = ProxmoxConfig( + api_url=_str(proxmox_raw, "api_url", required=True, prefix="proxmox"), + token_id=_str(proxmox_raw, "token_id", required=True, prefix="proxmox"), + token_secret=_opt_str(proxmox_raw, "token_secret", prefix="proxmox"), + token_secret_env=_opt_str(proxmox_raw, "token_secret_env", prefix="proxmox"), + token_secret_file=_opt_str(proxmox_raw, "token_secret_file", prefix="proxmox"), + verify_tls=_bool(proxmox_raw, "verify_tls", True, prefix="proxmox"), + timeout=_float(proxmox_raw, "timeout", 20.0, prefix="proxmox"), + exclude_networks=_str_tuple(proxmox_raw, "exclude_networks", prefix="proxmox") + or ProxmoxConfig.exclude_networks, + ip_preference=_choice( + proxmox_raw, "ip_preference", "ipv4", IP_PREFERENCES, prefix="proxmox" + ), + ) + if "!" not in proxmox.token_id: + raise ConfigError( + "proxmox.token_id must look like 'user@realm!tokenname' " + "(Proxmox API token identifier)" + ) + if not proxmox.api_url.startswith(("http://", "https://")): + raise ConfigError("proxmox.api_url must start with http:// or https://") + + cloudflare = CloudflareConfig( + api_url=_str(cloudflare_raw, "api_url", CloudflareConfig.api_url, prefix="cloudflare"), + api_token=_opt_str(cloudflare_raw, "api_token", prefix="cloudflare"), + api_token_env=_opt_str(cloudflare_raw, "api_token_env", prefix="cloudflare") + or None, + api_token_file=_opt_str(cloudflare_raw, "api_token_file", prefix="cloudflare"), + proxied=_bool(cloudflare_raw, "proxied", True, prefix="cloudflare"), + ttl=_int(cloudflare_raw, "ttl", 1, prefix="cloudflare"), + record_comment=_str( + cloudflare_raw, "record_comment", "managed by proxdomain", prefix="cloudflare" + ), + timeout=_float(cloudflare_raw, "timeout", 20.0, prefix="cloudflare"), + retries=_int(cloudflare_raw, "retries", 2, prefix="cloudflare"), + ) + if cloudflare.ttl != 1 and not 60 <= cloudflare.ttl <= 86400: + raise ConfigError("cloudflare.ttl must be 1 (auto) or between 60 and 86400") + + kind = _choice(webserver_raw, "kind", "nginx", WEBSERVER_KINDS, prefix="webserver") + defaults = _KIND_DEFAULTS[kind] + mode = _choice(webserver_raw, "mode", "local", WEBSERVER_MODES, prefix="webserver") + manage_dir = _str(webserver_raw, "manage_dir", defaults["manage_dir"], prefix="webserver") + if not manage_dir.startswith("/"): + raise ConfigError("webserver.manage_dir must be an absolute path on the Proxmox host") + + test_command = _str_tuple(webserver_raw, "test_command", prefix="webserver") + if "test_command" not in webserver_raw: + test_command = tuple(defaults["test_command"]) + reload_command = _str_tuple(webserver_raw, "reload_command", prefix="webserver") + if "reload_command" not in webserver_raw: + reload_command = tuple(defaults["reload_command"]) + + tls = TlsConfig( + mode=_choice(tls_raw, "mode", "none", TLS_MODES, prefix="webserver.tls"), + cert_dir=_str(tls_raw, "cert_dir", TlsConfig.cert_dir, prefix="webserver.tls"), + webroot=_str(tls_raw, "webroot", TlsConfig.webroot, prefix="webserver.tls"), + certbot_command=_str_tuple(tls_raw, "certbot_command", prefix="webserver.tls") + or TlsConfig.certbot_command, + email=_str(tls_raw, "email", "", 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'") + + webserver = WebServerConfig( + kind=kind, + mode=mode, + manage_dir=manage_dir.rstrip("/"), + test_command=test_command, + reload_command=reload_command, + ssh_host=_str(webserver_raw, "ssh_host", "", prefix="webserver"), + ssh_port=_int(webserver_raw, "ssh_port", 22, prefix="webserver"), + ssh_identity_file=_str(webserver_raw, "ssh_identity_file", "", prefix="webserver"), + ssh_options=_str_tuple(webserver_raw, "ssh_options", prefix="webserver"), + sudo=_str(webserver_raw, "sudo", "sudo -n", prefix="webserver"), + cert_resolver=_str( + webserver_raw, "cert_resolver", defaults["cert_resolver"], prefix="webserver" + ), + tls=tls, + ) + if webserver.mode == "ssh" and not webserver.ssh_host: + raise ConfigError("webserver.ssh_host is required when webserver.mode = 'ssh'") + 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'" + ) + if kind == "traefik" and tls.mode == "files": + raise ConfigError( + "webserver.tls.mode = 'files' is not supported with kind = 'traefik'; " + "set webserver.cert_resolver instead" + ) + + 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"), + ) + watch = WatchConfig( + enabled=_bool(watch_raw, "enabled", False, prefix="watch"), + interval=max(5, _int(watch_raw, "interval", 60, prefix="watch")), + tag=_str(watch_raw, "tag", "proxdomain", prefix="watch").strip(), + auto_assign=_bool(watch_raw, "auto_assign", False, prefix="watch"), + require_running=_bool(watch_raw, "require_running", True, prefix="watch"), + ) + + return Config( + general=general, + proxmox=proxmox, + cloudflare=cloudflare, + webserver=webserver, + watch=watch, + state=state, + source=source, + ) + + +def with_overrides(config: Config, **overrides: Any) -> Config: + """Return a copy with simple top-level field overrides (used by tests/CLI).""" + return replace(config, **overrides) + + +# --------------------------------------------------------------------------- +# helpers +# --------------------------------------------------------------------------- +def _table(raw: Mapping[str, Any], key: str, *, prefix: str = "") -> Mapping[str, Any]: + value = raw.get(key, {}) + if not isinstance(value, Mapping): + raise ConfigError(f"{prefix + '.' if prefix else ''}{key} must be a TOML table") + return value + + +def _str( + table: Mapping[str, Any], key: str, default: str | None = None, *, + required: bool = False, prefix: str = "", +) -> str: + value = table.get(key, default) + if value is None: + if required: + raise ConfigError(f"missing required setting {_dotted(prefix, key)}") + return "" + if not isinstance(value, str): + raise ConfigError(f"{_dotted(prefix, key)} must be a string") + if required and not value.strip(): + raise ConfigError(f"{_dotted(prefix, key)} must not be empty") + return value.strip() + + +def _opt_str(table: Mapping[str, Any], key: str, *, prefix: str = "") -> str | None: + value = table.get(key) + if value is None: + return None + if not isinstance(value, str): + raise ConfigError(f"{_dotted(prefix, key)} must be a string") + return value.strip() or None + + +def _bool(table: Mapping[str, Any], key: str, default: bool, *, prefix: str = "") -> bool: + value = table.get(key, default) + if not isinstance(value, bool): + raise ConfigError(f"{_dotted(prefix, key)} must be true or false") + return value + + +def _int(table: Mapping[str, Any], key: str, default: int, *, prefix: str = "") -> int: + value = table.get(key, default) + if isinstance(value, bool) or not isinstance(value, int): + raise ConfigError(f"{_dotted(prefix, key)} must be an integer") + return value + + +def _float(table: Mapping[str, Any], key: str, default: float, *, prefix: str = "") -> float: + value = table.get(key, default) + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ConfigError(f"{_dotted(prefix, key)} must be a number") + return float(value) + + +def _port(table: Mapping[str, Any], key: str, default: int, *, prefix: str = "") -> int: + value = _int(table, key, default, prefix=prefix) + if not 1 <= value <= 65535: + raise ConfigError(f"{_dotted(prefix, key)} must be between 1 and 65535") + return value + + +def _str_tuple(table: Mapping[str, Any], key: str, *, prefix: str = "") -> tuple[str, ...]: + value = table.get(key) + if value is None: + return () + if isinstance(value, str): + raise ConfigError( + f"{_dotted(prefix, key)} must be an array of strings, e.g. [\"nginx\", \"-t\"]" + ) + if not isinstance(value, list) or not all(isinstance(v, str) for v in value): + raise ConfigError(f"{_dotted(prefix, key)} must be an array of strings") + return tuple(value) + + +def _choice( + table: Mapping[str, Any], key: str, default: str, allowed: tuple[str, ...], *, + prefix: str = "", +) -> str: + value = _str(table, key, default, prefix=prefix) + if value not in allowed: + raise ConfigError( + f"{_dotted(prefix, key)} must be one of: {', '.join(allowed)} (got {value!r})" + ) + return value + + +def _dotted(prefix: str, key: str) -> str: + return f"{prefix}.{key}" if prefix else key diff --git a/proxdomain/errors.py b/proxdomain/errors.py new file mode 100755 index 0000000..3b8bef4 --- /dev/null +++ b/proxdomain/errors.py @@ -0,0 +1,36 @@ +"""Exception types shared by every proxdomain module.""" + +from __future__ import annotations + + +class ProxdomainError(Exception): + """Base class for all expected, user-facing failures.""" + + +class ConfigError(ProxdomainError): + """The configuration file is missing, malformed or incomplete.""" + + +class ApiError(ProxdomainError): + """A remote API (Proxmox VE or Cloudflare) returned an error.""" + + def __init__( + self, + message: str, + *, + status: int | None = None, + payload: object | None = None, + url: str | None = None, + ) -> None: + super().__init__(message) + self.status = status + self.payload = payload + self.url = url + + @property + def is_auth_error(self) -> bool: + return self.status in (401, 403) + + +class WebServerError(ProxdomainError): + """Writing, validating or reloading the web server configuration failed.""" diff --git a/proxdomain/http.py b/proxdomain/http.py new file mode 100755 index 0000000..36433c1 --- /dev/null +++ b/proxdomain/http.py @@ -0,0 +1,203 @@ +"""A very small JSON-over-HTTP client with retries and testable transport.""" + +from __future__ import annotations + +import json +import socket +import ssl +import time +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass, field +from typing import Any, Mapping, Protocol + +from .errors import ApiError + +RETRY_STATUSES = (429, 502, 503, 504) +# POST is deliberately excluded: retrying a DNS create after a 502 could leave a +# duplicate record behind. Everything else here is safe to replay. +RETRYABLE_METHODS = frozenset({"GET", "HEAD", "PUT", "PATCH", "DELETE"}) + + +@dataclass(frozen=True) +class Response: + status: int + body: bytes + headers: Mapping[str, str] = field(default_factory=dict) + + def json(self) -> Any: + try: + return json.loads(self.body.decode("utf-8") or "null") + except (UnicodeDecodeError, json.JSONDecodeError) as exc: # pragma: no cover - defensive + raise ApiError(f"response is not valid JSON: {exc}") from exc + + def text(self) -> str: + return self.body.decode("utf-8", errors="replace") + + +class Transport(Protocol): + def request( + self, + method: str, + url: str, + headers: Mapping[str, str], + body: bytes | None, + timeout: float, + ) -> Response: ... + + +class UrllibTransport: + """Real network transport built on urllib (no third-party dependencies).""" + + def __init__(self, *, verify_tls: bool = True) -> None: + if verify_tls: + self._context: ssl.SSLContext | None = None + else: + self._context = ssl._create_unverified_context() # noqa: SLF001 - documented API gap + + def request( + self, + method: str, + url: str, + headers: Mapping[str, str], + body: bytes | None, + timeout: float, + ) -> Response: + req = urllib.request.Request(url, data=body, headers=dict(headers), method=method) + try: + with urllib.request.urlopen(req, timeout=timeout, context=self._context) as resp: + return Response( + status=resp.status, + body=resp.read(), + headers={k.lower(): v for k, v in resp.headers.items()}, + ) + except urllib.error.HTTPError as exc: + # Keep the payload: Cloudflare and Proxmox both put useful detail there. + return Response( + status=exc.code, + body=exc.read() or b"", + headers={k.lower(): v for k, v in (exc.headers or {}).items()}, + ) + except urllib.error.URLError as exc: + raise ApiError(f"cannot reach {url}: {exc.reason}") from exc + except socket.timeout as exc: + raise ApiError(f"timeout while calling {url}") from exc + + +class JsonClient: + """Base URL + auth headers + JSON encoding/decoding + bounded retries.""" + + def __init__( + self, + base_url: str, + *, + transport: Transport | None = None, + timeout: float = 20.0, + retries: int = 2, + backoff: float = 0.5, + default_headers: Mapping[str, str] | None = None, + sleep=time.sleep, + ) -> None: + self.base_url = base_url.rstrip("/") + self.transport = transport or UrllibTransport() + self.timeout = timeout + self.retries = max(0, retries) + self.backoff = backoff + self.default_headers = {"Accept": "application/json", **dict(default_headers or {})} + self._sleep = sleep + + # -- public API ----------------------------------------------------- + def get(self, path: str, params: Mapping[str, Any] | None = None) -> Any: + return self.request("GET", path, params=params) + + def post(self, path: str, body: Any) -> Any: + return self.request("POST", path, json_body=body) + + def patch(self, path: str, body: Any) -> Any: + return self.request("PATCH", path, json_body=body) + + def put(self, path: str, body: Any) -> Any: + return self.request("PUT", path, json_body=body) + + def delete(self, path: str) -> Any: + return self.request("DELETE", path) + + def request( + self, + method: str, + path: str, + *, + params: Mapping[str, Any] | None = None, + json_body: Any = None, + headers: Mapping[str, str] | None = None, + ) -> Any: + url = self.base_url + path + if params: + query = urllib.parse.urlencode( + {k: v for k, v in params.items() if v is not None}, doseq=True + ) + if query: + url = f"{url}?{query}" + + body = None if json_body is None else json.dumps(json_body).encode("utf-8") + request_headers = dict(self.default_headers) + if body is not None: + request_headers["Content-Type"] = "application/json" + if headers: + request_headers.update(headers) + + attempts = self.retries + 1 + last: Response | None = None + for attempt in range(1, attempts + 1): + last = self.transport.request(method, url, request_headers, body, self.timeout) + retryable = last.status == 429 or ( + last.status in RETRY_STATUSES and method.upper() in RETRYABLE_METHODS + ) + if last.status < 400 or not retryable or attempt == attempts: + break + delay = self.backoff * (2 ** (attempt - 1)) + retry_after = last.headers.get("retry-after") + if retry_after: + try: + delay = max(delay, float(retry_after)) + except ValueError: + pass + self._sleep(delay) + + assert last is not None + if last.status >= 400: + raise ApiError( + self._error_message(method, url, last), + status=last.status, + payload=_safe_json(last), + url=url, + ) + if not last.body: + return None + return last.json() + + # -- helpers -------------------------------------------------------- + @staticmethod + def _error_message(method: str, url: str, response: Response) -> str: + detail = "" + payload = _safe_json(response) + if isinstance(payload, dict): + errors = payload.get("errors") + if isinstance(errors, list) and errors: + detail = "; ".join( + str(e.get("message") if isinstance(e, dict) else e) for e in errors + ) + elif payload.get("message"): + detail = str(payload["message"]) + if not detail: + detail = response.text().strip()[:300] + suffix = f": {detail}" if detail else "" + return f"{method} {url} -> HTTP {response.status}{suffix}" + + +def _safe_json(response: Response) -> Any: + try: + return response.json() + except ApiError: + return None diff --git a/proxdomain/proxmox.py b/proxdomain/proxmox.py new file mode 100755 index 0000000..4fdfea5 --- /dev/null +++ b/proxdomain/proxmox.py @@ -0,0 +1,258 @@ +"""Proxmox VE API client: guest discovery and IP address resolution.""" + +from __future__ import annotations + +import ipaddress +from dataclasses import dataclass, field +from typing import Iterable + +from .config import ProxmoxConfig +from .errors import ApiError, ProxdomainError +from .http import JsonClient, Transport, UrllibTransport + + +@dataclass(frozen=True) +class Guest: + vmid: int + node: str + name: str + kind: str # "qemu" | "lxc" + status: str = "unknown" + tags: tuple[str, ...] = field(default_factory=tuple) + + @property + def ref(self) -> str: + return f"{self.kind}/{self.vmid}" + + @property + def label(self) -> str: + return f"{self.name or 'unnamed'} ({self.kind} {self.vmid} on {self.node})" + + @property + def is_running(self) -> bool: + return self.status == "running" + + +class ProxmoxClient: + def __init__( + self, + config: ProxmoxConfig, + *, + http: JsonClient | None = None, + transport: Transport | None = None, + ) -> None: + self.config = config + if http is None: + http = JsonClient( + config.api_url, + transport=transport or UrllibTransport(verify_tls=config.verify_tls), + timeout=config.timeout, + retries=1, + ) + self.http = http + self._excluded = _parse_networks(config.exclude_networks) + self.http.default_headers["Authorization"] = ( + f"PVEAPIToken={config.token_id}={config.resolve_secret()}" + ) + + # -- inventory ------------------------------------------------------ + def list_guests(self) -> list[Guest]: + data = self.http.get("/cluster/resources", {"type": "vm"}) + guests: list[Guest] = [] + for item in _data_list(data): + if not isinstance(item, dict) or "vmid" not in item: + continue + kind = str(item.get("type") or "") + if kind not in ("qemu", "lxc"): + continue + guests.append( + Guest( + vmid=int(item["vmid"]), + node=str(item.get("node") or ""), + name=str(item.get("name") or ""), + kind=kind, + status=str(item.get("status") or "unknown"), + tags=_split_tags(item.get("tags")), + ) + ) + guests.sort(key=lambda g: (g.node, g.vmid)) + return guests + + def find_guest( + self, *, vmid: int | None = None, name: str | None = None + ) -> Guest: + if vmid is None and not name: + raise ProxdomainError("specify a guest by --vmid or --name") + guests = self.list_guests() + if vmid is not None: + matches = [g for g in guests if g.vmid == vmid] + else: + needle = (name or "").strip().lower() + matches = [g for g in guests if g.name.lower() == needle] + if not matches: + matches = [g for g in guests if needle and needle in g.name.lower()] + if not matches: + target = f"vmid {vmid}" if vmid is not None else f"name {name!r}" + raise ProxdomainError(f"no guest found for {target}; check the PVE token permissions") + if len(matches) > 1: + listing = ", ".join(f"{g.kind}/{g.vmid} ({g.name})" for g in matches) + raise ProxdomainError(f"{name!r} matches several guests: {listing}; use --vmid") + return matches[0] + + def new_guests(self, known_vmids: Iterable[int], *, tag: str = "") -> list[Guest]: + known = set(known_vmids) + result = [] + for guest in self.list_guests(): + if guest.vmid in known: + continue + if tag and tag not in guest.tags: + continue + result.append(guest) + return result + + # -- addressing ----------------------------------------------------- + def guest_ip(self, guest: Guest) -> str | None: + want = self.config.ip_preference + candidates: list[str] = [] + + if guest.kind == "qemu": + candidates.extend(self._agent_ips(guest)) + else: + candidates.extend(self._lxc_runtime_ips(guest)) + candidates.extend(self._config_ips(guest)) + + unique: list[str] = [] + for address in candidates: + if address and address not in unique: + unique.append(address) + + v4 = [a for a in unique if _version(a) == 4 and self._usable(a)] + v6 = [a for a in unique if _version(a) == 6 and self._usable(a)] + if want == "ipv4": + return (v4 or v6 or [None])[0] + if want == "ipv6": + return (v6 or v4 or [None])[0] + return (unique and next((a for a in unique if self._usable(a)), None)) or None + + def _usable(self, address: str) -> bool: + try: + ip = ipaddress.ip_address(address) + except ValueError: + return False + if ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_unspecified: + return False + return not any(ip in network for network in self._excluded) + + def _agent_ips(self, guest: Guest) -> list[str]: + path = f"/nodes/{guest.node}/qemu/{guest.vmid}/agent/network-get-interfaces" + try: + data = self.http.get(path) + except ApiError as exc: + if exc.is_auth_error: + raise + return [] # qemu-guest-agent not installed/running: fall back to config + payload = data + if isinstance(payload, dict) and isinstance(payload.get("data"), (dict, list)): + payload = payload["data"] + if isinstance(payload, dict) and isinstance(payload.get("result"), list): + payload = payload["result"] + found: list[str] = [] + if isinstance(payload, list): + for iface in payload: + if not isinstance(iface, dict) or iface.get("name") == "lo": + continue + for addr in iface.get("ip-addresses") or []: + if not isinstance(addr, dict): + continue + value = addr.get("ip-address") + kind = addr.get("ip-address-type") + if value and kind in ("ipv4", "ipv6", 4, 6): + found.append(str(value)) + return found + + def _lxc_runtime_ips(self, guest: Guest) -> list[str]: + path = f"/nodes/{guest.node}/lxc/{guest.vmid}/interfaces" + try: + data = self.http.get(path) + except ApiError as exc: + if exc.is_auth_error: + raise + return [] + found: list[str] = [] + for item in _data_list(data): + if not isinstance(item, dict): + continue + for key in ("inet", "inet6"): + value = str(item.get(key) or "").split("/")[0].strip() + if value and value != "127.0.0.1": + found.append(value) + return found + + def _config_ips(self, guest: Guest) -> list[str]: + endpoint = "qemu" if guest.kind == "qemu" else "lxc" + try: + data = self.http.get(f"/nodes/{guest.node}/{endpoint}/{guest.vmid}/config") + except ApiError as exc: + if exc.is_auth_error: + raise + return [] + config = data if isinstance(data, dict) else {} + if "data" in config and isinstance(config["data"], dict): + config = config["data"] + found: list[str] = [] + for key, value in sorted(config.items()): + if not (key.startswith("net") or key.startswith("ipconfig")): + continue + if not isinstance(value, str): + continue + for option in value.split(","): + option = option.strip() + if "=" not in option: + continue + name, _, raw = option.partition("=") + if name.strip() not in ("ip", "ip6"): + continue + address = raw.split("/")[0].strip() + if address and address.lower() != "dhcp" and address.lower() != "auto": + found.append(address) + return found + + +# --------------------------------------------------------------------------- +def _parse_networks(values: Iterable[str]) -> tuple[ipaddress._BaseNetwork, ...]: + networks = [] + for value in values: + try: + networks.append(ipaddress.ip_network(value, strict=False)) + except ValueError as exc: + raise ProxdomainError( + f"proxmox.exclude_networks contains an invalid network {value!r}: {exc}" + ) from exc + return tuple(networks) + + +def _data_list(data: object) -> list: + if isinstance(data, dict): + inner = data.get("data") + if isinstance(inner, list): + return inner + if inner is None: + return [] + return [inner] + if isinstance(data, list): + return data + return [] + + +def _split_tags(value: object) -> tuple[str, ...]: + if not isinstance(value, str): + return () + normalized = value.replace(",", ";") + return tuple(tag.strip() for tag in normalized.split(";") if tag.strip()) + + +def _version(address: str) -> int: + try: + return ipaddress.ip_address(address).version + except ValueError: + return 0 diff --git a/proxdomain/runner.py b/proxdomain/runner.py new file mode 100755 index 0000000..3867f9d --- /dev/null +++ b/proxdomain/runner.py @@ -0,0 +1,287 @@ +"""File and command execution: either on this machine or on the Proxmox host over SSH.""" + +from __future__ import annotations + +import os +import shlex +import subprocess +import tempfile +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Protocol, Sequence + +from .errors import ProxdomainError + + +@dataclass(frozen=True) +class CommandResult: + argv: tuple[str, ...] + returncode: int + stdout: str = "" + stderr: str = "" + + @property + def ok(self) -> bool: + return self.returncode == 0 + + def output(self, limit: int = 1200) -> str: + text = "\n".join(part.strip() for part in (self.stdout, self.stderr) if part.strip()) + return text[-limit:] + + +class Runner(Protocol): + def run( + self, argv: Sequence[str], *, input_text: str | None = None, timeout: float = 120.0 + ) -> CommandResult: ... + + def write_text(self, path: str, content: str, mode: int = 0o644) -> bool: ... + + def read_text(self, path: str) -> str | None: ... + + def remove(self, path: str) -> bool: ... + + def exists(self, path: str) -> bool: ... + + def mkdir(self, path: str) -> None: ... + + def describe(self) -> str: ... + + +class LocalRunner: + """Writes files and runs commands directly (used when proxdomain runs on the PVE host).""" + + def __init__(self, *, sleep=time.sleep) -> None: + self._sleep = sleep + + def run( + self, argv: Sequence[str], *, input_text: str | None = None, timeout: float = 120.0 + ) -> CommandResult: + argv = tuple(argv) + if not argv: + raise ProxdomainError("refusing to run an empty command") + try: + completed = subprocess.run( + list(argv), + input=input_text, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=timeout, + check=False, + ) + except FileNotFoundError as exc: + raise ProxdomainError(f"command not found: {argv[0]}") from exc + except subprocess.TimeoutExpired as exc: + raise ProxdomainError(f"command timed out after {timeout}s: {' '.join(argv)}") from exc + return CommandResult( + argv=argv, + returncode=completed.returncode, + stdout=completed.stdout or "", + stderr=completed.stderr or "", + ) + + def write_text(self, path: str, content: str, mode: int = 0o644) -> bool: + target = Path(path) + current = self.read_text(path) + if current is not None and current == content: + return False + target.parent.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=str(target.parent)) + try: + with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle: + handle.write(content) + handle.flush() + os.fsync(handle.fileno()) + if os.name != "nt": + os.chmod(tmp, mode) + os.replace(tmp, target) + except BaseException: + with _suppress_errors(): + os.unlink(tmp) + raise + return True + + def read_text(self, path: str) -> str | None: + try: + return Path(path).read_text(encoding="utf-8") + except FileNotFoundError: + return None + except IsADirectoryError: + return None + except OSError as exc: + raise ProxdomainError(f"cannot read {path}: {exc}") from exc + + def remove(self, path: str) -> bool: + try: + os.unlink(path) + return True + except FileNotFoundError: + return False + except OSError as exc: + raise ProxdomainError(f"cannot remove {path}: {exc}") from exc + + def exists(self, path: str) -> bool: + return Path(path).exists() + + def mkdir(self, path: str) -> None: + Path(path).mkdir(parents=True, exist_ok=True) + + def describe(self) -> str: + return "local" + + +class SSHRunner: + """Runs commands and manages files on the Proxmox host through `ssh`. + + Uses non-interactive sudo (`sudo -n` by default) so a missing sudo grant fails + fast instead of hanging a cron job or systemd unit. + """ + + def __init__( + self, + host: str, + *, + port: int = 22, + identity_file: str = "", + ssh_options: Sequence[str] = (), + sudo: str = "sudo -n", + timeout: float = 120.0, + sleep=time.sleep, + ) -> None: + if not host: + raise ProxdomainError("webserver.ssh_host must not be empty") + self.host = host + self.port = port + self.identity_file = identity_file + self.ssh_options = tuple(ssh_options) + self.sudo = sudo.strip() + self.timeout = timeout + self._sleep = sleep + + # -- commands ------------------------------------------------------- + def run( + self, argv: Sequence[str], *, input_text: str | None = None, timeout: float = 120.0 + ) -> CommandResult: + argv = tuple(argv) + if not argv: + raise ProxdomainError("refusing to run an empty command") + remote = " ".join(shlex.quote(str(part)) for part in argv) + return self._ssh(remote, input_text=input_text, timeout=timeout) + + def _ssh( + self, remote_command: str, *, input_text: str | None = None, timeout: float = 120.0 + ) -> CommandResult: + argv = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10"] + if self.port != 22: + argv += ["-p", str(self.port)] + if self.identity_file: + argv += ["-i", self.identity_file] + for option in self.ssh_options: + argv += ["-o", option] + argv += [self.host, remote_command] + try: + completed = subprocess.run( + argv, + input=input_text, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=timeout, + check=False, + ) + except FileNotFoundError as exc: + raise ProxdomainError("ssh client not found on PATH") from exc + except subprocess.TimeoutExpired as exc: + raise ProxdomainError( + f"ssh to {self.host} timed out after {timeout}s: {remote_command[:200]}" + ) from exc + return CommandResult( + argv=tuple(argv), + returncode=completed.returncode, + stdout=completed.stdout or "", + stderr=completed.stderr or "", + ) + + # -- files ---------------------------------------------------------- + def write_text(self, path: str, content: str, mode: int = 0o644) -> bool: + if self.read_text(path) == content: + return False + directory = _posix_dirname(path) + tmp = f"{path}.proxdomain.tmp" + script = " && ".join( + [ + self._sudo(f"mkdir -p {shlex.quote(directory)}"), + self._sudo(f"tee {shlex.quote(tmp)} > /dev/null"), + self._sudo(f"chmod {mode:o} {shlex.quote(tmp)}"), + self._sudo(f"mv -f {shlex.quote(tmp)} {shlex.quote(path)}"), + ] + ) + result = self._ssh(script, input_text=content) + if not result.ok: + raise ProxdomainError( + f"cannot write {path} on {self.host}: {result.output()}" + ) + return True + + def read_text(self, path: str) -> str | None: + result = self._ssh(self._sudo(f"cat {shlex.quote(path)}")) + if not result.ok: + if "No such file" in result.stderr or "cannot open" in result.stderr: + return None + raise ProxdomainError(f"cannot read {path} on {self.host}: {result.output()}") + return result.stdout + + def remove(self, path: str) -> bool: + if not self.exists(path): + return False + result = self._ssh(self._sudo(f"rm -f {shlex.quote(path)}")) + if not result.ok: + raise ProxdomainError(f"cannot remove {path} on {self.host}: {result.output()}") + return True + + def exists(self, path: str) -> bool: + result = self._ssh(self._sudo(f"test -e {shlex.quote(path)}")) + return result.ok + + def mkdir(self, path: str) -> None: + result = self._ssh(self._sudo(f"mkdir -p {shlex.quote(path)}")) + if not result.ok: + raise ProxdomainError( + f"cannot create directory {path} on {self.host}: {result.output()}" + ) + + def describe(self) -> str: + return f"ssh://{self.host}" + + def _sudo(self, command: str) -> str: + return f"{self.sudo} {command}" if self.sudo else command + + +def build_runner(config) -> Runner: # config: WebServerConfig + if config.mode == "ssh": + return SSHRunner( + config.ssh_host, + port=config.ssh_port, + identity_file=config.ssh_identity_file, + ssh_options=config.ssh_options, + sudo=config.sudo, + ) + return LocalRunner() + + +def _posix_dirname(path: str) -> str: + trimmed = path.rstrip("/") + if "/" not in trimmed: + return "." + return trimmed.rsplit("/", 1)[0] or "/" + + +class _suppress_errors: + def __enter__(self) -> None: + return None + + def __exit__(self, *exc_info: object) -> bool: + return True diff --git a/proxdomain/service.py b/proxdomain/service.py new file mode 100755 index 0000000..20f4591 --- /dev/null +++ b/proxdomain/service.py @@ -0,0 +1,597 @@ +"""Orchestration: guest -> domain -> Cloudflare record -> reverse proxy config.""" + +from __future__ import annotations + +import ipaddress +import re +from dataclasses import dataclass, field + +from .cloudflare import CloudflareClient, Zone +from .config import Config +from .errors import ConfigError, ProxdomainError +from .proxmox import Guest, ProxmoxClient +from .runner import build_runner +from .state import Assignment, StateStore +from .webserver import FQDN_RE, SiteSpec, WebServerManager + +_HOSTNAME_STRIP = re.compile(r"[^a-z0-9]+") +_DASHES = re.compile(r"-{2,}") + + +@dataclass +class Step: + name: str + status: str # ok | changed | planned | warning | skipped | error + detail: str = "" + + +@dataclass +class ServiceReport: + action: str + steps: list[Step] = field(default_factory=list) + assignment: Assignment | None = None + + @property + def ok(self) -> bool: + return not any(step.status == "error" for step in self.steps) + + def add(self, name: str, status: str, detail: str = "") -> "ServiceReport": + self.steps.append(Step(name, status, detail)) + return self + + def fail(self, name: str, detail: str) -> "ServiceReport": + return self.add(name, "error", detail) + + def to_dict(self) -> dict: + return { + "action": self.action, + "ok": self.ok, + "steps": [step.__dict__ for step in self.steps], + "assignment": self.assignment.to_dict() if self.assignment else None, + } + + +class DomainService: + def __init__( + self, + config: Config, + *, + proxmox: ProxmoxClient | None = None, + cloudflare: CloudflareClient | None = None, + webserver: WebServerManager | None = None, + state: StateStore | None = None, + ) -> None: + self.config = config + self.state = state or StateStore( + config.state.path, + audit_path=config.state.resolved_audit_path(), + lock_timeout=config.state.lock_timeout, + ) + self.state.load() + self._proxmox = proxmox + self._cloudflare = cloudflare + self._webserver = webserver + + # -- lazy clients (so `list` works without API credentials) --------- + @property + def proxmox(self) -> ProxmoxClient: + if self._proxmox is None: + self._proxmox = ProxmoxClient(self.config.proxmox) + return self._proxmox + + @property + def cloudflare(self) -> CloudflareClient: + if self._cloudflare is None: + self._cloudflare = CloudflareClient(self.config.cloudflare) + return self._cloudflare + + @property + def webserver(self) -> WebServerManager: + if self._webserver is None: + self._webserver = WebServerManager( + self.config.webserver, build_runner(self.config.webserver) + ) + return self._webserver + + # -- main workflow -------------------------------------------------- + def assign( + self, + *, + vmid: int | None = None, + name: str | None = None, + subdomain: str | None = None, + port: int | None = None, + ip: str | None = None, + proxied: bool | None = None, + force: bool = False, + dry_run: bool = False, + ) -> ServiceReport: + report = ServiceReport("assign") + + try: + guest = self.proxmox.find_guest(vmid=vmid, name=name) + except ProxdomainError as exc: + return report.fail("guest", str(exc)) + report.add("guest", "ok", guest.label) + if not guest.is_running: + report.add("guest", "warning", "guest is not running; the proxy target may be down") + + try: + fqdn = self._resolve_fqdn(guest, subdomain) + except ProxdomainError as exc: + return report.fail("domain", str(exc)) + + try: + address = ip or self.proxmox.guest_ip(guest) + except ProxdomainError as exc: + return report.fail("address", str(exc)) + if not 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) + 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'})") + report.add("domain", "ok", fqdn) + + target_port = int(port or self.config.general.default_port) + if not 1 <= target_port <= 65535: + return report.fail("port", f"{target_port} is not a valid TCP port") + + existing = self.state.get(fqdn) + if existing is not None and existing.vmid != guest.vmid and not force: + return report.fail( + "state", + f"{fqdn} is already assigned to {existing.kind} {existing.vmid}; " + "pass --force to take it over", + ) + + zone = self._find_zone(report, fqdn, dry_run=dry_run) + if zone is None and not dry_run: + return report + + effective_proxied = self.config.cloudflare.proxied if proxied is None else proxied + proxy_note = "" + if effective_proxied and not parsed_ip.is_global: + effective_proxied = False + proxy_note = ( + f"{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) + try: + applied = self.webserver.apply(spec, dry_run=dry_run) + except ProxdomainError as exc: + return report.fail("web-config", str(exc)) + if dry_run: + status = "planned" + elif applied.changed: + status = "changed" + else: + status = "ok" + report.add( + "web-config", + status, + "; ".join(applied.messages) or applied.path, + ) + if proxy_note: + report.add("dns", "warning", proxy_note) + + assignment = existing or Assignment( + fqdn=fqdn, vmid=guest.vmid, node=guest.node, kind=guest.kind + ) + assignment.name = guest.name + assignment.vmid = guest.vmid + assignment.ip = address + assignment.port = target_port + assignment.node = guest.node + assignment.kind = guest.kind + assignment.webserver = self.config.webserver.kind + assignment.site_file = applied.path + if zone is not None: + assignment.zone_id = zone.id + assignment.zone_name = zone.name + + record_type = "A" if parsed_ip.version == 4 else "AAAA" + if not dry_run: + self._save(assignment) + self.state.audit( + "assign.web-config", + fqdn=fqdn, + vmid=guest.vmid, + address=address, + port=target_port, + path=applied.path, + ) + + if zone is None: + report.add("dns", "skipped", "no zone resolved; DNS not touched in this dry run") + report.assignment = assignment + return report + + if dry_run: + self._preview_dns(report, zone, fqdn, 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 + + assignment.record_type = upsert.record.type or record_type + assignment.record_id = upsert.record.id + self._save(assignment) + self.state.audit( + "assign.dns", + fqdn=fqdn, + record_id=upsert.record.id, + action=upsert.action, + content=address, + proxied=effective_proxied, + ) + report.add( + "dns", + "changed" if upsert.changed else "ok", + f"{upsert.action} {record_type} {fqdn} -> {address} " + f"(proxied={'yes' if effective_proxied else 'no'})", + ) + report.add("result", "ok", f"{fqdn} -> {spec.target}") + report.assignment = assignment + return report + + def remove( + self, + *, + fqdn: str | None = None, + vmid: int | None = None, + confirm: bool = False, + dry_run: bool = False, + ) -> ServiceReport: + report = ServiceReport("remove") + if not fqdn and vmid is None: + return report.fail("state", "specify --fqdn or --vmid") + if vmid is not None and not fqdn: + matches = self.state.find(vmid=vmid) + if len(matches) > 1: + listing = ", ".join(item.fqdn for item in matches) + return report.fail("state", f"vmid {vmid} has several assignments: {listing}") + else: + matches = self.state.find(fqdn=fqdn) + if not matches: + target = fqdn or f"vmid {vmid}" + return report.fail("state", f"no managed assignment found for {target}") + assignment = matches[0] + report.add( + "state", + "ok", + f"{assignment.fqdn} -> {assignment.kind} {assignment.vmid} on {assignment.node}", + ) + + if not confirm and not dry_run: + return report.fail( + "confirm", + f"this deletes the DNS record and proxy config for {assignment.fqdn}; " + "re-run with --yes to proceed", + ) + + try: + result = self.webserver.remove(assignment.fqdn, dry_run=dry_run) + except ProxdomainError as exc: + return report.fail("web-config", str(exc)) + report.add( + "web-config", + "planned" if dry_run else ("changed" if result.changed else "ok"), + "; ".join(result.messages) or assignment.site_file, + ) + + if not assignment.has_dns_record: + report.add("dns", "skipped", "no Cloudflare record id recorded for this assignment") + elif dry_run: + report.add( + "dns", + "planned", + f"would delete {assignment.record_type} {assignment.fqdn} " + f"(zone {assignment.zone_name or assignment.zone_id})", + ) + else: + try: + self.cloudflare.delete_record(assignment.zone_id, assignment.record_id or "") + except ProxdomainError as exc: + report.fail("dns", str(exc)) + report.add( + "result", + "warning", + "the proxy config was removed but the assignment is kept in state; " + "fix the DNS error and re-run remove", + ) + return report + report.add( + "dns", + "changed", + f"deleted {assignment.record_type} {assignment.fqdn}", + ) + assignment.record_id = None + + if not dry_run: + with self.state.locked(): + self.state.load() + self.state.remove(assignment.fqdn) + self.state.flush() + self.state.audit("remove", fqdn=assignment.fqdn, vmid=assignment.vmid) + report.add( + "result", + "planned" if dry_run else "ok", + f"{assignment.fqdn} is no longer managed", + ) + return report + + def sync(self, *, dry_run: bool = False) -> ServiceReport: + report = ServiceReport("sync") + assignments = self.state.all() + if not assignments: + return report.add("state", "ok", "no assignments to sync") + changed = 0 + for assignment in assignments: + try: + guest = self.proxmox.find_guest(vmid=assignment.vmid) + except ProxdomainError as exc: + report.add("guest", "warning", f"{assignment.fqdn}: {exc}") + continue + try: + 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: + report.add("guest", "warning", f"{assignment.fqdn}: guest has no IP") + continue + spec = self._site_spec(guest, assignment.fqdn, address, assignment.port) + try: + result = self.webserver.apply(spec, dry_run=dry_run) + except ProxdomainError as exc: + report.fail("web-config", f"{assignment.fqdn}: {exc}") + continue + if result.changed: + changed += 1 + report.add( + "web-config", + "planned" if dry_run else ("changed" if result.changed else "ok"), + f"{assignment.fqdn}: {'; '.join(result.messages) or 'up to date'}", + ) + + if dry_run or not assignment.zone_id: + continue + try: + upsert = self.cloudflare.upsert_address_record( + assignment.zone_id, assignment.fqdn, address + ) + except ProxdomainError as exc: + report.fail("dns", f"{assignment.fqdn}: {exc}") + continue + assignment.ip = address + 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}") + self._save(assignment) + + report.add( + "result", + "planned" if dry_run else "ok", + f"{len(assignments)} assignment(s) checked, {changed} change(s)", + ) + return report + + # -- discovery / diagnostics --------------------------------------- + def watch_candidates( + self, *, tag: str | None = None, require_running: bool = True + ) -> list[Guest]: + wanted_tag = self.config.watch.tag if tag is None else tag + tracked = {item.vmid for item in self.state.all()} + candidates = [] + for guest in self.proxmox.list_guests(): + if guest.vmid in tracked: + continue + if wanted_tag and wanted_tag not in guest.tags: + continue + if require_running and not guest.is_running: + continue + candidates.append(guest) + return candidates + + def doctor(self) -> ServiceReport: + report = ServiceReport("doctor") + if self.config.source is not None: + report.add("config", "ok", str(self.config.source)) + + try: + guests = self.proxmox.list_guests() + report.add( + "proxmox", + "ok", + f"{len(guests)} guest(s) visible via {self.config.proxmox.api_url}", + ) + except (ProxdomainError, ConfigError) as exc: + report.fail( + "proxmox", + f"{exc} (the token needs at least VM.Audit on /vms)", + ) + + try: + status = self.cloudflare.verify_token() + zones = self.cloudflare.list_zones() + names = ", ".join(zone.name for zone in zones[:5]) or "none" + report.add("cloudflare", "ok", f"token {status}; {len(zones)} zone(s): {names}") + except (ProxdomainError, ConfigError) as exc: + report.fail( + "cloudflare", + f"{exc} (the token needs Zone:Read and DNS:Edit)", + ) + + report.add( + "web-server", + "ok", + f"{self.config.webserver.kind} via {self.webserver.runner.describe()}, " + f"managed dir {self.config.webserver.manage_dir}", + ) + try: + present = self.webserver.runner.exists(self.config.webserver.manage_dir) + report.add( + "web-server", + "ok" if present else "warning", + "managed directory exists" + if present + else "managed directory is missing; run `proxdomain init`", + ) + except ProxdomainError as exc: + report.fail("web-server", str(exc)) + + try: + validated = self.webserver.validate() + report.add( + "web-server", + "ok" if validated else "skipped", + "configuration test passed" + if validated + else "no test command configured for this web server", + ) + except ProxdomainError as exc: + report.fail("web-server", str(exc)) + + 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)) + return report + + def init(self, *, dry_run: bool = False) -> ServiceReport: + report = ServiceReport("init") + try: + steps = self.webserver.bootstrap(dry_run=dry_run) + except ProxdomainError as exc: + return report.fail("bootstrap", str(exc)) + for status, detail in steps: + report.add("bootstrap", status, detail) + report.add( + "result", + "planned" if dry_run else "ok", + "bootstrap finished" if not dry_run else "dry run: nothing was changed", + ) + return report + + # -- internals ------------------------------------------------------ + def _resolve_fqdn(self, guest: Guest, subdomain: str | None) -> str: + if subdomain and subdomain.strip(): + value = subdomain.strip().lower().rstrip(".") + if "." in value: + fqdn = value + else: + fqdn = f"{value}.{self.config.general.base_domain}" + else: + hostname = sanitize_hostname(guest.name, guest.vmid) + try: + fqdn = self.config.general.domain_template.format( + hostname=hostname, + vmid=guest.vmid, + node=guest.node, + kind=guest.kind, + base_domain=self.config.general.base_domain, + ) + except KeyError as exc: + raise ProxdomainError( + f"general.domain_template uses an unknown placeholder {exc}" + ) from exc + fqdn = fqdn.strip().lower().rstrip(".") + if not FQDN_RE.match(fqdn): + raise ProxdomainError(f"{fqdn!r} is not a valid DNS name") + return fqdn + + def _site_spec( + self, guest: Guest, fqdn: str, address: str, port: int + ) -> SiteSpec: + return SiteSpec( + fqdn=fqdn, + address=address, + port=port, + vmid=guest.vmid, + node=guest.node, + kind=guest.kind, + webserver=self.config.webserver.kind, + tls_mode=self.config.webserver.tls.mode, + cert_dir=self.config.webserver.tls.cert_dir, + webroot=self.config.webserver.tls.webroot, + cert_resolver=self.config.webserver.cert_resolver, + ) + + def _find_zone( + self, report: ServiceReport, fqdn: str, *, dry_run: bool + ) -> Zone | None: + try: + zone = self.cloudflare.find_zone(fqdn, self.config.general.base_domain) + except (ProxdomainError, ConfigError) as exc: + if dry_run: + report.add("zone", "warning", f"{exc} (dry run: skipping DNS preview)") + return None + report.fail("zone", str(exc)) + return None + report.add("zone", "ok", f"{zone.name} ({zone.id})") + return zone + + def _preview_dns( + self, + report: ServiceReport, + zone: Zone, + fqdn: str, + address: str, + record_type: str, + proxied: bool, + ) -> None: + try: + records = self.cloudflare.list_records(zone.id, name=fqdn, rtype=record_type) + except ProxdomainError as exc: + report.add("dns", "warning", f"could not preview the record: {exc}") + return + action = "create" if not records else ( + "keep" if records[0].content == address and records[0].proxied == proxied else "update" + ) + report.add( + "dns", + "planned", + f"would {action} {record_type} {fqdn} -> {address} " + f"(proxied={'yes' if proxied else 'no'})", + ) + + def _save(self, assignment: Assignment) -> None: + with self.state.locked(): + self.state.load() + self.state.upsert(assignment) + self.state.flush() + + +def sanitize_hostname(name: str, vmid: int) -> str: + value = _HOSTNAME_STRIP.sub("-", (name or "").strip().lower()).strip("-") + value = _DASHES.sub("-", value) + value = value[:40].strip("-") + return value or f"vm{vmid}" diff --git a/proxdomain/state.py b/proxdomain/state.py new file mode 100755 index 0000000..bc700cf --- /dev/null +++ b/proxdomain/state.py @@ -0,0 +1,240 @@ +"""Persistent assignment state plus an append-only audit log.""" + +from __future__ import annotations + +import json +import os +import time +from contextlib import contextmanager +from dataclasses import asdict, dataclass, field +from datetime import datetime, timezone +from pathlib import Path +from typing import Iterator + +from .errors import ProxdomainError + +STATE_VERSION = 1 + + +def utcnow() -> str: + return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z") + + +@dataclass +class Assignment: + fqdn: str + vmid: int + node: str + kind: str + name: str = "" + ip: str = "" + port: int = 80 + webserver: str = "" + zone_id: str = "" + zone_name: str = "" + record_type: str = "" + record_id: str | None = None + site_file: str = "" + created_at: str = "" + updated_at: str = "" + extra: dict = field(default_factory=dict) + + @classmethod + def from_dict(cls, payload: dict) -> "Assignment": + try: + fqdn = str(payload["fqdn"]) + vmid = int(payload["vmid"]) + node = str(payload["node"]) + kind = str(payload["kind"]) + except (KeyError, TypeError, ValueError) as exc: + raise ProxdomainError(f"corrupt assignment entry in state file: {exc}") from exc + return cls( + fqdn=fqdn, + vmid=vmid, + node=node, + kind=kind, + name=str(payload.get("name") or ""), + ip=str(payload.get("ip") or ""), + port=int(payload.get("port") or 80), + webserver=str(payload.get("webserver") or ""), + zone_id=str(payload.get("zone_id") or ""), + zone_name=str(payload.get("zone_name") or ""), + record_type=str(payload.get("record_type") or ""), + record_id=(str(payload["record_id"]) if payload.get("record_id") else None), + site_file=str(payload.get("site_file") or ""), + created_at=str(payload.get("created_at") or ""), + updated_at=str(payload.get("updated_at") or ""), + extra=dict(payload.get("extra") or {}), + ) + + def to_dict(self) -> dict: + return asdict(self) + + @property + def has_dns_record(self) -> bool: + return bool(self.record_id and self.zone_id) + + +class StateStore: + def __init__( + self, + path: str, + *, + audit_path: str | None = None, + lock_timeout: float = 10.0, + ) -> None: + self.path = path + self.audit_path = audit_path + self.lock_timeout = lock_timeout + self._items: dict[str, Assignment] = {} + self._loaded = False + + # -- persistence ---------------------------------------------------- + @property + def memory_only(self) -> bool: + return self.path == ":memory:" + + def load(self) -> dict[str, Assignment]: + if self.memory_only: + self._loaded = True + return self._items + file = Path(self.path) + if not file.exists(): + self._items = {} + self._loaded = True + return self._items + try: + payload = json.loads(file.read_text(encoding="utf-8") or "{}") + except (OSError, json.JSONDecodeError) as exc: + raise ProxdomainError( + f"cannot read state file {self.path}: {exc}; " + "fix or move it aside before retrying" + ) from exc + if not isinstance(payload, dict): + raise ProxdomainError(f"state file {self.path} has an unexpected format") + version = payload.get("version") + if version not in (None, STATE_VERSION): + raise ProxdomainError( + f"state file {self.path} uses version {version}, this build expects {STATE_VERSION}" + ) + rows = payload.get("assignments") or {} + if not isinstance(rows, dict): + raise ProxdomainError(f"state file {self.path} has no assignments table") + self._items = {name: Assignment.from_dict(row) for name, row in rows.items()} + self._loaded = True + return self._items + + def flush(self) -> None: + if self.memory_only: + return + if not self._loaded: + self.load() + file = Path(self.path) + file.parent.mkdir(parents=True, exist_ok=True) + payload = { + "version": STATE_VERSION, + "updated_at": utcnow(), + "assignments": { + name: item.to_dict() for name, item in sorted(self._items.items()) + }, + } + tmp = file.with_name(f".{file.name}.tmp") + tmp.write_text(json.dumps(payload, indent=2, sort_keys=False) + "\n", encoding="utf-8") + os.replace(tmp, file) + + # -- accessors ------------------------------------------------------ + def all(self) -> list[Assignment]: + if not self._loaded: + self.load() + return sorted(self._items.values(), key=lambda item: item.fqdn) + + def get(self, fqdn: str) -> Assignment | None: + if not self._loaded: + self.load() + return self._items.get(fqdn.lower()) + + def find(self, *, fqdn: str | None = None, vmid: int | None = None) -> list[Assignment]: + items = self.all() + if fqdn: + return [item for item in items if item.fqdn == fqdn.lower().strip()] + if vmid is not None: + return [item for item in items if item.vmid == vmid] + return [] + + def upsert(self, assignment: Assignment) -> Assignment: + if not self._loaded: + self.load() + key = assignment.fqdn.lower() + now = utcnow() + current = self._items.get(key) + if current is not None and not assignment.created_at: + assignment.created_at = current.created_at + if not assignment.created_at: + assignment.created_at = now + assignment.fqdn = key + assignment.updated_at = now + self._items[key] = assignment + return assignment + + def remove(self, fqdn: str) -> bool: + if not self._loaded: + self.load() + return self._items.pop(fqdn.lower(), None) is not None + + # -- audit ---------------------------------------------------------- + def audit(self, event: str, **fields: object) -> None: + if not self.audit_path: + return + path = Path(self.audit_path) + path.parent.mkdir(parents=True, exist_ok=True) + record = {"ts": utcnow(), "event": event, **fields} + with path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(record, default=str) + "\n") + + # -- locking -------------------------------------------------------- + @contextmanager + def locked(self) -> Iterator[None]: + if self.memory_only: + yield + return + path = Path(self.path) + path.parent.mkdir(parents=True, exist_ok=True) + lock_path = path.with_name(path.name + ".lock") + deadline = time.monotonic() + self.lock_timeout + fd: int | None = None + while True: + try: + fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY) + os.write(fd, str(os.getpid()).encode("ascii", "ignore")) + break + except FileExistsError: + if _is_stale(lock_path, self.lock_timeout): + _try_unlink(lock_path) + continue + if time.monotonic() >= deadline: + raise ProxdomainError( + f"state file is locked by another proxdomain run ({lock_path}); " + "wait for it to finish or delete the lock file if it is stale" + ) + time.sleep(0.1) + try: + yield + finally: + if fd is not None: + os.close(fd) + _try_unlink(lock_path) + + +def _is_stale(lock_path: Path, lock_timeout: float) -> bool: + try: + age = time.time() - lock_path.stat().st_mtime + except OSError: + return False + return age > max(60.0, lock_timeout * 6) + + +def _try_unlink(path: Path) -> None: + try: + path.unlink() + except OSError: + pass diff --git a/proxdomain/webserver.py b/proxdomain/webserver.py new file mode 100755 index 0000000..88ec03e --- /dev/null +++ b/proxdomain/webserver.py @@ -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}(? 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 diff --git a/pyproject.toml b/pyproject.toml new file mode 100755 index 0000000..8f3bfa2 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,26 @@ +[build-system] +requires = ["setuptools>=68"] +build-backend = "setuptools.build_meta" + +[project] +name = "proxdomain" +version = "0.1.0" +description = "Assign public domains to Proxmox VMs/containers via Cloudflare DNS and a reverse proxy on the PVE host" +readme = "README.md" +requires-python = ">=3.11" +license = { text = "MIT" } +authors = [{ name = "proxdomain contributors" }] +keywords = ["proxmox", "cloudflare", "dns", "reverse-proxy", "nginx", "homelab"] +classifiers = [ + "Environment :: Console", + "Intended Audience :: System Administrators", + "Programming Language :: Python :: 3 :: Only", + "Topic :: System :: Systems Administration", +] +dependencies = [] + +[project.scripts] +proxdomain = "proxdomain.cli:main" + +[tool.setuptools.packages.find] +include = ["proxdomain*"] diff --git a/run_tests.py b/run_tests.py new file mode 100755 index 0000000..b1ccddc --- /dev/null +++ b/run_tests.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Run the proxdomain test suite. + +Mirrors a compact summary (and failure details) into $GITHUB_STEP_SUMMARY when +present, and emits ::error:: annotations, so CI failures are readable even when +the job log API is unavailable. +""" + +from __future__ import annotations + +import os +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +sys.path.insert(0, str(ROOT)) + + +def main() -> int: + suite = unittest.TestLoader().discover(str(ROOT / "tests"), top_level_dir=str(ROOT)) + result = unittest.TextTestRunner(verbosity=2).run(suite) + + total = result.testsRun + failures = len(result.failures) + errors = len(result.errors) + skipped = len(result.skipped) + summary = ( + f"{total} tests, {failures} failures, {errors} errors, {skipped} skipped " + f"({'PASS' if result.wasSuccessful() else 'FAIL'})" + ) + print() + print(summary) + _write_ci_summary(summary, result) + return 0 if result.wasSuccessful() else 1 + + +def _write_ci_summary(summary: str, result: unittest.TestResult) -> None: + for test, trace in result.failures + result.errors: + label = test.id().split(".")[-1] + first_line = next( + (line for line in reversed(trace.strip().splitlines()) if line.strip()), "failed" + ) + print(f"::error title={label}::{first_line}") + + path = os.environ.get("GITHUB_STEP_SUMMARY") + if not path: + return + try: + with open(path, "a", encoding="utf-8") as handle: + handle.write("## proxdomain tests\n\n") + handle.write(f"`{summary}`\n\n") + for test, trace in result.failures + result.errors: + handle.write(f"### {test.id()}\n\n```text\n{trace.strip()}\n```\n\n") + except OSError as exc: # pragma: no cover - CI convenience only + print(f"warning: cannot write step summary: {exc}", file=sys.stderr) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100755 index 0000000..7a12279 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""Test package for proxdomain.""" diff --git a/tests/support.py b/tests/support.py new file mode 100755 index 0000000..96e1824 --- /dev/null +++ b/tests/support.py @@ -0,0 +1,271 @@ +"""Shared test doubles: an in-memory HTTP transport and file/command runner.""" + +from __future__ import annotations + +import json +import urllib.parse +from dataclasses import dataclass +from typing import Any, Callable + +from proxdomain.config import Config, parse_config +from proxdomain.http import Response +from proxdomain.runner import CommandResult + + +@dataclass +class Call: + method: str + url: str + path: str + query: dict[str, list[str]] + body: Any + + def param(self, name: str, default: str | None = None) -> str | None: + values = self.query.get(name) + return values[0] if values else default + + +@dataclass +class Route: + method: str + path: str + handler: Callable[[Call], Any] | Any + status: int = 200 + + +class FakeTransport: + def __init__(self) -> None: + self.routes: list[Route] = [] + self.calls: list[Call] = [] + + def add(self, method: str, path: str, response: Any, *, status: int = 200) -> "FakeTransport": + self.routes.append(Route(method.upper(), path, response, status)) + return self + + # -- Transport protocol -------------------------------------------- + def request(self, method, url, headers, body, timeout) -> Response: + split = urllib.parse.urlsplit(url) + call = Call( + method=method, + url=url, + path=split.path, + query=urllib.parse.parse_qs(split.query), + body=json.loads(body.decode("utf-8")) if body else None, + ) + self.calls.append(call) + for route in reversed(self.routes): + if route.method == method and route.path == split.path: + payload = route.handler(call) if callable(route.handler) else route.handler + status = route.status + if isinstance(payload, tuple) and len(payload) == 2: + status, payload = payload + return Response( + status=status, + body=json.dumps(payload).encode("utf-8"), + headers={"content-type": "application/json"}, + ) + return Response( + status=404, + body=json.dumps( + {"success": False, "errors": [{"code": 0, "message": "no route in fake"}]} + ).encode("utf-8"), + headers={"content-type": "application/json"}, + ) + + # -- helpers -------------------------------------------------------- + def calls_to(self, method: str, path: str) -> list[Call]: + return [c for c in self.calls if c.method == method and c.path == path] + + def count(self, method: str, path: str) -> int: + return len(self.calls_to(method, path)) + + +def cf(payload: Any) -> dict: + return {"success": True, "errors": [], "result": payload} + + +def pve(payload: Any) -> dict: + return {"data": payload} + + +class FakeRunner: + """In-memory stand-in for LocalRunner/SSHRunner.""" + + def __init__( + self, + files: dict[str, str] | None = None, + *, + failures: list[tuple[str, int, str]] | None = None, + ) -> None: + self.files = dict(files or {}) + self.dirs: set[str] = set() + self.commands: list[tuple[str, ...]] = [] + self.failures = list(failures or []) + + def run(self, argv, *, input_text=None, timeout: float = 120.0) -> CommandResult: + argv = tuple(argv) + self.commands.append(argv) + joined = " ".join(argv) + for needle, code, stderr in self.failures: + if needle in joined: + return CommandResult(argv, code, "", stderr) + if argv and argv[0] == "grep": + return self._grep(argv) + return CommandResult(argv, 0, "ok", "") + + def _grep(self, argv: tuple[str, ...]) -> CommandResult: + needle = argv[-2] + directory = argv[-1].rstrip("/") + prefix = directory + "/" + for path, content in self.files.items(): + if path.startswith(prefix) and "/" not in path[len(prefix):] and needle in content: + return CommandResult(argv, 0, path, "") + return CommandResult(argv, 1, "", "no match") + + def write_text(self, path: str, content: str, mode: int = 0o644) -> bool: + current = self.files.get(path) + if current == content: + return False + self.files[path] = content + return True + + def read_text(self, path: str) -> str | None: + return self.files.get(path) + + def remove(self, path: str) -> bool: + return self.files.pop(path, None) is not None + + def exists(self, path: str) -> bool: + path = path.rstrip("/") + return path in self.files or path in self.dirs or any( + name.startswith(path + "/") for name in self.files + ) + + def mkdir(self, path: str) -> None: + self.dirs.add(path.rstrip("/")) + + def describe(self) -> str: + return "fake" + + +def make_config( + *, + proxmox: dict[str, Any] | None = None, + general: dict[str, Any] | None = None, + cloudflare: dict[str, Any] | None = None, + state: dict[str, Any] | None = None, + **webserver: Any, +) -> Config: + raw: dict[str, Any] = { + "general": {"base_domain": "example.com"}, + "proxmox": { + "api_url": "https://pve.example.com:8006/api2/json", + "token_id": "automation@pve!proxdomain", + "token_secret": "pve-secret", + }, + "cloudflare": {"api_token": "cf-token", "proxied": True}, + "webserver": { + "kind": "nginx", + "mode": "local", + }, + "state": {"path": ":memory:"}, + } + for section, values in ( + ("general", general), + ("proxmox", proxmox), + ("cloudflare", cloudflare), + ("state", state), + ): + if values: + raw[section].update(values) + raw["webserver"].update(webserver) + return parse_config(raw) + + +def add_proxmox_routes( + transport: FakeTransport, + *, + guests: list[dict] | None = None, + agent_ips: list[str] | None = None, + node: str = "pve", +) -> None: + transport.add( + "GET", + "/api2/json/cluster/resources", + pve(guests if guests is not None else []), + ) + if agent_ips is not None: + transport.add( + "GET", + f"/api2/json/nodes/{node}/qemu/101/agent/network-get-interfaces", + pve( + { + "result": [ + { + "name": "eth0", + "ip-addresses": [ + {"ip-address": ip, "ip-address-type": "ipv4"} + for ip in agent_ips + ], + } + ] + } + ), + ) + transport.add( + "GET", + f"/api2/json/nodes/{node}/qemu/101/config", + pve({}), + ) + + +def add_cloudflare_routes( + transport: FakeTransport, + *, + zone_id: str = "zone-1", + zone_name: str = "example.com", + existing: list[dict] | None = None, +) -> FakeTransport: + transport.add("GET", "/client/v4/zones", cf([{"id": zone_id, "name": zone_name}])) + transport.add( + "GET", + f"/client/v4/zones/{zone_id}/dns_records", + cf(list(existing or [])), + ) + + def create(call: Call): + return cf( + { + "id": "rec-created", + "name": call.body["name"], + "type": call.body["type"], + "content": call.body["content"], + "proxied": call.body.get("proxied", False), + "ttl": call.body.get("ttl", 1), + } + ) + + def update(call: Call): + return cf( + { + "id": call.path.rsplit("/", 1)[-1], + "name": call.body["name"], + "type": call.body["type"], + "content": call.body["content"], + "proxied": call.body.get("proxied", False), + "ttl": call.body.get("ttl", 1), + } + ) + + transport.add("POST", f"/client/v4/zones/{zone_id}/dns_records", create) + for record in existing or []: + transport.add( + "PATCH", f"/client/v4/zones/{zone_id}/dns_records/{record['id']}", update + ) + transport.add( + "DELETE", + f"/client/v4/zones/{zone_id}/dns_records/{record['id']}", + cf({"id": record["id"]}), + ) + transport.add("DELETE", f"/client/v4/zones/{zone_id}/dns_records/rec-created", cf({"id": "rec-created"})) + return transport diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100755 index 0000000..66d6c26 --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,131 @@ +"""CLI wiring: parsing, exit codes and table/JSON output.""" + +from __future__ import annotations + +import contextlib +import io +import json +import tempfile +import unittest +from pathlib import Path + +from proxdomain.cli import build_parser, main + +CONFIG_TEMPLATE = """ +[general] +base_domain = "example.com" + +[proxmox] +api_url = "https://pve.example.com:8006/api2/json" +token_id = "automation@pve!proxdomain" +token_secret = "secret" + +[cloudflare] +api_token = "cf-token" + +[state] +path = "{state}" +""" + + +def write_config(directory: str) -> Path: + state = Path(directory) / "state.json" + config = Path(directory) / "proxdomain.toml" + config.write_text(CONFIG_TEMPLATE.format(state=state.as_posix()), encoding="utf-8") + return config + + +def write_state(directory: str) -> Path: + state = Path(directory) / "state.json" + state.write_text( + json.dumps( + { + "version": 1, + "assignments": { + "web01.example.com": { + "fqdn": "web01.example.com", + "vmid": 101, + "node": "pve", + "kind": "qemu", + "name": "web01", + "ip": "10.0.0.5", + "port": 80, + "record_id": "rec-1", + } + }, + } + ), + encoding="utf-8", + ) + return state + + +class CliTests(unittest.TestCase): + def test_version(self) -> None: + with contextlib.redirect_stdout(io.StringIO()) as out: + with self.assertRaises(SystemExit) as ctx: + main(["--version"]) + self.assertEqual(ctx.exception.code, 0) + self.assertIn("proxdomain", out.getvalue()) + + def test_no_command_prints_help(self) -> None: + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(main([]), 2) + + def test_missing_config(self) -> None: + with contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(main(["list", "-c", "/nonexistent/proxdomain.toml"]), 2) + + def test_list_empty(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + config = write_config(tmp) + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertEqual(main(["list", "-c", str(config)]), 0) + self.assertIn("no managed domains", out.getvalue()) + + def test_list_json(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + config = write_config(tmp) + write_state(tmp) + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertEqual(main(["list", "-c", str(config), "--json"]), 0) + payload = json.loads(out.getvalue()) + self.assertEqual(payload[0]["fqdn"], "web01.example.com") + + def test_list_table(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + config = write_config(tmp) + write_state(tmp) + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertEqual(main(["list", "-c", str(config)]), 0) + text = out.getvalue() + self.assertIn("FQDN", text) + self.assertIn("web01.example.com", text) + self.assertIn("10.0.0.5", text) + + def test_remove_without_assignment_fails(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + config = write_config(tmp) + with contextlib.redirect_stdout(io.StringIO()) as out: + code = main(["remove", "--fqdn", "nope.example.com", "--yes", "-c", str(config)]) + self.assertEqual(code, 1) + self.assertIn("FAILED", out.getvalue()) + + def test_parser_requires_a_target(self) -> None: + parser = build_parser() + with contextlib.redirect_stderr(io.StringIO()): + with self.assertRaises(SystemExit): + parser.parse_args(["assign"]) + + def test_global_option_before_and_after_subcommand(self) -> None: + parser = build_parser() + with tempfile.TemporaryDirectory() as tmp: + config = write_config(tmp) + before = parser.parse_args(["-c", str(config), "list"]) + after = parser.parse_args(["list", "-c", str(config)]) + self.assertEqual(before.config, str(config)) + self.assertEqual(after.config, str(config)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_cloudflare.py b/tests/test_cloudflare.py new file mode 100755 index 0000000..45c8a21 --- /dev/null +++ b/tests/test_cloudflare.py @@ -0,0 +1,178 @@ +"""Cloudflare zone discovery and DNS record upserts.""" + +from __future__ import annotations + +import unittest + +from proxdomain.cloudflare import CloudflareClient +from proxdomain.errors import ProxdomainError +from tests.support import FakeTransport, cf, make_config + + +def client(transport: FakeTransport, **cloudflare) -> CloudflareClient: + config = make_config(cloudflare=cloudflare or None) + return CloudflareClient(config.cloudflare, transport=transport) + + +class ZoneTests(unittest.TestCase): + def test_base_domain_zone(self) -> None: + transport = FakeTransport() + transport.add("GET", "/client/v4/zones", cf([{"id": "z1", "name": "example.com"}])) + zone = client(transport).find_zone("web01.example.com", "example.com") + self.assertEqual(zone.id, "z1") + self.assertEqual(transport.calls[0].param("name"), "example.com") + + def test_suffix_walk_when_base_domain_does_not_match(self) -> None: + transport = FakeTransport() + transport.add( + "GET", + "/client/v4/zones", + lambda call: cf([{"id": "z2", "name": "example.com"}]) + if call.param("name") == "example.com" + else cf([]), + ) + zone = client(transport, api_token="t").find_zone("app.example.com", "other.com") + self.assertEqual(zone.name, "example.com") + + def test_zone_lookup_is_cached(self) -> None: + transport = FakeTransport() + transport.add("GET", "/client/v4/zones", cf([{"id": "z1", "name": "example.com"}])) + cf_client = client(transport) + cf_client.find_zone("a.example.com", "example.com") + cf_client.find_zone("b.example.com", "example.com") + self.assertEqual(len(transport.calls), 1) + + def test_missing_zone(self) -> None: + transport = FakeTransport() + transport.add("GET", "/client/v4/zones", cf([])) + with self.assertRaises(ProxdomainError) as ctx: + client(transport).find_zone("a.example.com", "example.com") + self.assertIn("no Cloudflare zone", str(ctx.exception)) + + def test_verify_token(self) -> None: + transport = FakeTransport() + transport.add("GET", "/client/v4/user/tokens/verify", cf({"status": "active"})) + self.assertEqual(client(transport).verify_token(), "active") + + +class RecordTests(unittest.TestCase): + def test_create_a_record(self) -> None: + transport = FakeTransport() + transport.add("GET", "/client/v4/zones", cf([{"id": "z1", "name": "example.com"}])) + transport.add("GET", "/client/v4/zones/z1/dns_records", cf([])) + transport.add( + "POST", + "/client/v4/zones/z1/dns_records", + lambda call: cf({"id": "new", **call.body}), + ) + result = client(transport).upsert_address_record("z1", "web01.example.com", "10.0.0.5") + self.assertEqual(result.action, "created") + self.assertEqual(result.record.id, "new") + body = transport.calls_to("POST", "/client/v4/zones/z1/dns_records")[0].body + self.assertEqual(body["type"], "A") + self.assertEqual(body["content"], "10.0.0.5") + self.assertTrue(body["proxied"]) + self.assertEqual(body["ttl"], 1) + self.assertEqual(body["comment"], "managed by proxdomain") + + def test_aaaa_for_ipv6(self) -> None: + transport = FakeTransport() + transport.add("GET", "/client/v4/zones/z1/dns_records", cf([])) + transport.add( + "POST", + "/client/v4/zones/z1/dns_records", + lambda call: cf({"id": "new", **call.body}), + ) + result = client(transport).upsert_address_record("z1", "v6.example.com", "2001:db8::5") + self.assertEqual(result.record.type, "AAAA") + + def test_unchanged_record_is_not_written(self) -> None: + existing = [ + { + "id": "r1", + "name": "web01.example.com", + "type": "A", + "content": "10.0.0.5", + "proxied": True, + "ttl": 1, + } + ] + transport = FakeTransport() + transport.add("GET", "/client/v4/zones/z1/dns_records", cf(existing)) + transport.add("PATCH", "/client/v4/zones/z1/dns_records/r1", cf({"id": "r1"})) + result = client(transport).upsert_address_record("z1", "web01.example.com", "10.0.0.5") + self.assertEqual(result.action, "unchanged") + self.assertEqual(transport.count("PATCH", "/client/v4/zones/z1/dns_records/r1"), 0) + self.assertEqual(transport.count("POST", "/client/v4/zones/z1/dns_records"), 0) + + def test_update_when_address_changes(self) -> None: + existing = [ + { + "id": "r1", + "name": "web01.example.com", + "type": "A", + "content": "10.0.0.4", + "proxied": True, + "ttl": 1, + } + ] + transport = FakeTransport() + transport.add("GET", "/client/v4/zones/z1/dns_records", cf(existing)) + transport.add( + "PATCH", + "/client/v4/zones/z1/dns_records/r1", + lambda call: cf({"id": "r1", **call.body}), + ) + result = client(transport).upsert_address_record("z1", "web01.example.com", "10.0.0.5") + self.assertEqual(result.action, "updated") + self.assertEqual(result.previous.content, "10.0.0.4") + body = transport.calls_to("PATCH", "/client/v4/zones/z1/dns_records/r1")[0].body + self.assertEqual(body["content"], "10.0.0.5") + + def test_filters_records_by_name_and_type(self) -> None: + payload = [ + {"id": "r1", "name": "other.example.com", "type": "A", "content": "1.1.1.1"}, + {"id": "r2", "name": "web01.example.com", "type": "A", "content": "10.0.0.5"}, + ] + transport = FakeTransport() + transport.add("GET", "/client/v4/zones/z1/dns_records", cf(payload)) + records = client(transport).list_records("z1", name="web01.example.com", rtype="A") + self.assertEqual([r.id for r in records], ["r2"]) + + def test_proxied_record_uses_automatic_ttl(self) -> None: + existing = [ + { + "id": "r1", + "name": "web01.example.com", + "type": "A", + "content": "10.0.0.5", + "proxied": True, + "ttl": 1, + } + ] + transport = FakeTransport() + transport.add("GET", "/client/v4/zones/z1/dns_records", cf(existing)) + transport.add("PATCH", "/client/v4/zones/z1/dns_records/r1", cf({"id": "r1"})) + cf_client = client(transport, ttl=300, proxied=True) + result = cf_client.upsert_address_record("z1", "web01.example.com", "10.0.0.5") + self.assertEqual(result.action, "unchanged") + self.assertEqual(transport.count("PATCH", "/client/v4/zones/z1/dns_records/r1"), 0) + + def test_delete_missing_record_is_not_an_error(self) -> None: + transport = FakeTransport() + transport.add( + "DELETE", + "/client/v4/zones/z1/dns_records/gone", + {"success": False, "errors": [{"code": 81044, "message": "not found"}]}, + status=404, + ) + self.assertFalse(client(transport).delete_record("z1", "gone")) + + def test_delete_record(self) -> None: + transport = FakeTransport() + transport.add("DELETE", "/client/v4/zones/z1/dns_records/r1", cf({"id": "r1"})) + self.assertTrue(client(transport).delete_record("z1", "r1")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100755 index 0000000..19bf3fc --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,165 @@ +"""Configuration parsing and validation.""" + +from __future__ import annotations + +import os +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from proxdomain.config import ConfigError, load_config, parse_config +from tests.support import make_config + + +def raw_config() -> dict: + return { + "general": {"base_domain": "example.com"}, + "proxmox": { + "api_url": "https://pve.example.com:8006/api2/json", + "token_id": "automation@pve!proxdomain", + "token_secret": "secret", + }, + "cloudflare": {"api_token": "cf-token"}, + "webserver": {"kind": "nginx", "manage_dir": "/etc/nginx/conf.d/proxdomain.d"}, + } + + +class ConfigTests(unittest.TestCase): + def test_defaults(self) -> None: + config = make_config() + self.assertEqual(config.general.default_port, 80) + self.assertEqual(config.general.domain_template, "{hostname}.{base_domain}") + self.assertEqual(config.webserver.test_command, ("nginx", "-t")) + self.assertEqual(config.webserver.reload_command, ("systemctl", "reload", "nginx")) + self.assertEqual(config.webserver.tls.mode, "none") + self.assertEqual(config.proxmox.ip_preference, "ipv4") + + def test_requires_base_domain(self) -> None: + raw = raw_config() + del raw["general"]["base_domain"] + with self.assertRaises(ConfigError) as ctx: + parse_config(raw) + self.assertIn("general.base_domain", str(ctx.exception)) + + def test_base_domain_must_have_a_dot(self) -> None: + raw = raw_config() + raw["general"]["base_domain"] = "localhost" + with self.assertRaises(ConfigError): + parse_config(raw) + + def test_template_needs_a_placeholder(self) -> None: + raw = raw_config() + raw["general"]["domain_template"] = "static.example.com" + with self.assertRaises(ConfigError) as ctx: + parse_config(raw) + self.assertIn("domain_template", str(ctx.exception)) + + def test_token_id_shape(self) -> None: + raw = raw_config() + raw["proxmox"]["token_id"] = "automation@pve" + with self.assertRaises(ConfigError) as ctx: + parse_config(raw) + self.assertIn("token_id", str(ctx.exception)) + + def test_certbot_requires_email(self) -> None: + raw = raw_config() + raw["webserver"]["tls"] = {"mode": "certbot"} + with self.assertRaises(ConfigError) as ctx: + parse_config(raw) + self.assertIn("email", str(ctx.exception)) + + def test_certbot_only_for_nginx(self) -> None: + raw = raw_config() + raw["webserver"]["kind"] = "caddy" + raw["webserver"]["tls"] = {"mode": "certbot", "email": "a@example.com"} + with self.assertRaises(ConfigError): + parse_config(raw) + + def test_traefik_files_tls_rejected(self) -> None: + raw = raw_config() + raw["webserver"]["kind"] = "traefik" + raw["webserver"]["tls"] = {"mode": "files"} + with self.assertRaises(ConfigError): + parse_config(raw) + + def test_ssh_mode_requires_host(self) -> None: + raw = raw_config() + raw["webserver"]["mode"] = "ssh" + with self.assertRaises(ConfigError) as ctx: + parse_config(raw) + self.assertIn("ssh_host", str(ctx.exception)) + + def test_invalid_choice(self) -> None: + raw = raw_config() + raw["webserver"]["kind"] = "apache" + with self.assertRaises(ConfigError) as ctx: + parse_config(raw) + self.assertIn("nginx, caddy, traefik", str(ctx.exception)) + + def test_secret_from_environment(self) -> None: + raw = raw_config() + raw["proxmox"] = { + "api_url": "https://pve:8006/api2/json", + "token_id": "a@pve!t", + "token_secret_env": "PROX_TEST_PVE_SECRET", + } + raw["cloudflare"] = {"api_token_env": "PROX_TEST_CF_TOKEN"} + with mock.patch.dict( + os.environ, {"PROX_TEST_PVE_SECRET": "s3cret", "PROX_TEST_CF_TOKEN": "cf"} + ): + config = parse_config(raw) + self.assertEqual(config.proxmox.resolve_secret(), "s3cret") + self.assertEqual(config.cloudflare.resolve_token(), "cf") + with mock.patch.dict(os.environ, {}, clear=True): + with self.assertRaises(ConfigError): + config.proxmox.resolve_secret() + + def test_secret_from_file(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + secret = Path(tmp) / "pve.secret" + secret.write_text("from-file\n", encoding="utf-8") + raw = raw_config() + raw["proxmox"].pop("token_secret") + raw["proxmox"]["token_secret_file"] = str(secret) + config = parse_config(raw) + self.assertEqual(config.proxmox.resolve_secret(), "from-file") + + def test_load_from_disk_and_env(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "proxdomain.toml" + path.write_text( + "[general]\nbase_domain = \"example.com\"\n" + "[proxmox]\napi_url = \"https://pve:8006/api2/json\"\n" + "token_id = \"a@pve!t\"\ntoken_secret = \"x\"\n" + "[cloudflare]\napi_token = \"y\"\n", + encoding="utf-8", + ) + config = load_config(path) + self.assertEqual(config.general.base_domain, "example.com") + self.assertEqual(config.source, path) + with mock.patch.dict(os.environ, {"PROXDOMAIN_CONFIG": str(path)}): + self.assertEqual(load_config().general.base_domain, "example.com") + + def test_missing_config_file(self) -> None: + with self.assertRaises(ConfigError) as ctx: + load_config("/nonexistent/proxdomain.toml") + self.assertIn("no configuration file found", str(ctx.exception)) + + def test_empty_test_command_disables_validation(self) -> None: + raw = raw_config() + raw["webserver"]["test_command"] = [] + config = parse_config(raw) + self.assertEqual(config.webserver.test_command, ()) + + def test_bad_toml(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "broken.toml" + path.write_text("general = [", encoding="utf-8") + with self.assertRaises(ConfigError) as ctx: + load_config(path) + self.assertIn("not valid TOML", str(ctx.exception)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_http.py b/tests/test_http.py new file mode 100755 index 0000000..ba807ab --- /dev/null +++ b/tests/test_http.py @@ -0,0 +1,67 @@ +"""HTTP client: retries, error surfaces and non-replayable POSTs.""" + +from __future__ import annotations + +import unittest + +from proxdomain.errors import ApiError +from proxdomain.http import JsonClient +from tests.support import FakeTransport + + +def client(transport: FakeTransport, **kwargs) -> JsonClient: + return JsonClient( + "https://api.example.com", + transport=transport, + retries=kwargs.pop("retries", 2), + sleep=lambda _seconds: None, + **kwargs, + ) + + +class RetryTests(unittest.TestCase): + def test_get_is_retried_on_502(self) -> None: + transport = FakeTransport() + transport.add("GET", "/x", {"errors": [{"message": "bad gateway"}]}, status=502) + with self.assertRaises(ApiError) as ctx: + client(transport).get("/x") + self.assertEqual(transport.count("GET", "/x"), 3) + self.assertEqual(ctx.exception.status, 502) + self.assertIn("bad gateway", str(ctx.exception)) + + def test_post_is_not_replayed_on_502(self) -> None: + transport = FakeTransport() + transport.add("POST", "/y", {"errors": [{"message": "bad gateway"}]}, status=502) + with self.assertRaises(ApiError): + client(transport).post("/y", {"name": "web01"}) + self.assertEqual(transport.count("POST", "/y"), 1) + + def test_post_is_retried_on_429(self) -> None: + transport = FakeTransport() + transport.add("POST", "/y", {"errors": [{"message": "rate limited"}]}, status=429) + with self.assertRaises(ApiError): + client(transport).post("/y", {"name": "web01"}) + self.assertEqual(transport.count("POST", "/y"), 3) + + def test_success_returns_parsed_json(self) -> None: + transport = FakeTransport() + transport.add("GET", "/z", {"ok": True}) + self.assertEqual(client(transport).get("/z"), {"ok": True}) + + def test_delete_missing_is_returned_as_error(self) -> None: + transport = FakeTransport() + transport.add("DELETE", "/z/1", {"success": False}, status=404) + with self.assertRaises(ApiError) as ctx: + client(transport).delete("/z/1") + self.assertEqual(ctx.exception.status, 404) + + def test_retries_can_be_disabled(self) -> None: + transport = FakeTransport() + transport.add("GET", "/x", {"errors": []}, status=503) + with self.assertRaises(ApiError): + client(transport, retries=0).get("/x") + self.assertEqual(transport.count("GET", "/x"), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_proxmox.py b/tests/test_proxmox.py new file mode 100755 index 0000000..5850cee --- /dev/null +++ b/tests/test_proxmox.py @@ -0,0 +1,174 @@ +"""Proxmox guest discovery and IP selection.""" + +from __future__ import annotations + +import unittest + +from proxdomain.errors import ApiError, ProxdomainError +from proxdomain.proxmox import Guest, ProxmoxClient, _split_tags +from proxdomain.http import JsonClient +from tests.support import FakeTransport, add_proxmox_routes, make_config, pve + + +def client(transport: FakeTransport, **proxmox) -> ProxmoxClient: + config = make_config(proxmox=proxmox or None) + return ProxmoxClient(config.proxmox, transport=transport) + + +class GuestParsingTests(unittest.TestCase): + def test_list_guests(self) -> None: + transport = FakeTransport() + add_proxmox_routes( + transport, + guests=[ + { + "vmid": 101, + "node": "pve", + "type": "qemu", + "name": "web01", + "status": "running", + "tags": "proxdomain;web", + }, + {"vmid": 102, "node": "pve2", "type": "lxc", "name": "db", "status": "stopped"}, + {"id": "storage/local", "type": "storage"}, + ], + ) + guests = client(transport).list_guests() + self.assertEqual([g.vmid for g in guests], [101, 102]) + self.assertEqual(guests[0].tags, ("proxdomain", "web")) + self.assertTrue(guests[0].is_running) + self.assertFalse(guests[1].is_running) + + def test_find_by_name_exact_then_substring(self) -> None: + transport = FakeTransport() + add_proxmox_routes( + transport, + guests=[ + {"vmid": 101, "node": "pve", "type": "qemu", "name": "web01", "status": "running"}, + {"vmid": 102, "node": "pve", "type": "lxc", "name": "web02", "status": "running"}, + ], + ) + proxmox = client(transport) + self.assertEqual(proxmox.find_guest(name="web01").vmid, 101) + self.assertEqual(proxmox.find_guest(name="WEB02").vmid, 102) + + def test_ambiguous_name(self) -> None: + transport = FakeTransport() + add_proxmox_routes( + transport, + guests=[ + {"vmid": 101, "node": "pve", "type": "qemu", "name": "web01", "status": "running"}, + {"vmid": 102, "node": "pve", "type": "lxc", "name": "web02", "status": "running"}, + ], + ) + with self.assertRaises(ProxdomainError) as ctx: + client(transport).find_guest(name="web") + self.assertIn("use --vmid", str(ctx.exception)) + + def test_unknown_guest(self) -> None: + transport = FakeTransport() + add_proxmox_routes(transport) + with self.assertRaises(ProxdomainError): + client(transport).find_guest(vmid=999) + + def test_tag_parsing(self) -> None: + self.assertEqual(_split_tags("a;b"), ("a", "b")) + self.assertEqual(_split_tags("a,b"), ("a", "b")) + self.assertEqual(_split_tags(None), ()) + + +class AddressTests(unittest.TestCase): + def _guest(self, kind: str = "qemu", vmid: int = 101) -> Guest: + return Guest(vmid=vmid, node="pve", name="web01", kind=kind, status="running") + + def test_agent_addresses_filtered(self) -> None: + transport = FakeTransport() + add_proxmox_routes( + transport, + agent_ips=["127.0.0.1", "169.254.10.1", "192.168.1.50"], + ) + self.assertEqual(client(transport).guest_ip(self._guest()), "192.168.1.50") + + def test_excluded_network_is_skipped(self) -> None: + transport = FakeTransport() + add_proxmox_routes(transport, agent_ips=["172.17.0.5"]) + self.assertIsNone(client(transport).guest_ip(self._guest())) + + def test_agent_failure_falls_back_to_static_config(self) -> None: + transport = FakeTransport() + transport.add( + "GET", + "/api2/json/nodes/pve/qemu/101/agent/network-get-interfaces", + {"errors": [{"message": "guest agent not running"}]}, + status=500, + ) + transport.add( + "GET", + "/api2/json/nodes/pve/qemu/101/config", + pve({"ipconfig0": "ip=10.0.0.9/24,gw=10.0.0.1"}), + ) + self.assertEqual(client(transport).guest_ip(self._guest()), "10.0.0.9") + + def test_auth_error_propagates(self) -> None: + transport = FakeTransport() + transport.add( + "GET", + "/api2/json/nodes/pve/qemu/101/agent/network-get-interfaces", + {"errors": [{"message": "denied"}]}, + status=403, + ) + with self.assertRaises(ApiError) as ctx: + client(transport).guest_ip(self._guest()) + self.assertTrue(ctx.exception.is_auth_error) + + def test_lxc_static_ip_from_net0(self) -> None: + transport = FakeTransport() + transport.add( + "GET", + "/api2/json/nodes/pve/lxc/102/config", + pve({"net0": "name=eth0,bridge=vmbr0,ip=10.0.0.6/24,gw=10.0.0.1"}), + ) + guest = Guest(vmid=102, node="pve", name="db", kind="lxc", status="running") + self.assertEqual(client(transport).guest_ip(guest), "10.0.0.6") + + def test_lxc_runtime_interfaces(self) -> None: + transport = FakeTransport() + transport.add( + "GET", + "/api2/json/nodes/pve/lxc/102/interfaces", + pve([{"name": "eth0", "inet": "10.0.0.7/24", "inet6": "fe80::1/64"}]), + ) + guest = Guest(vmid=102, node="pve", name="db", kind="lxc", status="running") + self.assertEqual(client(transport).guest_ip(guest), "10.0.0.7") + + def test_ipv6_preference(self) -> None: + transport = FakeTransport() + add_proxmox_routes(transport, agent_ips=["192.168.1.50"]) + transport.add( + "GET", + "/api2/json/nodes/pve/qemu/101/agent/network-get-interfaces", + pve( + { + "result": [ + { + "name": "eth0", + "ip-addresses": [ + {"ip-address": "192.168.1.50", "ip-address-type": "ipv4"}, + {"ip-address": "2001:db8::10", "ip-address-type": "ipv6"}, + ], + } + ] + } + ), + ) + proxmox = client(transport, ip_preference="ipv6") + self.assertEqual(proxmox.guest_ip(self._guest()), "2001:db8::10") + + def test_loopback_only_returns_none(self) -> None: + transport = FakeTransport() + add_proxmox_routes(transport, agent_ips=["127.0.0.1", "::1"]) + self.assertIsNone(client(transport).guest_ip(self._guest())) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_service.py b/tests/test_service.py new file mode 100755 index 0000000..9f45d82 --- /dev/null +++ b/tests/test_service.py @@ -0,0 +1,297 @@ +"""End-to-end orchestration against fake Proxmox, Cloudflare and web server.""" + +from __future__ import annotations + +import unittest + +from proxdomain.cloudflare import CloudflareClient +from proxdomain.proxmox import ProxmoxClient +from proxdomain.service import DomainService, sanitize_hostname +from proxdomain.state import Assignment, StateStore +from proxdomain.webserver import WebServerManager +from tests.support import FakeRunner, FakeTransport, add_proxmox_routes, cf, make_config + +ZONE = "zone-1" +DNS_PATH = f"/client/v4/zones/{ZONE}/dns_records" + + +def build( + *, + guests: list[dict] | None = None, + agent_ips: list[str] | None = None, + records: list[dict] | None = None, +): + guests = guests if guests is not None else [ + { + "vmid": 101, + "node": "pve", + "type": "qemu", + "name": "web01", + "status": "running", + "tags": "proxdomain", + } + ] + agent_ips = agent_ips if agent_ips is not None else ["127.0.0.1", "10.0.0.5"] + transport = FakeTransport() + add_proxmox_routes(transport, guests=guests, agent_ips=agent_ips) + stored = list(records or []) + + transport.add("GET", "/client/v4/zones", cf([{"id": ZONE, "name": "example.com"}])) + transport.add("GET", "/client/v4/user/tokens/verify", cf({"status": "active"})) + + def list_records(call): + return cf([dict(record) for record in stored]) + + def create(call): + record = { + "id": "rec-1", + "name": call.body["name"], + "type": call.body["type"], + "content": call.body["content"], + "proxied": call.body.get("proxied", False), + "ttl": call.body.get("ttl", 1), + } + stored.append(record) + return cf(record) + + def update(call, record_id="rec-1"): + updated = {"id": record_id, **call.body} + for index, record in enumerate(stored): + if record["id"] == record_id: + stored[index] = updated + return cf(updated) + + transport.add("GET", DNS_PATH, list_records) + transport.add("POST", DNS_PATH, create) + transport.add("PATCH", f"{DNS_PATH}/rec-1", update) + transport.add("DELETE", f"{DNS_PATH}/rec-1", cf({"id": "rec-1"})) + + config = make_config() + runner = FakeRunner() + service = DomainService( + config, + proxmox=ProxmoxClient(config.proxmox, transport=transport), + cloudflare=CloudflareClient(config.cloudflare, transport=transport), + webserver=WebServerManager(config.webserver, runner), + state=StateStore(":memory:"), + ) + return service, transport, runner, stored + + +SITE_FILE = "/etc/nginx/conf.d/proxdomain.d/web01.example.com.conf" + + +class AssignTests(unittest.TestCase): + def test_assign_end_to_end(self) -> None: + service, transport, runner, stored = build() + report = service.assign(vmid=101) + self.assertTrue(report.ok, report.to_dict()) + self.assertEqual(report.assignment.fqdn, "web01.example.com") + self.assertEqual(report.assignment.record_id, "rec-1") + self.assertIn(SITE_FILE, runner.files) + self.assertEqual(len(stored), 1) + + body = transport.calls_to("POST", DNS_PATH)[0].body + self.assertEqual(body["content"], "10.0.0.5") + # 10.0.0.5 is private, so the orange cloud must be off automatically. + self.assertFalse(body["proxied"]) + self.assertTrue(any(step.status == "warning" for step in report.steps)) + + items = service.state.all() + self.assertEqual(len(items), 1) + self.assertEqual(items[0].vmid, 101) + self.assertEqual(items[0].zone_id, ZONE) + + def test_assign_is_idempotent(self) -> None: + service, transport, runner, _ = build() + service.assign(vmid=101) + posts = transport.count("POST", DNS_PATH) + commands = len(runner.commands) + + report = service.assign(vmid=101) + self.assertTrue(report.ok, report.to_dict()) + self.assertEqual(transport.count("POST", DNS_PATH), posts) + self.assertEqual(len(runner.commands), commands) + self.assertIn("unchanged", " ".join(step.detail for step in report.steps)) + + def test_public_ip_keeps_cloudflare_proxy(self) -> None: + service, transport, _, _ = build(agent_ips=["8.8.8.8"]) + report = service.assign(vmid=101) + self.assertTrue(report.ok, report.to_dict()) + self.assertTrue(transport.calls_to("POST", DNS_PATH)[0].body["proxied"]) + + def test_explicit_no_proxy(self) -> None: + service, transport, _, _ = build(agent_ips=["8.8.8.8"]) + report = service.assign(vmid=101, proxied=False) + self.assertTrue(report.ok) + self.assertFalse(transport.calls_to("POST", DNS_PATH)[0].body["proxied"]) + + def test_dry_run_changes_nothing(self) -> None: + service, transport, runner, stored = build() + report = service.assign(vmid=101, dry_run=True) + self.assertTrue(report.ok, report.to_dict()) + self.assertEqual(runner.files, {}) + self.assertEqual(runner.commands, []) + self.assertEqual(transport.count("POST", DNS_PATH), 0) + self.assertEqual(stored, []) + self.assertEqual(service.state.all(), []) + self.assertTrue(any(step.status == "planned" for step in report.steps)) + + def test_port_override_and_subdomain(self) -> None: + service, _, runner, _ = build() + report = service.assign(vmid=101, subdomain="app", port=8080) + self.assertTrue(report.ok, report.to_dict()) + self.assertEqual(report.assignment.fqdn, "app.example.com") + content = runner.files["/etc/nginx/conf.d/proxdomain.d/app.example.com.conf"] + self.assertIn("proxy_pass http://10.0.0.5:8080;", content) + + def test_missing_ip_is_explained(self) -> None: + service, _, runner, _ = build(agent_ips=["127.0.0.1"]) + report = service.assign(vmid=101) + self.assertFalse(report.ok) + detail = " ".join(step.detail for step in report.steps) + self.assertIn("no usable IP address", detail) + self.assertIn("qemu-guest-agent", detail) + self.assertEqual(runner.files, {}) + + def test_domain_taken_by_another_guest(self) -> None: + service, _, _, _ = build() + service.state.upsert( + Assignment( + fqdn="web01.example.com", + vmid=999, + node="pve", + kind="lxc", + ip="10.0.0.9", + ) + ) + report = service.assign(vmid=101) + self.assertFalse(report.ok) + self.assertIn("already assigned", " ".join(step.detail for step in report.steps)) + + forced = service.assign(vmid=101, force=True) + self.assertTrue(forced.ok, forced.to_dict()) + self.assertEqual(service.state.get("web01.example.com").vmid, 101) + + def test_unknown_guest(self) -> None: + service, _, _, _ = build() + report = service.assign(vmid=404) + self.assertFalse(report.ok) + self.assertEqual(report.steps[0].name, "guest") + + +class RemoveTests(unittest.TestCase): + def test_requires_confirmation(self) -> None: + service, transport, runner, _ = build() + service.assign(vmid=101) + report = service.remove(fqdn="web01.example.com") + self.assertFalse(report.ok) + self.assertIn("--yes", " ".join(step.detail for step in report.steps)) + self.assertIn(SITE_FILE, runner.files) + self.assertEqual(transport.count("DELETE", f"{DNS_PATH}/rec-1"), 0) + + def test_remove_deletes_config_dns_and_state(self) -> None: + service, transport, runner, _ = build() + service.assign(vmid=101) + report = service.remove(fqdn="web01.example.com", confirm=True) + self.assertTrue(report.ok, report.to_dict()) + self.assertNotIn(SITE_FILE, runner.files) + self.assertEqual(transport.count("DELETE", f"{DNS_PATH}/rec-1"), 1) + self.assertEqual(service.state.all(), []) + + def test_remove_by_vmid(self) -> None: + service, _, _, _ = build() + service.assign(vmid=101) + report = service.remove(vmid=101, confirm=True) + self.assertTrue(report.ok, report.to_dict()) + + def test_remove_unknown(self) -> None: + service, _, _, _ = build() + report = service.remove(fqdn="nope.example.com", confirm=True) + self.assertFalse(report.ok) + + def test_dry_run_remove(self) -> None: + service, transport, runner, _ = build() + service.assign(vmid=101) + report = service.remove(fqdn="web01.example.com", dry_run=True) + self.assertTrue(report.ok) + self.assertIn(SITE_FILE, runner.files) + self.assertEqual(transport.count("DELETE", f"{DNS_PATH}/rec-1"), 0) + self.assertEqual(len(service.state.all()), 1) + + +class SyncTests(unittest.TestCase): + def test_sync_is_quiet_when_nothing_changed(self) -> None: + service, _, runner, _ = build() + service.assign(vmid=101) + commands = len(runner.commands) + report = service.sync() + self.assertTrue(report.ok, report.to_dict()) + self.assertEqual(len(runner.commands), commands) + + def test_sync_tracks_ip_change(self) -> None: + service, transport, runner, stored = build() + service.assign(vmid=101) + transport.add( + "GET", + "/api2/json/nodes/pve/qemu/101/agent/network-get-interfaces", + { + "data": { + "result": [ + { + "name": "eth0", + "ip-addresses": [ + {"ip-address": "10.0.0.77", "ip-address-type": "ipv4"} + ], + } + ] + } + }, + ) + report = service.sync() + self.assertTrue(report.ok, report.to_dict()) + self.assertEqual(stored[0]["content"], "10.0.0.77") + self.assertEqual(service.state.get("web01.example.com").ip, "10.0.0.77") + self.assertIn("10.0.0.77", runner.files[SITE_FILE]) + + +class DiscoveryTests(unittest.TestCase): + def test_watch_candidates_respects_tag_and_state(self) -> None: + guests = [ + {"vmid": 101, "node": "pve", "type": "qemu", "name": "web01", "status": "running", "tags": "proxdomain"}, + {"vmid": 102, "node": "pve", "type": "lxc", "name": "db", "status": "running"}, + {"vmid": 103, "node": "pve", "type": "lxc", "name": "cache", "status": "stopped", "tags": "proxdomain"}, + ] + service, _, _, _ = build(guests=guests) + candidates = service.watch_candidates() + self.assertEqual([guest.vmid for guest in candidates], [101]) + + service.assign(vmid=101) + self.assertEqual(service.watch_candidates(), []) + self.assertEqual([g.vmid for g in service.watch_candidates(tag="")], [102]) + + def test_doctor_reports_all_subsystems(self) -> None: + service, _, _, _ = build() + report = service.doctor() + self.assertTrue(report.ok, report.to_dict()) + names = {step.name for step in report.steps} + self.assertTrue({"proxmox", "cloudflare", "web-server", "state"} <= names) + + def test_init_dry_run(self) -> None: + service, _, runner, _ = build() + report = service.init(dry_run=True) + self.assertTrue(report.ok, report.to_dict()) + self.assertEqual(runner.files, {}) + + +class HostnameTests(unittest.TestCase): + def test_sanitize(self) -> None: + self.assertEqual(sanitize_hostname("Web Server", 1), "web-server") + self.assertEqual(sanitize_hostname("db_01", 1), "db-01") + self.assertEqual(sanitize_hostname("!!!", 7), "vm7") + self.assertEqual(sanitize_hostname("", 7), "vm7") + self.assertEqual(len(sanitize_hostname("a" * 80, 1)), 40) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_state.py b/tests/test_state.py new file mode 100755 index 0000000..db01a3b --- /dev/null +++ b/tests/test_state.py @@ -0,0 +1,94 @@ +"""Assignment state persistence, locking and audit log.""" + +from __future__ import annotations + +import json +import tempfile +import unittest +from pathlib import Path + +from proxdomain.errors import ProxdomainError +from proxdomain.state import Assignment, StateStore + + +def assignment(fqdn: str = "web01.example.com", vmid: int = 101) -> Assignment: + return Assignment(fqdn=fqdn, vmid=vmid, node="pve", kind="qemu", name="web01", ip="10.0.0.5") + + +class StateTests(unittest.TestCase): + def test_roundtrip(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = str(Path(tmp) / "state.json") + store = StateStore(path, audit_path=str(Path(tmp) / "audit.jsonl")) + store.load() + store.upsert(assignment()) + store.flush() + + reloaded = StateStore(path) + items = reloaded.all() + self.assertEqual(len(items), 1) + self.assertEqual(items[0].fqdn, "web01.example.com") + self.assertEqual(items[0].ip, "10.0.0.5") + self.assertTrue(items[0].created_at) + + def test_created_at_is_preserved(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = str(Path(tmp) / "state.json") + store = StateStore(path) + first = store.upsert(assignment()) + created = first.created_at + first.port = 8080 + again = store.upsert(first) + self.assertEqual(again.created_at, created) + self.assertGreaterEqual(again.updated_at, created) + + def test_remove(self) -> None: + store = StateStore(":memory:") + store.upsert(assignment()) + self.assertTrue(store.remove("web01.example.com")) + self.assertFalse(store.remove("web01.example.com")) + self.assertEqual(store.all(), []) + + def test_corrupt_state_is_reported(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "state.json" + path.write_text("{not json", encoding="utf-8") + with self.assertRaises(ProxdomainError) as ctx: + StateStore(str(path)).load() + self.assertIn("cannot read state file", str(ctx.exception)) + + def test_unknown_version_is_rejected(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "state.json" + path.write_text(json.dumps({"version": 99, "assignments": {}}), encoding="utf-8") + with self.assertRaises(ProxdomainError): + StateStore(str(path)).load() + + def test_audit_appends_json_lines(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + audit = Path(tmp) / "audit.jsonl" + store = StateStore(str(Path(tmp) / "state.json"), audit_path=str(audit)) + store.audit("assign", fqdn="web01.example.com", vmid=101) + store.audit("remove", fqdn="web01.example.com") + lines = [json.loads(line) for line in audit.read_text(encoding="utf-8").splitlines()] + self.assertEqual([line["event"] for line in lines], ["assign", "remove"]) + self.assertEqual(lines[0]["vmid"], 101) + + def test_second_lock_times_out(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + store = StateStore(str(Path(tmp) / "state.json"), lock_timeout=0.2) + with store.locked(): + with self.assertRaises(ProxdomainError) as ctx: + with store.locked(): + pass + self.assertIn("locked", str(ctx.exception)) + + def test_memory_only(self) -> None: + store = StateStore(":memory:") + store.upsert(assignment()) + store.flush() + self.assertEqual(len(store.all()), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_webserver.py b/tests/test_webserver.py new file mode 100755 index 0000000..1a512bf --- /dev/null +++ b/tests/test_webserver.py @@ -0,0 +1,249 @@ +"""Reverse-proxy rendering, activation, rollback and bootstrap.""" + +from __future__ import annotations + +import unittest + +from proxdomain.errors import WebServerError +from proxdomain.webserver import SiteSpec, WebServerManager, render_nginx_challenge +from tests.support import FakeRunner, make_config + + +def spec(**overrides) -> SiteSpec: + values = dict( + fqdn="web01.example.com", + address="10.0.0.5", + port=80, + vmid=101, + node="pve", + kind="qemu", + webserver="nginx", + ) + values.update(overrides) + return SiteSpec(**values) + + +class RenderTests(unittest.TestCase): + def test_nginx_plain_http(self) -> None: + content = WebServerManager(make_config().webserver, FakeRunner()).render(spec()) + self.assertIn("server_name web01.example.com;", content) + self.assertIn("proxy_pass http://10.0.0.5:80;", content) + self.assertIn("listen 80;", content) + self.assertNotIn("ssl_certificate", content) + self.assertIn("Managed by proxdomain", content) + + def test_nginx_with_tls(self) -> None: + content = WebServerManager(make_config().webserver, FakeRunner()).render( + spec(tls_mode="files", port=8080) + ) + self.assertIn("listen 443 ssl;", content) + self.assertIn( + "ssl_certificate /etc/letsencrypt/live/web01.example.com/fullchain.pem;", + content, + ) + self.assertIn("return 301 https://$host$request_uri;", content) + self.assertIn("proxy_pass http://10.0.0.5:8080;", content) + self.assertIn("root /var/www/certbot;", content) + + def test_caddy(self) -> None: + manager = WebServerManager(make_config(kind="caddy").webserver, FakeRunner()) + content = manager.render(spec(webserver="caddy", port=3000)) + self.assertIn("web01.example.com {", content) + self.assertIn("reverse_proxy http://10.0.0.5:3000", content) + + def test_caddy_with_certificate_files(self) -> None: + manager = WebServerManager(make_config(kind="caddy").webserver, FakeRunner()) + content = manager.render(spec(webserver="caddy", tls_mode="files")) + self.assertIn( + "tls /etc/letsencrypt/live/web01.example.com/fullchain.pem " + "/etc/letsencrypt/live/web01.example.com/privkey.pem", + content, + ) + + def test_traefik(self) -> None: + manager = WebServerManager( + make_config(kind="traefik", cert_resolver="letsencrypt").webserver, FakeRunner() + ) + content = manager.render(spec(webserver="traefik", cert_resolver="letsencrypt")) + self.assertIn("rule: \"Host(`web01.example.com`)\"", content) + self.assertIn("url: \"http://10.0.0.5:80\"", content) + self.assertIn("certResolver: letsencrypt", content) + + def test_traefik_without_resolver(self) -> None: + manager = WebServerManager(make_config(kind="traefik").webserver, FakeRunner()) + content = manager.render(spec(webserver="traefik")) + self.assertIn("tls: {}", content) + + def test_site_path(self) -> None: + manager = WebServerManager(make_config().webserver, FakeRunner()) + self.assertEqual( + manager.site_path("web01.example.com"), + "/etc/nginx/conf.d/proxdomain.d/web01.example.com.conf", + ) + with self.assertRaises(WebServerError): + manager.site_path("../../etc/passwd") + + +class ApplyTests(unittest.TestCase): + def test_apply_writes_validates_and_reloads(self) -> None: + runner = FakeRunner() + manager = WebServerManager(make_config().webserver, runner) + result = manager.apply(spec()) + self.assertTrue(result.changed) + self.assertTrue(result.validated) + self.assertTrue(result.reloaded) + self.assertIn("/etc/nginx/conf.d/proxdomain.d/web01.example.com.conf", runner.files) + self.assertEqual( + runner.commands, + [("nginx", "-t"), ("systemctl", "reload", "nginx")], + ) + self.assertIn(("systemctl", "reload", "nginx"), runner.commands) + + def test_second_apply_is_a_noop(self) -> None: + runner = FakeRunner() + manager = WebServerManager(make_config().webserver, runner) + manager.apply(spec()) + calls_after_first = len(runner.commands) + result = manager.apply(spec()) + self.assertFalse(result.changed) + self.assertEqual(len(runner.commands), calls_after_first) + + def test_dry_run_touches_nothing(self) -> None: + runner = FakeRunner() + manager = WebServerManager(make_config().webserver, runner) + result = manager.apply(spec(), dry_run=True) + self.assertTrue(result.changed) + self.assertEqual(runner.files, {}) + self.assertEqual(runner.commands, []) + + def test_failed_validation_removes_a_new_file(self) -> None: + runner = FakeRunner(failures=[("nginx -t", 1, "nginx: [emerg] bad directive")]) + manager = WebServerManager(make_config().webserver, runner) + with self.assertRaises(WebServerError) as ctx: + manager.apply(spec()) + self.assertIn("rolled back", str(ctx.exception)) + self.assertEqual(runner.files, {}) + + def test_failed_validation_restores_previous_content(self) -> None: + path = "/etc/nginx/conf.d/proxdomain.d/web01.example.com.conf" + runner = FakeRunner({path: "# previous\n"}, failures=[("nginx -t", 1, "boom")]) + manager = WebServerManager(make_config().webserver, runner) + with self.assertRaises(WebServerError): + manager.apply(spec(port=8080)) + self.assertEqual(runner.files[path], "# previous\n") + + def test_reload_failure_keeps_valid_config(self) -> None: + runner = FakeRunner(failures=[("systemctl reload", 1, "unit not running")]) + manager = WebServerManager(make_config().webserver, runner) + with self.assertRaises(WebServerError) as ctx: + manager.apply(spec()) + self.assertIn("reloading the web server failed", str(ctx.exception)) + self.assertIn("/etc/nginx/conf.d/proxdomain.d/web01.example.com.conf", runner.files) + + def test_remove_deletes_and_reloads(self) -> None: + runner = FakeRunner() + manager = WebServerManager(make_config().webserver, runner) + manager.apply(spec()) + result = manager.remove("web01.example.com") + self.assertTrue(result.changed) + self.assertEqual(runner.files, {}) + + def test_remove_restores_when_validation_breaks(self) -> None: + path = "/etc/nginx/conf.d/proxdomain.d/web01.example.com.conf" + runner = FakeRunner({path: "server {}\n"}) + manager = WebServerManager(make_config().webserver, runner) + runner.failures = [("nginx -t", 1, "boom")] + with self.assertRaises(WebServerError) as ctx: + manager.remove("web01.example.com") + self.assertIn("restored", str(ctx.exception)) + self.assertEqual(runner.files[path], "server {}\n") + + def test_without_test_command_validation_is_skipped(self) -> None: + config = make_config(kind="traefik") + runner = FakeRunner() + manager = WebServerManager(config.webserver, runner) + result = manager.apply(spec(webserver="traefik")) + self.assertTrue(result.changed) + self.assertFalse(result.validated) + self.assertEqual(runner.commands, []) + + +class CertbotTests(unittest.TestCase): + def _manager(self, runner: FakeRunner) -> WebServerManager: + config = make_config(tls={"mode": "certbot", "email": "ops@example.com"}) + return WebServerManager(config.webserver, runner) + + def test_challenge_vhost_is_rendered(self) -> None: + content = render_nginx_challenge(spec(tls_mode="certbot")) + self.assertIn("root /var/www/certbot;", content) + self.assertIn("proxy_pass http://10.0.0.5:80;", content) + self.assertNotIn("ssl_certificate", content) + + def test_issues_certificate_after_serving_challenge(self) -> None: + runner = FakeRunner() + manager = self._manager(runner) + result = manager.apply(spec(tls_mode="certbot")) + self.assertTrue(result.changed) + self.assertTrue(any("issued a certificate" in message for message in result.messages)) + commands = [" ".join(command) for command in runner.commands] + self.assertTrue(any(command.startswith("certbot") for command in commands)) + certbot_index = next( + index for index, command in enumerate(commands) if command.startswith("certbot") + ) + # The port-80 vhost must be live before certbot runs. + self.assertIn("nginx -t", commands[:certbot_index]) + self.assertIn("systemctl reload nginx", commands[:certbot_index]) + final = runner.files["/etc/nginx/conf.d/proxdomain.d/web01.example.com.conf"] + self.assertIn("listen 443 ssl;", final) + + def test_failed_certbot_removes_temporary_vhost(self) -> None: + runner = FakeRunner(failures=[("certbot", 1, "dns problem")]) + manager = self._manager(runner) + with self.assertRaises(WebServerError) as ctx: + manager.apply(spec(tls_mode="certbot")) + self.assertIn("certbot failed", str(ctx.exception)) + self.assertEqual(runner.files, {}) + + def test_existing_certificate_skips_certbot(self) -> None: + runner = FakeRunner( + {"/etc/letsencrypt/live/web01.example.com/fullchain.pem": "cert"} + ) + manager = self._manager(runner) + result = manager.apply(spec(tls_mode="certbot")) + self.assertTrue(result.changed) + self.assertFalse(any(command[0] == "certbot" for command in runner.commands)) + + +class BootstrapTests(unittest.TestCase): + def test_nginx_include_written_once(self) -> None: + runner = FakeRunner() + manager = WebServerManager(make_config().webserver, runner) + steps = manager.bootstrap() + self.assertIn("/etc/nginx/conf.d/proxdomain.d", runner.dirs) + include = "/etc/nginx/conf.d/proxdomain.d.conf" + self.assertIn(include, runner.files) + self.assertIn("include /etc/nginx/conf.d/proxdomain.d/*.conf;", runner.files[include]) + self.assertTrue(any(status == "ok" for status, _ in steps)) + + second = manager.bootstrap() + self.assertTrue(any("already includes" in detail for _, detail in second)) + + def test_caddy_import_appended_once(self) -> None: + runner = FakeRunner({"/etc/caddy/Caddyfile": "{\n\tadmin off\n}\n"}) + manager = WebServerManager(make_config(kind="caddy").webserver, runner) + manager.bootstrap() + self.assertIn("import /etc/caddy/proxdomain.d/*.caddy", runner.files["/etc/caddy/Caddyfile"]) + snapshot = runner.files["/etc/caddy/Caddyfile"] + manager.bootstrap() + self.assertEqual(runner.files["/etc/caddy/Caddyfile"], snapshot) + + def test_bootstrap_dry_run(self) -> None: + runner = FakeRunner() + manager = WebServerManager(make_config().webserver, runner) + steps = manager.bootstrap(dry_run=True) + self.assertEqual(runner.files, {}) + self.assertTrue(any(status == "planned" for status, _ in steps)) + + +if __name__ == "__main__": + unittest.main()