Files
prxdom/README.md
T
2026-11-23 00:05:50 +02:00

421 lines
19 KiB
Markdown
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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 sftpgo (lxc 101 on vz)
[ok ] address guest 10.3.0.22 (discovered)
[ok ] dns-address 93.184.216.34 (detected via https://ipv4.icanhazip.com)
[ok ] domain sftpgo.example.com
[ok ] zone example.com (023e105f4ecef8ad9ca31a8372d0c353)
[done] web-config created /etc/caddy/conf.d/sftpgo.example.com.caddy
[ok ] tls Caddy requests and renews a Let's Encrypt certificate for this site
[done] dns created A sftpgo.example.com -> 93.184.216.34 (proxied=yes)
[ok ] result sftpgo.example.com -> http://10.3.0.22:80 (published 93.184.216.34)
```
## 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). This is the **proxy target**, not the DNS value.
2. **Address** — `[dns] target = "host"` (the default) publishes the Proxmox
host's public address, because the host runs the reverse proxy; the vhost
still proxies to the guest's private IP. Set `dns.address` (or `dns.hostname`)
to skip auto-detection, or `target = "guest"` when guests hold public IPs.
3. **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; non-public targets automatically get a grey cloud.
4. **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.
5. **TLS** — with `webserver.tls.mode = "letsencrypt"` the certificate is
obtained automatically (certbot for nginx, Caddy's ACME issuer, Traefik's
cert resolver) and renewed by the web server itself.
6. **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.
To remove proxdomain again — domains, DNS records, include line and secrets —
follow [`UNINSTALL.md`](UNINSTALL.md).
## 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'
```
`proxmox.token_secret_env` holds the **name** of that variable
(`PROXDOMAIN_PVE_TOKEN`), not the secret. The secret goes in the variable, in
`token_secret_file`, or in `token_secret`. Note that `VAR=value proxdomain ...`
exports it for that one command, while `VAR=value && proxdomain ...` does not
export it at all.
### 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`.
### DNS target
| `[dns] target` | Record points at | Use when |
| --- | --- | --- |
| `host` (default) | the Proxmox host's public address | guests sit on a private bridge and the host runs nginx/Caddy/Traefik |
| `fixed` | `dns.address` verbatim | the public address is known and detection should never run |
| `guest` | the guest's own address | every guest holds a public IP |
For `host`, the address is taken from `dns.address`, otherwise a DNS lookup of
`dns.hostname`, otherwise an HTTPS detection endpoint (`detect_url_v4` /
`detect_url_v6`). Pinning the address is recommended for a stable host:
```toml
[dns]
target = "host"
address = "93.184.216.34" # optional; skips auto-detection
```
`proxdomain doctor` prints the resolved target, and `assign --address <ip>`
overrides it for a single command. After changing `target` (or the host's
address), run `proxdomain sync` to re-point existing records.
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 <hostname>.<base_domain>
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
# publish a one-off address instead of the configured host address
proxdomain assign --vmid 101 --address 93.184.216.34
# 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
### Backend port
A guest is proxied to `http://<guest IP>:<port>`. The port is resolved in this
order, and `assign` prints which source won:
1. `--port` on the command line
2. `proxdomain-port=8080` in the guest's **Notes** field (Options → Notes), or a
`proxdomain-port-8080` tag — so a VM/CT carries its own port and automatic
assignment picks it up
3. the port already stored for that domain — re-running `assign` never resets a
custom port back to the default
4. `general.default_port`
```bash
proxdomain assign --vmid 101 --port 8080 # one-off, stored in state.json
proxdomain sync # re-reads Notes/tags, rewrites vhosts
```
Changing the port later is the same command, or edit the Notes field and run
`sync`; the vhost and the Cloudflare record do not need to be recreated. Ports
outside 1–65535 are refused before any file or DNS change.
## 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
Set one section and every managed domain gets HTTPS automatically:
```toml
[webserver.tls]
mode = "letsencrypt"
email = "ops@example.com"
```
| `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 |
| `letsencrypt` | Automatic Let's Encrypt certificate (per web server, see below) | The normal choice for a public domain |
| `files` | `:80` redirect + `:443` vhost with `cert_dir/<fqdn>/{fullchain,privkey}.pem` | Certificates already exist (wildcard, acme.sh, another certbot) |
| `certbot` | Alias of `letsencrypt` for nginx, kept for older configs | — |
How each web server gets the certificate:
* **nginx** — for a domain with no certificate, proxdomain first activates an
HTTP-only vhost, runs `certbot certonly --webroot --keep-until-expiring`
against `webserver.tls.webroot`, then writes the `:443` vhost. The renewal hook
(`--deploy-hook`, default `webserver.reload_command`) makes certbot's systemd
timer reload nginx after each renewal. Install certbot first
(`apt install certbot`); `proxdomain doctor` reports whether it is present.
* **Caddy** — the site block pins `tls { issuer acme { email … } }`, so Caddy
obtains and renews the certificate itself and never falls back to ZeroSSL.
* **Traefik** — the router keeps `certResolver` (`webserver.cert_resolver`),
which must be defined in the static config with an ACME challenge.
`acme_ca` switches the ACME directory (staging, Pebble, Buypass); leave it empty
for Let's Encrypt production. `renew_hook` overrides the post-renewal command.
`proxdomain assign` prints a `tls` line, `proxdomain list` has a `TLS` column, and
`proxdomain doctor` checks the mode plus the certificate of every managed site.
### Ports, Cloudflare and the ACME challenge
HTTP-01 needs the name to point at the host and port 80 to answer. proxdomain
publishes the record **before** requesting a certificate, so a fresh `assign`
works without manual DNS steps. An orange-clouded record is fine for HTTP-01
because Cloudflare forwards `/.well-known/acme-challenge` over HTTP; if issuance
still fails, grey-cloud the record for the first run and re-enable it afterwards.
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. If Caddy or another
origin serves a self-signed certificate, use Cloudflare's **Full** mode rather
than **Full (strict)** until the Let's Encrypt certificate is in place.
## 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.
The one exception is a domain that needs an ACME certificate: then the DNS
record is created first, because ACME must resolve the name, and the TLS vhost is
written only after the certificate exists (for nginx, after certbot succeeds;
Caddy always goes DNS-first because it starts issuing as soon as it reloads). If
nginx issuance fails, the temporary HTTP vhost is removed and the error explains
what to check; re-running `assign` retries (it is idempotent).
* 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`. |
| Wrong port in the vhost | Check the `port` line of `assign`: `--port`, then the guest Notes/tag declaration, then the stored value, then `general.default_port`. |
| `401/403` from Proxmox | Token ACL or `--privsep`. Grant `VM.Audit VM.Monitor` on `/` (or at least `/vms`). |
| `token_secret_env ... must be the name of an environment variable` | The secret was pasted into the setting that should hold the variable name. Set `token_secret_env = "PROXDOMAIN_PVE_TOKEN"` and export the secret, or use `token_secret_file` / `token_secret`. |
| Secret reported as empty although it was set inline | `VAR=value && proxdomain ...` sets a variable and then runs an unrelated command. Use `export VAR=value` first, or `VAR=value proxdomain ...`. |
| `no Cloudflare zone found` | `general.base_domain` must be inside the zone, and the token must include that zone under Zone Resources. |
| `cannot determine the Proxmox host's public address` | Detection endpoints were unreachable or returned non-public addresses. Set `dns.address` (recommended) or `dns.hostname`. |
| `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. |
| `certbot failed for <domain>` | The name must resolve to this host and port 80 must be reachable. Check the A record, the firewall, and that nothing else answers `/.well-known/acme-challenge`. Rate limits need `acme_ca` pointed at staging while testing. |
| Site shows a certificate warning | The `:443` vhost was written before a certificate existed (mode `files`). Issue the certificate, or switch to mode `letsencrypt`. |
| `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
addressing.py host/fixed/guest resolution for the published DNS address
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
UNINSTALL.md step-by-step removal runbook
```
## 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.
* Host-address detection requires outbound HTTPS; pin `dns.address` on a host
where outbound traffic is filtered or NATed behind a different address.
* Automatic certificates cover the FQDN only: no wildcard, no DNS-01 (so a host
whose port 80 is blocked cannot use `tls.mode = "letsencrypt"` with nginx),
and `remove` leaves the Let's Encrypt certificate on disk for re-use.
* 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.