change app dns bind behavior
This commit is contained in:
1 parent
dd50a0d05e
commit
40a8ed23cd
17 files changed
+1440
-104
No files matched your search
@@ -10,29 +10,36 @@ broken config is rolled back before the reload.
|
|||||||
```
|
```
|
||||||
$ proxdomain assign --vmid 101
|
$ proxdomain assign --vmid 101
|
||||||
assign: ok
|
assign: ok
|
||||||
[ok ] guest web01 (qemu 101 on pve)
|
[ok ] guest sftpgo (lxc 101 on vz)
|
||||||
[ok ] address 10.0.0.5 (discovered)
|
[ok ] address guest 10.3.0.22 (discovered)
|
||||||
[ok ] domain web01.example.com
|
[ok ] dns-address 93.184.216.34 (detected via https://ipv4.icanhazip.com)
|
||||||
|
[ok ] domain sftpgo.example.com
|
||||||
[ok ] zone example.com (023e105f4ecef8ad9ca31a8372d0c353)
|
[ok ] zone example.com (023e105f4ecef8ad9ca31a8372d0c353)
|
||||||
[ok ] web-config created /etc/nginx/conf.d/proxdomain.d/web01.example.com.conf
|
[done] web-config created /etc/caddy/conf.d/sftpgo.example.com.caddy
|
||||||
[warn] dns 10.0.0.5 is not a public address, so the Cloudflare proxy
|
[ok ] tls Caddy requests and renews a Let's Encrypt certificate for this site
|
||||||
(orange cloud) was disabled; only the DNS record is created
|
[done] dns created A sftpgo.example.com -> 93.184.216.34 (proxied=yes)
|
||||||
[done] dns created A web01.example.com -> 10.0.0.5 (proxied=no)
|
[ok ] result sftpgo.example.com -> http://10.3.0.22:80 (published 93.184.216.34)
|
||||||
[ok ] result web01.example.com -> http://10.0.0.5:80
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## What it does
|
## What it does
|
||||||
|
|
||||||
1. **Proxmox** — finds the guest (`--vmid` or `--name`), then resolves its IP from
|
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
|
the QEMU guest agent, the LXC runtime interfaces, or the static `ip=` in the
|
||||||
guest config (in that order).
|
guest config (in that order). This is the **proxy target**, not the DNS value.
|
||||||
2. **Cloudflare** — discovers the zone by walking up from the FQDN, then creates
|
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
|
or patches the `A`/`AAAA` record. `proxied`, TTL and comment come from the
|
||||||
config; private/loopback targets automatically get a grey cloud.
|
config; non-public targets automatically get a grey cloud.
|
||||||
3. **Web server** — renders one file per domain (`nginx`, `Caddy` or `Traefik`
|
4. **Web server** — renders one file per domain (`nginx`, `Caddy` or `Traefik`
|
||||||
file provider) into a managed directory, runs the config test, and reloads.
|
file provider) into a managed directory, runs the config test, and reloads.
|
||||||
If the test fails, the previous file is restored.
|
If the test fails, the previous file is restored.
|
||||||
4. **State** — records the assignment in `state.json` plus an append-only
|
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.
|
`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
|
The app never creates VMs and never installs a web server; it wires an existing
|
||||||
@@ -87,6 +94,12 @@ for the guest-agent IP query. Put the token in the environment, not in the file:
|
|||||||
export PROXDOMAIN_PVE_TOKEN='00000000-0000-0000-0000-000000000000'
|
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
|
### Cloudflare API token
|
||||||
|
|
||||||
Create a token with **Zone → Zone:Read** and **Zone → DNS:Edit**, limited to the
|
Create a token with **Zone → Zone:Read** and **Zone → DNS:Edit**, limited to the
|
||||||
@@ -110,6 +123,28 @@ in [`config.example.toml`](config.example.toml).
|
|||||||
The config is read from `--config`, then `$PROXDOMAIN_CONFIG`, then
|
The config is read from `--config`, then `$PROXDOMAIN_CONFIG`, then
|
||||||
`./proxdomain.toml`, then `/etc/proxdomain/config.toml`.
|
`./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:
|
Then create the managed directory and the include line:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -152,6 +187,9 @@ proxdomain assign --vmid 101 --subdomain app.example.net
|
|||||||
# guest IP discovery is wrong? override it, or force the orange cloud
|
# guest IP discovery is wrong? override it, or force the orange cloud
|
||||||
proxdomain assign --vmid 101 --ip 10.0.0.5 --proxied
|
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
|
# after changing template/port/TLS settings, re-apply every site
|
||||||
proxdomain sync --dry-run
|
proxdomain sync --dry-run
|
||||||
proxdomain sync
|
proxdomain sync
|
||||||
@@ -207,21 +245,53 @@ Or in cron: `*/2 * * * * /usr/local/bin/proxdomain watch --once --auto-assign`.
|
|||||||
|
|
||||||
## TLS
|
## 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 |
|
| `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 |
|
| `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) |
|
| `files` | `:80` redirect + `:443` vhost with `cert_dir/<fqdn>/{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 |
|
| `certbot` | Alias of `letsencrypt` for nginx, kept for older configs | — |
|
||||||
|
|
||||||
For `certbot`, the domain must resolve to the host and port 80 must be reachable
|
How each web server gets the certificate:
|
||||||
from the internet. Keep the Cloudflare record grey-clouded until the certificate
|
|
||||||
is issued, otherwise Cloudflare's edge answers the challenge. Caddy manages its
|
* **nginx** — for a domain with no certificate, proxdomain first activates an
|
||||||
own certificates, so `none`/`files` are the only meaningful modes there; for
|
HTTP-only vhost, runs `certbot certonly --webroot --keep-until-expiring`
|
||||||
Traefik set `webserver.cert_resolver`.
|
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
|
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
|
standard HTTP/HTTPS ports. Publish the reverse proxy on 80/443, not on an
|
||||||
arbitrary high port, or disable proxying for that record.
|
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
|
## How an assignment is ordered
|
||||||
|
|
||||||
@@ -229,6 +299,13 @@ 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
|
starts resolving, so a failure never leaves a public name pointing at an
|
||||||
unconfigured proxy.
|
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
|
* Config test fails → the new file is removed (or the old one restored) and the
|
||||||
error is reported; DNS is untouched.
|
error is reported; DNS is untouched.
|
||||||
* Reload fails after a valid test → the config is kept (it is valid) and the
|
* Reload fails after a valid test → the config is kept (it is valid) and the
|
||||||
@@ -258,9 +335,14 @@ records every config/DNS/remove action with a UTC timestamp.
|
|||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `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`. |
|
| `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`). |
|
| `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. |
|
| `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. |
|
| `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. |
|
| `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. |
|
| `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. |
|
| `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. |
|
| Cloudflare 522/521 | The origin address or port is unreachable from Cloudflare. Check the guest firewall and that the proxy listens on 80/443. |
|
||||||
@@ -273,6 +355,7 @@ records every config/DNS/remove action with a UTC timestamp.
|
|||||||
proxdomain/
|
proxdomain/
|
||||||
cli.py argparse commands and output
|
cli.py argparse commands and output
|
||||||
config.py TOML parsing, per-kind defaults, secret resolution
|
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
|
http.py urllib JSON client with retries and an injectable transport
|
||||||
proxmox.py guest inventory, tag parsing, IP resolution
|
proxmox.py guest inventory, tag parsing, IP resolution
|
||||||
cloudflare.py zone discovery, A/AAAA upsert, delete
|
cloudflare.py zone discovery, A/AAAA upsert, delete
|
||||||
@@ -299,6 +382,11 @@ Proxmox host or Cloudflare account.
|
|||||||
## Limits
|
## Limits
|
||||||
|
|
||||||
* One `A`/`AAAA` record per name; no CNAME, wildcard or Cloudflare Tunnel setup.
|
* 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
|
* The record type follows `proxmox.ip_preference`; a stale record of the other
|
||||||
type is left alone and reported in `list` as managed separately.
|
type is left alone and reported in `list` as managed separately.
|
||||||
* Removal only knows about assignments in `state.json`; deleting the state file
|
* Removal only knows about assignments in `state.json`; deleting the state file
|
||||||
|
|||||||
+31
-6
@@ -12,6 +12,23 @@ domain_template = "{hostname}.{base_domain}"
|
|||||||
# Backend port used when `assign` is called without --port.
|
# Backend port used when `assign` is called without --port.
|
||||||
default_port = 80
|
default_port = 80
|
||||||
|
|
||||||
|
[dns]
|
||||||
|
# What the public Cloudflare record points at:
|
||||||
|
# host - the Proxmox host's public address (default; it runs the reverse proxy)
|
||||||
|
# fixed - the literal dns.address below
|
||||||
|
# guest - the guest's own address (only when guests hold public IPs)
|
||||||
|
target = "host"
|
||||||
|
# Explicit public address of the Proxmox host. Recommended: skips detection and
|
||||||
|
# works on hosts whose outbound address differs from their inbound one.
|
||||||
|
# address = "93.184.216.34"
|
||||||
|
# Alternative to address: resolve the host's own FQDN instead of using a detector.
|
||||||
|
# hostname = "pve.example.com"
|
||||||
|
# Used when neither address nor hostname is set. The v4 URL is queried for
|
||||||
|
# ip_preference = "ipv4", the v6 URL for "ipv6", both for "auto".
|
||||||
|
detect_url_v4 = "https://ipv4.icanhazip.com"
|
||||||
|
detect_url_v6 = "https://ipv6.icanhazip.com"
|
||||||
|
detect_timeout = 5
|
||||||
|
|
||||||
[proxmox]
|
[proxmox]
|
||||||
# Proxmox VE API endpoint (note the /api2/json suffix and port 8006).
|
# Proxmox VE API endpoint (note the /api2/json suffix and port 8006).
|
||||||
api_url = "https://pve.example.com:8006/api2/json"
|
api_url = "https://pve.example.com:8006/api2/json"
|
||||||
@@ -68,17 +85,25 @@ manage_dir = "/etc/nginx/conf.d/proxdomain.d"
|
|||||||
# cert_resolver = "letsencrypt"
|
# cert_resolver = "letsencrypt"
|
||||||
|
|
||||||
[webserver.tls]
|
[webserver.tls]
|
||||||
# none - proxy listens on :80 (Cloudflare terminates TLS, or plain HTTP)
|
# none - proxy listens on :80 (Cloudflare terminates TLS, or plain HTTP)
|
||||||
# files - serve :443 using cert_dir/<fqdn>/{fullchain,privkey}.pem
|
# letsencrypt - automatic HTTPS with a Let's Encrypt certificate (recommended)
|
||||||
# certbot - obtain the certificate with certbot (nginx only); the app first
|
# files - serve :443 using cert_dir/<fqdn>/{fullchain,privkey}.pem
|
||||||
# activates an HTTP vhost to answer the ACME challenge
|
# certbot - alias of letsencrypt for nginx (kept for older configs)
|
||||||
|
#
|
||||||
|
# nginx : proxdomain runs certbot (webroot/HTTP-01), then writes the :443 vhost
|
||||||
|
# caddy : the site block pins the ACME issuer to Let's Encrypt
|
||||||
|
# traefik : the router uses cert_resolver
|
||||||
mode = "none"
|
mode = "none"
|
||||||
cert_dir = "/etc/letsencrypt/live"
|
cert_dir = "/etc/letsencrypt/live"
|
||||||
webroot = "/var/www/certbot"
|
webroot = "/var/www/certbot"
|
||||||
# Required for mode = "certbot":
|
# Required for mode = "letsencrypt"/"certbot": Let's Encrypt expiry notices.
|
||||||
# email = "ops@example.com"
|
# email = "ops@example.com"
|
||||||
|
# Alternative ACME directory: staging endpoint, Pebble, or another CA.
|
||||||
|
# acme_ca = "https://acme-staging-v02.api.letsencrypt.org/directory"
|
||||||
|
# Command run by certbot after each renewal. Default: reload_command.
|
||||||
|
# renew_hook = "systemctl reload nginx"
|
||||||
# certbot_command = ["certbot", "certonly", "--webroot", "-w", "/var/www/certbot", "-n", "--agree-tos"]
|
# certbot_command = ["certbot", "certonly", "--webroot", "-w", "/var/www/certbot", "-n", "--agree-tos"]
|
||||||
# extra_args = ["--deploy-hook", "systemctl reload nginx"]
|
# extra_args = ["--preferred-chain", "ISRG Root X1"]
|
||||||
|
|
||||||
[watch]
|
[watch]
|
||||||
# Used by `proxdomain watch`; the command itself is safe to run from cron/systemd.
|
# Used by `proxdomain watch`; the command itself is safe to run from cron/systemd.
|
||||||
|
|||||||
@@ -7,5 +7,5 @@ reverse-proxy config for nginx, Caddy or Traefik.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
__version__ = "0.1.0"
|
__version__ = "0.3.0"
|
||||||
__all__ = ["__version__"]
|
__all__ = ["__version__"]
|
||||||
Executable
+204
@@ -0,0 +1,204 @@
|
|||||||
|
"""Decide which address the public DNS record points at.
|
||||||
|
|
||||||
|
Reverse proxies normally run on the Proxmox host, so the record must publish the
|
||||||
|
host's public address while the vhost keeps proxying to the guest's private one.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ipaddress
|
||||||
|
import socket
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Callable, Sequence
|
||||||
|
|
||||||
|
from . import __version__
|
||||||
|
from .config import DnsConfig
|
||||||
|
from .errors import ProxdomainError
|
||||||
|
from .http import Transport, UrllibTransport
|
||||||
|
|
||||||
|
HostnameResolver = Callable[[str], Sequence[str]]
|
||||||
|
TextFetcher = Callable[[str], str]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ResolvedAddress:
|
||||||
|
address: str
|
||||||
|
source: str
|
||||||
|
|
||||||
|
|
||||||
|
class PublicAddressResolver:
|
||||||
|
"""Resolve the address to publish, according to `[dns] target`.
|
||||||
|
|
||||||
|
The host result is cached for the lifetime of the resolver (one sync run),
|
||||||
|
so a batch of assignments performs at most one detection request.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
config: DnsConfig,
|
||||||
|
*,
|
||||||
|
preference: str = "ipv4",
|
||||||
|
transport: Transport | None = None,
|
||||||
|
fetch_text: TextFetcher | None = None,
|
||||||
|
hostname_resolver: HostnameResolver | None = None,
|
||||||
|
) -> None:
|
||||||
|
self.config = config
|
||||||
|
self.preference = preference
|
||||||
|
self._transport = transport
|
||||||
|
self._fetch_text = fetch_text
|
||||||
|
self._hostname_resolver = hostname_resolver or system_hostname_addresses
|
||||||
|
self._host_cache: ResolvedAddress | None = None
|
||||||
|
|
||||||
|
def resolve(
|
||||||
|
self, *, guest_address: str = "", override: str | None = None
|
||||||
|
) -> ResolvedAddress:
|
||||||
|
if override:
|
||||||
|
return ResolvedAddress(_require_ip(override, "the --address override"), "command line")
|
||||||
|
if self.config.target == "guest":
|
||||||
|
return ResolvedAddress(_require_ip(guest_address, "the guest address"), "guest")
|
||||||
|
if self.config.target == "fixed":
|
||||||
|
return ResolvedAddress(
|
||||||
|
_require_ip(self.config.address, "dns.address"), "dns.address"
|
||||||
|
)
|
||||||
|
if self._host_cache is None:
|
||||||
|
self._host_cache = self._resolve_host()
|
||||||
|
return self._host_cache
|
||||||
|
|
||||||
|
# -- host resolution ------------------------------------------------
|
||||||
|
def _resolve_host(self) -> ResolvedAddress:
|
||||||
|
if self.config.address:
|
||||||
|
return ResolvedAddress(
|
||||||
|
_require_ip(self.config.address, "dns.address"), "dns.address"
|
||||||
|
)
|
||||||
|
if self.config.hostname:
|
||||||
|
return self._from_hostname()
|
||||||
|
return self._detect()
|
||||||
|
|
||||||
|
def _from_hostname(self) -> ResolvedAddress:
|
||||||
|
hostname = self.config.hostname
|
||||||
|
try:
|
||||||
|
raw = self._hostname_resolver(hostname)
|
||||||
|
except OSError as exc:
|
||||||
|
raise ProxdomainError(
|
||||||
|
f"cannot resolve dns.hostname {hostname}: {exc}; "
|
||||||
|
"set dns.address instead"
|
||||||
|
) from exc
|
||||||
|
parsed: list[ipaddress._BaseAddress] = []
|
||||||
|
for value in raw:
|
||||||
|
try:
|
||||||
|
parsed.append(ipaddress.ip_address(str(value)))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
public = [address for address in parsed if address.is_global]
|
||||||
|
chosen = _pick(public or parsed, self.preference)
|
||||||
|
if chosen is None:
|
||||||
|
raise ProxdomainError(
|
||||||
|
f"dns.hostname {hostname} did not resolve to a "
|
||||||
|
f"{self.preference} address; set dns.address instead"
|
||||||
|
)
|
||||||
|
return ResolvedAddress(str(chosen), f"hostname {hostname}")
|
||||||
|
|
||||||
|
def _detect(self) -> ResolvedAddress:
|
||||||
|
urls = self._detect_urls()
|
||||||
|
if not urls:
|
||||||
|
raise ProxdomainError(
|
||||||
|
"dns.target = 'host' has no dns.address, dns.hostname or detection URL; "
|
||||||
|
"set dns.address"
|
||||||
|
)
|
||||||
|
failures: list[str] = []
|
||||||
|
for url in urls:
|
||||||
|
try:
|
||||||
|
text = self._get(url)
|
||||||
|
except ProxdomainError as exc:
|
||||||
|
failures.append(str(exc))
|
||||||
|
continue
|
||||||
|
candidate = extract_address(text)
|
||||||
|
if candidate is None:
|
||||||
|
failures.append(f"{url} returned no IP address")
|
||||||
|
continue
|
||||||
|
address = ipaddress.ip_address(candidate)
|
||||||
|
if not address.is_global:
|
||||||
|
failures.append(f"{url} returned the non-public address {candidate}")
|
||||||
|
continue
|
||||||
|
return ResolvedAddress(str(address), f"detected via {url}")
|
||||||
|
raise ProxdomainError(
|
||||||
|
"cannot determine the Proxmox host's public address: "
|
||||||
|
+ "; ".join(failures)
|
||||||
|
+ "; set dns.address (or dns.hostname) in the config, or pass --address"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _detect_urls(self) -> list[str]:
|
||||||
|
if self.preference == "ipv4":
|
||||||
|
candidates = [self.config.detect_url_v4]
|
||||||
|
elif self.preference == "ipv6":
|
||||||
|
candidates = [self.config.detect_url_v6]
|
||||||
|
else:
|
||||||
|
candidates = [self.config.detect_url_v4, self.config.detect_url_v6]
|
||||||
|
return [url for url in candidates if url]
|
||||||
|
|
||||||
|
def _get(self, url: str) -> str:
|
||||||
|
if self._fetch_text is not None:
|
||||||
|
return self._fetch_text(url)
|
||||||
|
transport = self._transport or UrllibTransport()
|
||||||
|
try:
|
||||||
|
response = transport.request(
|
||||||
|
"GET",
|
||||||
|
url,
|
||||||
|
{
|
||||||
|
"User-Agent": f"proxdomain/{__version__}",
|
||||||
|
"Accept": "text/plain",
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
self.config.detect_timeout,
|
||||||
|
)
|
||||||
|
except ProxdomainError:
|
||||||
|
raise
|
||||||
|
except Exception as exc: # pragma: no cover - defensive around urllib
|
||||||
|
raise ProxdomainError(f"cannot reach {url}: {exc}") from exc
|
||||||
|
if response.status >= 400:
|
||||||
|
raise ProxdomainError(f"GET {url} -> HTTP {response.status}")
|
||||||
|
return response.text()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def extract_address(text: str) -> str | None:
|
||||||
|
"""Accept `203.0.113.10`, `ip=203.0.113.10` (Cloudflare trace) or a sentence."""
|
||||||
|
for line in text.splitlines():
|
||||||
|
candidate_line = line.strip()
|
||||||
|
if not candidate_line:
|
||||||
|
continue
|
||||||
|
if candidate_line.startswith("ip="):
|
||||||
|
candidates = [candidate_line[3:]]
|
||||||
|
else:
|
||||||
|
candidates = candidate_line.replace("=", " ").split()
|
||||||
|
for candidate in candidates:
|
||||||
|
candidate = candidate.strip().strip("\"'")
|
||||||
|
try:
|
||||||
|
return str(ipaddress.ip_address(candidate))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def system_hostname_addresses(hostname: str) -> list[str]:
|
||||||
|
infos = socket.getaddrinfo(hostname, None, type=socket.SOCK_STREAM)
|
||||||
|
seen: list[str] = []
|
||||||
|
for info in infos:
|
||||||
|
value = str(info[4][0])
|
||||||
|
if value not in seen:
|
||||||
|
seen.append(value)
|
||||||
|
return seen
|
||||||
|
|
||||||
|
|
||||||
|
def _pick(addresses: Sequence[ipaddress._BaseAddress], preference: str):
|
||||||
|
wanted = 4 if preference == "ipv4" else 6 if preference == "ipv6" else None
|
||||||
|
if wanted is not None:
|
||||||
|
addresses = [address for address in addresses if address.version == wanted]
|
||||||
|
return addresses[0] if addresses else None
|
||||||
|
|
||||||
|
|
||||||
|
def _require_ip(value: str, label: str) -> str:
|
||||||
|
try:
|
||||||
|
return str(ipaddress.ip_address(str(value).strip()))
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ProxdomainError(f"{label} is not a valid IP address: {value!r}") from exc
|
||||||
+10
-4
@@ -65,7 +65,11 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
help="subdomain label (app) or full name (app.example.com); default: from domain_template",
|
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("--port", type=int, help="backend port on the guest (default: general.default_port)")
|
||||||
assign.add_argument("--ip", help="override the discovered guest IP")
|
assign.add_argument("--ip", help="override the guest IP used as the proxy target")
|
||||||
|
assign.add_argument(
|
||||||
|
"--address",
|
||||||
|
help="override the published DNS address (default: the Proxmox host public IP)",
|
||||||
|
)
|
||||||
assign.add_argument(
|
assign.add_argument(
|
||||||
"--proxied",
|
"--proxied",
|
||||||
dest="proxied",
|
dest="proxied",
|
||||||
@@ -161,6 +165,7 @@ def main(argv: list[str] | None = None) -> int:
|
|||||||
subdomain=args.subdomain,
|
subdomain=args.subdomain,
|
||||||
port=args.port,
|
port=args.port,
|
||||||
ip=args.ip,
|
ip=args.ip,
|
||||||
|
address=args.address,
|
||||||
proxied=args.proxied,
|
proxied=args.proxied,
|
||||||
force=args.force,
|
force=args.force,
|
||||||
dry_run=args.dry_run,
|
dry_run=args.dry_run,
|
||||||
@@ -226,14 +231,15 @@ def _list(service: DomainService, json_output: bool) -> int:
|
|||||||
print("no managed domains yet (run: proxdomain assign --vmid <id>)")
|
print("no managed domains yet (run: proxdomain assign --vmid <id>)")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
headers = ("FQDN", "VMID", "NODE", "IP", "PORT", "DNS")
|
headers = ("FQDN", "VMID", "NODE", "TARGET", "PUBLISHED", "TLS", "RECORD")
|
||||||
rows = [
|
rows = [
|
||||||
(
|
(
|
||||||
item.fqdn,
|
item.fqdn,
|
||||||
str(item.vmid),
|
str(item.vmid),
|
||||||
item.node,
|
item.node,
|
||||||
item.ip or "-",
|
f"{item.ip or '-'}:{item.port}",
|
||||||
str(item.port),
|
item.dns_ip or "-",
|
||||||
|
item.tls or "none",
|
||||||
"yes" if item.record_id else "-",
|
"yes" if item.record_id else "-",
|
||||||
)
|
)
|
||||||
for item in items
|
for item in items
|
||||||
|
|||||||
+102
-19
@@ -2,7 +2,9 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ipaddress
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
import tomllib
|
import tomllib
|
||||||
from dataclasses import dataclass, replace
|
from dataclasses import dataclass, replace
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -18,7 +20,7 @@ DEFAULT_CONFIG_PATHS = (
|
|||||||
|
|
||||||
WEBSERVER_KINDS = ("nginx", "caddy", "traefik")
|
WEBSERVER_KINDS = ("nginx", "caddy", "traefik")
|
||||||
WEBSERVER_MODES = ("local", "ssh")
|
WEBSERVER_MODES = ("local", "ssh")
|
||||||
TLS_MODES = ("none", "files", "certbot")
|
TLS_MODES = ("none", "files", "certbot", "letsencrypt")
|
||||||
IP_PREFERENCES = ("auto", "ipv4", "ipv6")
|
IP_PREFERENCES = ("auto", "ipv4", "ipv6")
|
||||||
|
|
||||||
# Web server defaults live here so `config.example.toml` and the docs stay honest.
|
# Web server defaults live here so `config.example.toml` and the docs stay honest.
|
||||||
@@ -52,6 +54,23 @@ class GeneralConfig:
|
|||||||
default_port: int = 80
|
default_port: int = 80
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class DnsConfig:
|
||||||
|
"""What the public DNS record points at.
|
||||||
|
|
||||||
|
guest - the guest's own address (useful when guests hold public IPs)
|
||||||
|
host - the Proxmox host's public address, which runs the reverse proxy
|
||||||
|
fixed - the literal address in dns.address
|
||||||
|
"""
|
||||||
|
|
||||||
|
target: str = "host" # guest | host | fixed
|
||||||
|
address: str = ""
|
||||||
|
hostname: str = ""
|
||||||
|
detect_url_v4: str = "https://ipv4.icanhazip.com"
|
||||||
|
detect_url_v6: str = "https://ipv6.icanhazip.com"
|
||||||
|
detect_timeout: float = 5.0
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class ProxmoxConfig:
|
class ProxmoxConfig:
|
||||||
api_url: str
|
api_url: str
|
||||||
@@ -70,13 +89,11 @@ class ProxmoxConfig:
|
|||||||
|
|
||||||
def resolve_secret(self) -> str:
|
def resolve_secret(self) -> str:
|
||||||
if self.token_secret_env:
|
if self.token_secret_env:
|
||||||
value = os.environ.get(self.token_secret_env, "")
|
return _env_secret(
|
||||||
if not value:
|
self.token_secret_env,
|
||||||
raise ConfigError(
|
setting="proxmox.token_secret_env",
|
||||||
f"environment variable {self.token_secret_env} "
|
alternative="proxmox.token_secret",
|
||||||
"(proxmox.token_secret_env) is empty or unset"
|
)
|
||||||
)
|
|
||||||
return value
|
|
||||||
if self.token_secret_file:
|
if self.token_secret_file:
|
||||||
path = Path(self.token_secret_file).expanduser()
|
path = Path(self.token_secret_file).expanduser()
|
||||||
try:
|
try:
|
||||||
@@ -108,13 +125,11 @@ class CloudflareConfig:
|
|||||||
|
|
||||||
def resolve_token(self) -> str:
|
def resolve_token(self) -> str:
|
||||||
if self.api_token_env:
|
if self.api_token_env:
|
||||||
value = os.environ.get(self.api_token_env, "")
|
return _env_secret(
|
||||||
if not value:
|
self.api_token_env,
|
||||||
raise ConfigError(
|
setting="cloudflare.api_token_env",
|
||||||
f"environment variable {self.api_token_env} "
|
alternative="cloudflare.api_token",
|
||||||
"(cloudflare.api_token_env) is empty or unset"
|
)
|
||||||
)
|
|
||||||
return value
|
|
||||||
if self.api_token_file:
|
if self.api_token_file:
|
||||||
path = Path(self.api_token_file).expanduser()
|
path = Path(self.api_token_file).expanduser()
|
||||||
try:
|
try:
|
||||||
@@ -136,13 +151,17 @@ class CloudflareConfig:
|
|||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class TlsConfig:
|
class TlsConfig:
|
||||||
mode: str = "none" # none | files | certbot
|
mode: str = "none" # none | files | certbot | letsencrypt
|
||||||
cert_dir: str = "/etc/letsencrypt/live"
|
cert_dir: str = "/etc/letsencrypt/live"
|
||||||
webroot: str = "/var/www/certbot"
|
webroot: str = "/var/www/certbot"
|
||||||
certbot_command: tuple[str, ...] = (
|
certbot_command: tuple[str, ...] = (
|
||||||
"certbot", "certonly", "--webroot", "-w", "/var/www/certbot", "-n", "--agree-tos",
|
"certbot", "certonly", "--webroot", "-w", "/var/www/certbot", "-n", "--agree-tos",
|
||||||
)
|
)
|
||||||
email: str = ""
|
email: str = ""
|
||||||
|
# Alternative ACME directory (staging, Pebble, ...). Empty = Let's Encrypt production.
|
||||||
|
acme_ca: str = ""
|
||||||
|
# Command run after each renewal; empty = the web server's reload command.
|
||||||
|
renew_hook: str = ""
|
||||||
extra_args: tuple[str, ...] = ()
|
extra_args: tuple[str, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
@@ -195,6 +214,7 @@ class Config:
|
|||||||
proxmox: ProxmoxConfig
|
proxmox: ProxmoxConfig
|
||||||
cloudflare: CloudflareConfig
|
cloudflare: CloudflareConfig
|
||||||
webserver: WebServerConfig
|
webserver: WebServerConfig
|
||||||
|
dns: DnsConfig = DnsConfig()
|
||||||
watch: WatchConfig = WatchConfig()
|
watch: WatchConfig = WatchConfig()
|
||||||
state: StateConfig = StateConfig()
|
state: StateConfig = StateConfig()
|
||||||
source: Path | None = None
|
source: Path | None = None
|
||||||
@@ -245,6 +265,7 @@ def parse_config(raw: Mapping[str, Any], *, source: Path | None = None) -> Confi
|
|||||||
watch_raw = _table(raw, "watch")
|
watch_raw = _table(raw, "watch")
|
||||||
state_raw = _table(raw, "state")
|
state_raw = _table(raw, "state")
|
||||||
tls_raw = _table(webserver_raw, "tls", prefix="webserver")
|
tls_raw = _table(webserver_raw, "tls", prefix="webserver")
|
||||||
|
dns_raw = _table(raw, "dns")
|
||||||
|
|
||||||
general = GeneralConfig(
|
general = GeneralConfig(
|
||||||
base_domain=_str(general_raw, "base_domain", required=True, prefix="general"),
|
base_domain=_str(general_raw, "base_domain", required=True, prefix="general"),
|
||||||
@@ -320,10 +341,16 @@ def parse_config(raw: Mapping[str, Any], *, source: Path | None = None) -> Confi
|
|||||||
certbot_command=_str_tuple(tls_raw, "certbot_command", prefix="webserver.tls")
|
certbot_command=_str_tuple(tls_raw, "certbot_command", prefix="webserver.tls")
|
||||||
or TlsConfig.certbot_command,
|
or TlsConfig.certbot_command,
|
||||||
email=_str(tls_raw, "email", "", prefix="webserver.tls"),
|
email=_str(tls_raw, "email", "", prefix="webserver.tls"),
|
||||||
|
acme_ca=_str(tls_raw, "acme_ca", "", prefix="webserver.tls"),
|
||||||
|
renew_hook=_str(tls_raw, "renew_hook", "", prefix="webserver.tls"),
|
||||||
extra_args=_str_tuple(tls_raw, "extra_args", prefix="webserver.tls"),
|
extra_args=_str_tuple(tls_raw, "extra_args", prefix="webserver.tls"),
|
||||||
)
|
)
|
||||||
if tls.mode == "certbot" and not tls.email:
|
if tls.mode in ("certbot", "letsencrypt") and not tls.email:
|
||||||
raise ConfigError("webserver.tls.email is required when tls.mode = 'certbot'")
|
raise ConfigError(
|
||||||
|
"webserver.tls.email is required when tls.mode is 'certbot' or 'letsencrypt'"
|
||||||
|
)
|
||||||
|
if tls.acme_ca and not tls.acme_ca.startswith(("http://", "https://")):
|
||||||
|
raise ConfigError("webserver.tls.acme_ca must start with https://")
|
||||||
|
|
||||||
webserver = WebServerConfig(
|
webserver = WebServerConfig(
|
||||||
kind=kind,
|
kind=kind,
|
||||||
@@ -346,19 +373,45 @@ def parse_config(raw: Mapping[str, Any], *, source: Path | None = None) -> Confi
|
|||||||
if kind != "nginx" and tls.mode == "certbot":
|
if kind != "nginx" and tls.mode == "certbot":
|
||||||
raise ConfigError(
|
raise ConfigError(
|
||||||
"webserver.tls.mode = 'certbot' is only supported with kind = 'nginx'; "
|
"webserver.tls.mode = 'certbot' is only supported with kind = 'nginx'; "
|
||||||
"use 'none' (Caddy manages certificates itself) or 'files'"
|
"use 'letsencrypt' (automatic for Caddy/Traefik) or 'files'"
|
||||||
)
|
)
|
||||||
if kind == "traefik" and tls.mode == "files":
|
if kind == "traefik" and tls.mode == "files":
|
||||||
raise ConfigError(
|
raise ConfigError(
|
||||||
"webserver.tls.mode = 'files' is not supported with kind = 'traefik'; "
|
"webserver.tls.mode = 'files' is not supported with kind = 'traefik'; "
|
||||||
"set webserver.cert_resolver instead"
|
"set webserver.cert_resolver instead"
|
||||||
)
|
)
|
||||||
|
if kind == "traefik" and tls.mode == "letsencrypt" and not webserver.cert_resolver:
|
||||||
|
raise ConfigError(
|
||||||
|
"webserver.cert_resolver is required when kind = 'traefik' and "
|
||||||
|
"tls.mode = 'letsencrypt'"
|
||||||
|
)
|
||||||
|
|
||||||
state = StateConfig(
|
state = StateConfig(
|
||||||
path=_str(state_raw, "path", StateConfig.path, prefix="state"),
|
path=_str(state_raw, "path", StateConfig.path, prefix="state"),
|
||||||
audit_path=_str(state_raw, "audit_path", "", prefix="state"),
|
audit_path=_str(state_raw, "audit_path", "", prefix="state"),
|
||||||
lock_timeout=_float(state_raw, "lock_timeout", 10.0, prefix="state"),
|
lock_timeout=_float(state_raw, "lock_timeout", 10.0, prefix="state"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
dns = DnsConfig(
|
||||||
|
target=_choice(dns_raw, "target", "host", ("guest", "host", "fixed"), prefix="dns"),
|
||||||
|
address=_str(dns_raw, "address", "", prefix="dns"),
|
||||||
|
hostname=_str(dns_raw, "hostname", "", prefix="dns"),
|
||||||
|
detect_url_v4=_str(dns_raw, "detect_url_v4", DnsConfig.detect_url_v4, prefix="dns"),
|
||||||
|
detect_url_v6=_str(dns_raw, "detect_url_v6", DnsConfig.detect_url_v6, prefix="dns"),
|
||||||
|
detect_timeout=_float(dns_raw, "detect_timeout", 5.0, prefix="dns"),
|
||||||
|
)
|
||||||
|
if dns.address:
|
||||||
|
try:
|
||||||
|
ipaddress.ip_address(dns.address)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ConfigError(f"dns.address is not a valid IP address: {dns.address!r}") from exc
|
||||||
|
if dns.target == "fixed" and not dns.address:
|
||||||
|
raise ConfigError("dns.address is required when dns.target = 'fixed'")
|
||||||
|
if dns.detect_timeout <= 0:
|
||||||
|
raise ConfigError("dns.detect_timeout must be greater than zero")
|
||||||
|
for key, value in (("detect_url_v4", dns.detect_url_v4), ("detect_url_v6", dns.detect_url_v6)):
|
||||||
|
if value and not value.startswith(("http://", "https://")):
|
||||||
|
raise ConfigError(f"dns.{key} must start with http:// or https://")
|
||||||
watch = WatchConfig(
|
watch = WatchConfig(
|
||||||
enabled=_bool(watch_raw, "enabled", False, prefix="watch"),
|
enabled=_bool(watch_raw, "enabled", False, prefix="watch"),
|
||||||
interval=max(5, _int(watch_raw, "interval", 60, prefix="watch")),
|
interval=max(5, _int(watch_raw, "interval", 60, prefix="watch")),
|
||||||
@@ -372,6 +425,7 @@ def parse_config(raw: Mapping[str, Any], *, source: Path | None = None) -> Confi
|
|||||||
proxmox=proxmox,
|
proxmox=proxmox,
|
||||||
cloudflare=cloudflare,
|
cloudflare=cloudflare,
|
||||||
webserver=webserver,
|
webserver=webserver,
|
||||||
|
dns=dns,
|
||||||
watch=watch,
|
watch=watch,
|
||||||
state=state,
|
state=state,
|
||||||
source=source,
|
source=source,
|
||||||
@@ -386,6 +440,35 @@ def with_overrides(config: Config, **overrides: Any) -> Config:
|
|||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# helpers
|
# helpers
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
_ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
||||||
|
_UUID_RE = re.compile(
|
||||||
|
r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _env_secret(name: str, *, setting: str, alternative: str) -> str:
|
||||||
|
"""Read a secret from the environment variable named by a config setting."""
|
||||||
|
name = name.strip()
|
||||||
|
if not _ENV_NAME_RE.match(name):
|
||||||
|
hint = ""
|
||||||
|
if _UUID_RE.match(name):
|
||||||
|
hint = (
|
||||||
|
"; this looks like the token value itself — put the secret in "
|
||||||
|
f"{alternative} (or a *_file setting) and set {setting} to the "
|
||||||
|
"variable NAME, for example PROXDOMAIN_PVE_TOKEN"
|
||||||
|
)
|
||||||
|
raise ConfigError(
|
||||||
|
f"{setting} must be the name of an environment variable, not {name!r}{hint}"
|
||||||
|
)
|
||||||
|
value = os.environ.get(name, "")
|
||||||
|
if not value:
|
||||||
|
raise ConfigError(
|
||||||
|
f"{setting} points at environment variable {name}, which is empty or "
|
||||||
|
f"unset; export {name} before running proxdomain"
|
||||||
|
)
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
def _table(raw: Mapping[str, Any], key: str, *, prefix: str = "") -> Mapping[str, Any]:
|
def _table(raw: Mapping[str, Any], key: str, *, prefix: str = "") -> Mapping[str, Any]:
|
||||||
value = raw.get(key, {})
|
value = raw.get(key, {})
|
||||||
if not isinstance(value, Mapping):
|
if not isinstance(value, Mapping):
|
||||||
|
|||||||
+299
-41
@@ -6,6 +6,7 @@ import ipaddress
|
|||||||
import re
|
import re
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
from .addressing import PublicAddressResolver
|
||||||
from .cloudflare import CloudflareClient, Zone
|
from .cloudflare import CloudflareClient, Zone
|
||||||
from .config import Config
|
from .config import Config
|
||||||
from .errors import ConfigError, ProxdomainError
|
from .errors import ConfigError, ProxdomainError
|
||||||
@@ -60,6 +61,7 @@ class DomainService:
|
|||||||
cloudflare: CloudflareClient | None = None,
|
cloudflare: CloudflareClient | None = None,
|
||||||
webserver: WebServerManager | None = None,
|
webserver: WebServerManager | None = None,
|
||||||
state: StateStore | None = None,
|
state: StateStore | None = None,
|
||||||
|
dns_resolver: PublicAddressResolver | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
self.config = config
|
self.config = config
|
||||||
self.state = state or StateStore(
|
self.state = state or StateStore(
|
||||||
@@ -71,6 +73,7 @@ class DomainService:
|
|||||||
self._proxmox = proxmox
|
self._proxmox = proxmox
|
||||||
self._cloudflare = cloudflare
|
self._cloudflare = cloudflare
|
||||||
self._webserver = webserver
|
self._webserver = webserver
|
||||||
|
self._dns_resolver = dns_resolver
|
||||||
|
|
||||||
# -- lazy clients (so `list` works without API credentials) ---------
|
# -- lazy clients (so `list` works without API credentials) ---------
|
||||||
@property
|
@property
|
||||||
@@ -93,6 +96,14 @@ class DomainService:
|
|||||||
)
|
)
|
||||||
return self._webserver
|
return self._webserver
|
||||||
|
|
||||||
|
@property
|
||||||
|
def dns_resolver(self) -> PublicAddressResolver:
|
||||||
|
if self._dns_resolver is None:
|
||||||
|
self._dns_resolver = PublicAddressResolver(
|
||||||
|
self.config.dns, preference=self.config.proxmox.ip_preference
|
||||||
|
)
|
||||||
|
return self._dns_resolver
|
||||||
|
|
||||||
# -- main workflow --------------------------------------------------
|
# -- main workflow --------------------------------------------------
|
||||||
def assign(
|
def assign(
|
||||||
self,
|
self,
|
||||||
@@ -102,6 +113,7 @@ class DomainService:
|
|||||||
subdomain: str | None = None,
|
subdomain: str | None = None,
|
||||||
port: int | None = None,
|
port: int | None = None,
|
||||||
ip: str | None = None,
|
ip: str | None = None,
|
||||||
|
address: str | None = None,
|
||||||
proxied: bool | None = None,
|
proxied: bool | None = None,
|
||||||
force: bool = False,
|
force: bool = False,
|
||||||
dry_run: bool = False,
|
dry_run: bool = False,
|
||||||
@@ -122,20 +134,32 @@ class DomainService:
|
|||||||
return report.fail("domain", str(exc))
|
return report.fail("domain", str(exc))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
address = ip or self.proxmox.guest_ip(guest)
|
guest_address = ip or self.proxmox.guest_ip(guest)
|
||||||
except ProxdomainError as exc:
|
except ProxdomainError as exc:
|
||||||
return report.fail("address", str(exc))
|
return report.fail("address", str(exc))
|
||||||
if not address:
|
if not guest_address:
|
||||||
return report.fail(
|
return report.fail(
|
||||||
"address",
|
"address",
|
||||||
f"no usable IP address found for {guest.label}; pass --ip, install "
|
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",
|
"qemu-guest-agent in the VM, or set a static ip= in the guest config",
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
parsed_ip = ipaddress.ip_address(address)
|
ipaddress.ip_address(guest_address)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
return report.fail("address", f"{address!r} is not a valid IP address")
|
return report.fail("address", f"{guest_address!r} is not a valid IP address")
|
||||||
report.add("address", "ok", f"{address} ({'argument' if ip else 'discovered'})")
|
report.add(
|
||||||
|
"address",
|
||||||
|
"ok",
|
||||||
|
f"guest {guest_address} ({'argument' if ip else 'discovered'})",
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
published = self.dns_resolver.resolve(
|
||||||
|
guest_address=guest_address, override=address
|
||||||
|
)
|
||||||
|
except ProxdomainError as exc:
|
||||||
|
return report.fail("dns-address", str(exc))
|
||||||
|
report.add("dns-address", "ok", f"{published.address} ({published.source})")
|
||||||
report.add("domain", "ok", fqdn)
|
report.add("domain", "ok", fqdn)
|
||||||
|
|
||||||
target_port = int(port or self.config.general.default_port)
|
target_port = int(port or self.config.general.default_port)
|
||||||
@@ -155,18 +179,57 @@ class DomainService:
|
|||||||
return report
|
return report
|
||||||
|
|
||||||
effective_proxied = self.config.cloudflare.proxied if proxied is None else proxied
|
effective_proxied = self.config.cloudflare.proxied if proxied is None else proxied
|
||||||
|
parsed_dns = ipaddress.ip_address(published.address)
|
||||||
proxy_note = ""
|
proxy_note = ""
|
||||||
if effective_proxied and not parsed_ip.is_global:
|
if effective_proxied and not parsed_dns.is_global:
|
||||||
effective_proxied = False
|
effective_proxied = False
|
||||||
proxy_note = (
|
proxy_note = (
|
||||||
f"{address} is not a public address, so the Cloudflare proxy "
|
f"{published.address} is not a public address, so the Cloudflare proxy "
|
||||||
"(orange cloud) was disabled; only the DNS record is created"
|
"(orange cloud) was disabled; only the DNS record is created"
|
||||||
)
|
)
|
||||||
|
|
||||||
spec = self._site_spec(guest, fqdn, address, target_port)
|
spec = self._site_spec(guest, fqdn, guest_address, target_port)
|
||||||
|
record_type = "A" if parsed_dns.version == 4 else "AAAA"
|
||||||
|
|
||||||
|
# Ordering: ACME needs the name to resolve to this host before it can
|
||||||
|
# validate, so a certificate that is still missing forces DNS to be
|
||||||
|
# published first (Caddy starts ACME as soon as it reloads, so it always
|
||||||
|
# goes first there). Everywhere else the vhost is written first, so a
|
||||||
|
# failing DNS call cannot advertise a name that nothing answers for.
|
||||||
|
dns_first = zone is not None and not dry_run and self._dns_before_config(spec)
|
||||||
|
upsert = None
|
||||||
|
if dns_first:
|
||||||
|
try:
|
||||||
|
upsert = self.cloudflare.upsert_address_record(
|
||||||
|
zone.id, fqdn, published.address, proxied=effective_proxied
|
||||||
|
)
|
||||||
|
except ProxdomainError as exc:
|
||||||
|
report.fail("dns", str(exc))
|
||||||
|
report.add(
|
||||||
|
"result",
|
||||||
|
"warning",
|
||||||
|
"a Let's Encrypt certificate needs this name to resolve first, "
|
||||||
|
"so nothing was changed; fix the DNS error and re-run assign",
|
||||||
|
)
|
||||||
|
return report
|
||||||
|
report.add(
|
||||||
|
"dns",
|
||||||
|
"changed" if upsert.changed else "ok",
|
||||||
|
f"{upsert.action} {record_type} {fqdn} -> {published.address} "
|
||||||
|
f"(proxied={'yes' if effective_proxied else 'no'}; "
|
||||||
|
"published before the certificate request)",
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
applied = self.webserver.apply(spec, dry_run=dry_run)
|
applied = self.webserver.apply(spec, dry_run=dry_run)
|
||||||
except ProxdomainError as exc:
|
except ProxdomainError as exc:
|
||||||
|
if upsert is not None:
|
||||||
|
self.state.audit(
|
||||||
|
"assign.dns-only",
|
||||||
|
fqdn=fqdn,
|
||||||
|
vmid=guest.vmid,
|
||||||
|
content=published.address,
|
||||||
|
)
|
||||||
return report.fail("web-config", str(exc))
|
return report.fail("web-config", str(exc))
|
||||||
if dry_run:
|
if dry_run:
|
||||||
status = "planned"
|
status = "planned"
|
||||||
@@ -179,6 +242,9 @@ class DomainService:
|
|||||||
status,
|
status,
|
||||||
"; ".join(applied.messages) or applied.path,
|
"; ".join(applied.messages) or applied.path,
|
||||||
)
|
)
|
||||||
|
tls_step = self._tls_step(spec)
|
||||||
|
if tls_step is not None:
|
||||||
|
report.add(*tls_step)
|
||||||
if proxy_note:
|
if proxy_note:
|
||||||
report.add("dns", "warning", proxy_note)
|
report.add("dns", "warning", proxy_note)
|
||||||
|
|
||||||
@@ -187,7 +253,8 @@ class DomainService:
|
|||||||
)
|
)
|
||||||
assignment.name = guest.name
|
assignment.name = guest.name
|
||||||
assignment.vmid = guest.vmid
|
assignment.vmid = guest.vmid
|
||||||
assignment.ip = address
|
assignment.ip = guest_address
|
||||||
|
assignment.dns_ip = published.address
|
||||||
assignment.port = target_port
|
assignment.port = target_port
|
||||||
assignment.node = guest.node
|
assignment.node = guest.node
|
||||||
assignment.kind = guest.kind
|
assignment.kind = guest.kind
|
||||||
@@ -197,14 +264,15 @@ class DomainService:
|
|||||||
assignment.zone_id = zone.id
|
assignment.zone_id = zone.id
|
||||||
assignment.zone_name = zone.name
|
assignment.zone_name = zone.name
|
||||||
|
|
||||||
record_type = "A" if parsed_ip.version == 4 else "AAAA"
|
record_type = "A" if parsed_dns.version == 4 else "AAAA"
|
||||||
if not dry_run:
|
if not dry_run:
|
||||||
self._save(assignment)
|
self._save(assignment)
|
||||||
self.state.audit(
|
self.state.audit(
|
||||||
"assign.web-config",
|
"assign.web-config",
|
||||||
fqdn=fqdn,
|
fqdn=fqdn,
|
||||||
vmid=guest.vmid,
|
vmid=guest.vmid,
|
||||||
address=address,
|
guest_address=guest_address,
|
||||||
|
dns_address=published.address,
|
||||||
port=target_port,
|
port=target_port,
|
||||||
path=applied.path,
|
path=applied.path,
|
||||||
)
|
)
|
||||||
@@ -215,47 +283,57 @@ class DomainService:
|
|||||||
return report
|
return report
|
||||||
|
|
||||||
if dry_run:
|
if dry_run:
|
||||||
self._preview_dns(report, zone, fqdn, address, record_type, effective_proxied)
|
self._preview_dns(
|
||||||
|
report, zone, fqdn, published.address, record_type, effective_proxied
|
||||||
|
)
|
||||||
report.add("result", "planned", "dry run: nothing was changed")
|
report.add("result", "planned", "dry run: nothing was changed")
|
||||||
report.assignment = assignment
|
report.assignment = assignment
|
||||||
return report
|
return report
|
||||||
|
|
||||||
try:
|
if upsert is None:
|
||||||
upsert = self.cloudflare.upsert_address_record(
|
try:
|
||||||
zone.id,
|
upsert = self.cloudflare.upsert_address_record(
|
||||||
fqdn,
|
zone.id,
|
||||||
address,
|
fqdn,
|
||||||
proxied=effective_proxied,
|
published.address,
|
||||||
)
|
proxied=effective_proxied,
|
||||||
except ProxdomainError as exc:
|
)
|
||||||
report.fail("dns", str(exc))
|
except ProxdomainError as exc:
|
||||||
report.add(
|
report.fail("dns", str(exc))
|
||||||
"result",
|
report.add(
|
||||||
"warning",
|
"result",
|
||||||
"the web server config is in place; fix the DNS error and re-run "
|
"warning",
|
||||||
"assign (it is idempotent)",
|
"the web server config is in place; fix the DNS error and re-run "
|
||||||
)
|
"assign (it is idempotent)",
|
||||||
report.assignment = assignment
|
)
|
||||||
return report
|
report.assignment = assignment
|
||||||
|
return report
|
||||||
|
|
||||||
assignment.record_type = upsert.record.type or record_type
|
assignment.record_type = upsert.record.type or record_type
|
||||||
assignment.record_id = upsert.record.id
|
assignment.record_id = upsert.record.id
|
||||||
|
assignment.tls = self.config.webserver.tls.mode
|
||||||
self._save(assignment)
|
self._save(assignment)
|
||||||
self.state.audit(
|
self.state.audit(
|
||||||
"assign.dns",
|
"assign.dns",
|
||||||
fqdn=fqdn,
|
fqdn=fqdn,
|
||||||
record_id=upsert.record.id,
|
record_id=upsert.record.id,
|
||||||
action=upsert.action,
|
action=upsert.action,
|
||||||
content=address,
|
content=published.address,
|
||||||
|
guest_address=guest_address,
|
||||||
proxied=effective_proxied,
|
proxied=effective_proxied,
|
||||||
)
|
)
|
||||||
|
if not dns_first:
|
||||||
|
report.add(
|
||||||
|
"dns",
|
||||||
|
"changed" if upsert.changed else "ok",
|
||||||
|
f"{upsert.action} {record_type} {fqdn} -> {published.address} "
|
||||||
|
f"(proxied={'yes' if effective_proxied else 'no'})",
|
||||||
|
)
|
||||||
report.add(
|
report.add(
|
||||||
"dns",
|
"result",
|
||||||
"changed" if upsert.changed else "ok",
|
"ok",
|
||||||
f"{upsert.action} {record_type} {fqdn} -> {address} "
|
f"{fqdn} -> {spec.target} (published {published.address})",
|
||||||
f"(proxied={'yes' if effective_proxied else 'no'})",
|
|
||||||
)
|
)
|
||||||
report.add("result", "ok", f"{fqdn} -> {spec.target}")
|
|
||||||
report.assignment = assignment
|
report.assignment = assignment
|
||||||
return report
|
return report
|
||||||
|
|
||||||
@@ -358,14 +436,26 @@ class DomainService:
|
|||||||
report.add("guest", "warning", f"{assignment.fqdn}: {exc}")
|
report.add("guest", "warning", f"{assignment.fqdn}: {exc}")
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
address = self.proxmox.guest_ip(guest) or assignment.ip
|
guest_address = self.proxmox.guest_ip(guest) or assignment.ip
|
||||||
except ProxdomainError as exc:
|
except ProxdomainError as exc:
|
||||||
report.add("guest", "warning", f"{assignment.fqdn}: {exc}")
|
report.add("guest", "warning", f"{assignment.fqdn}: {exc}")
|
||||||
continue
|
continue
|
||||||
if not address:
|
if not guest_address:
|
||||||
report.add("guest", "warning", f"{assignment.fqdn}: guest has no IP")
|
report.add("guest", "warning", f"{assignment.fqdn}: guest has no IP")
|
||||||
continue
|
continue
|
||||||
spec = self._site_spec(guest, assignment.fqdn, address, assignment.port)
|
try:
|
||||||
|
published = self.dns_resolver.resolve(guest_address=guest_address)
|
||||||
|
except ProxdomainError as exc:
|
||||||
|
report.fail("dns-address", f"{assignment.fqdn}: {exc}")
|
||||||
|
continue
|
||||||
|
if published.address != assignment.dns_ip:
|
||||||
|
report.add(
|
||||||
|
"dns-address",
|
||||||
|
"planned" if dry_run else "changed",
|
||||||
|
f"{assignment.fqdn}: {assignment.dns_ip or '-'} -> "
|
||||||
|
f"{published.address} ({published.source})",
|
||||||
|
)
|
||||||
|
spec = self._site_spec(guest, assignment.fqdn, guest_address, assignment.port)
|
||||||
try:
|
try:
|
||||||
result = self.webserver.apply(spec, dry_run=dry_run)
|
result = self.webserver.apply(spec, dry_run=dry_run)
|
||||||
except ProxdomainError as exc:
|
except ProxdomainError as exc:
|
||||||
@@ -380,20 +470,28 @@ class DomainService:
|
|||||||
)
|
)
|
||||||
|
|
||||||
if dry_run or not assignment.zone_id:
|
if dry_run or not assignment.zone_id:
|
||||||
|
assignment.ip = guest_address
|
||||||
|
assignment.dns_ip = published.address
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
upsert = self.cloudflare.upsert_address_record(
|
upsert = self.cloudflare.upsert_address_record(
|
||||||
assignment.zone_id, assignment.fqdn, address
|
assignment.zone_id, assignment.fqdn, published.address
|
||||||
)
|
)
|
||||||
except ProxdomainError as exc:
|
except ProxdomainError as exc:
|
||||||
report.fail("dns", f"{assignment.fqdn}: {exc}")
|
report.fail("dns", f"{assignment.fqdn}: {exc}")
|
||||||
continue
|
continue
|
||||||
assignment.ip = address
|
assignment.ip = guest_address
|
||||||
|
assignment.dns_ip = published.address
|
||||||
|
assignment.tls = self.config.webserver.tls.mode
|
||||||
assignment.record_type = upsert.record.type or assignment.record_type
|
assignment.record_type = upsert.record.type or assignment.record_type
|
||||||
assignment.record_id = upsert.record.id
|
assignment.record_id = upsert.record.id
|
||||||
if upsert.changed:
|
if upsert.changed:
|
||||||
changed += 1
|
changed += 1
|
||||||
report.add("dns", "changed", f"{assignment.fqdn}: {upsert.action} -> {address}")
|
report.add(
|
||||||
|
"dns",
|
||||||
|
"changed",
|
||||||
|
f"{assignment.fqdn}: {upsert.action} -> {published.address}",
|
||||||
|
)
|
||||||
self._save(assignment)
|
self._save(assignment)
|
||||||
|
|
||||||
report.add(
|
report.add(
|
||||||
@@ -449,6 +547,24 @@ class DomainService:
|
|||||||
f"{exc} (the token needs Zone:Read and DNS:Edit)",
|
f"{exc} (the token needs Zone:Read and DNS:Edit)",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if self.config.dns.target == "guest":
|
||||||
|
report.add(
|
||||||
|
"dns-target",
|
||||||
|
"ok",
|
||||||
|
"guest: each record publishes the guest's own address",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
resolved = self.dns_resolver.resolve(guest_address="")
|
||||||
|
report.add(
|
||||||
|
"dns-target",
|
||||||
|
"ok",
|
||||||
|
f"target {self.config.dns.target}: {resolved.address} "
|
||||||
|
f"({resolved.source})",
|
||||||
|
)
|
||||||
|
except ProxdomainError as exc:
|
||||||
|
report.fail("dns-target", str(exc))
|
||||||
|
|
||||||
report.add(
|
report.add(
|
||||||
"web-server",
|
"web-server",
|
||||||
"ok",
|
"ok",
|
||||||
@@ -479,13 +595,99 @@ class DomainService:
|
|||||||
except ProxdomainError as exc:
|
except ProxdomainError as exc:
|
||||||
report.fail("web-server", str(exc))
|
report.fail("web-server", str(exc))
|
||||||
|
|
||||||
|
report.add(*self._doctor_tls())
|
||||||
|
|
||||||
try:
|
try:
|
||||||
items = self.state.all()
|
items = self.state.all()
|
||||||
report.add("state", "ok", f"{len(items)} assignment(s) in {self.state.path}")
|
report.add("state", "ok", f"{len(items)} assignment(s) in {self.state.path}")
|
||||||
except ProxdomainError as exc:
|
except ProxdomainError as exc:
|
||||||
report.fail("state", str(exc))
|
report.fail("state", str(exc))
|
||||||
|
items = []
|
||||||
|
if items and self.config.webserver.tls.mode in ("letsencrypt", "certbot"):
|
||||||
|
report.add(*self._doctor_certificates(items))
|
||||||
return report
|
return report
|
||||||
|
|
||||||
|
def _doctor_tls(self) -> tuple[str, str, str]:
|
||||||
|
tls = self.config.webserver.tls
|
||||||
|
kind = self.config.webserver.kind
|
||||||
|
if tls.mode == "none":
|
||||||
|
return (
|
||||||
|
"tls",
|
||||||
|
"skipped",
|
||||||
|
"not managed (webserver.tls.mode = 'none'); set 'letsencrypt' for "
|
||||||
|
"automatic HTTPS",
|
||||||
|
)
|
||||||
|
if tls.mode == "files":
|
||||||
|
present = self.webserver.runner.exists(tls.cert_dir)
|
||||||
|
return (
|
||||||
|
"tls",
|
||||||
|
"ok" if present else "warning",
|
||||||
|
f"files mode: reading certificates from {tls.cert_dir}"
|
||||||
|
if present
|
||||||
|
else f"files mode, but {tls.cert_dir} does not exist",
|
||||||
|
)
|
||||||
|
if kind == "caddy":
|
||||||
|
return (
|
||||||
|
"tls",
|
||||||
|
"ok",
|
||||||
|
f"letsencrypt: Caddy's ACME issuer requests certificates on demand "
|
||||||
|
f"({tls.email}) and renews them automatically",
|
||||||
|
)
|
||||||
|
if kind == "traefik":
|
||||||
|
return (
|
||||||
|
"tls",
|
||||||
|
"ok",
|
||||||
|
f"letsencrypt: Traefik certResolver "
|
||||||
|
f"{self.config.webserver.cert_resolver} (must be defined in the "
|
||||||
|
"static config with an ACME configuration)",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
binary = (tls.certbot_command or ("certbot",))[0]
|
||||||
|
probe = self.webserver.runner.run([binary, "--version"])
|
||||||
|
except ProxdomainError as exc:
|
||||||
|
return ("tls", "warning", f"cannot run certbot: {exc}")
|
||||||
|
if not probe.ok:
|
||||||
|
return (
|
||||||
|
"tls",
|
||||||
|
"warning",
|
||||||
|
f"{binary} is not installed or not executable; install certbot "
|
||||||
|
"(apt install certbot) so proxdomain can issue Let's Encrypt "
|
||||||
|
"certificates",
|
||||||
|
)
|
||||||
|
version = probe.stdout.strip() or probe.output(limit=60)
|
||||||
|
return (
|
||||||
|
"tls",
|
||||||
|
"ok",
|
||||||
|
f"letsencrypt via {binary} ({version}); webroot {tls.webroot}, "
|
||||||
|
f"renew hook '{self.webserver.renew_hook or '-'}'",
|
||||||
|
)
|
||||||
|
|
||||||
|
def _doctor_certificates(self, items: list[Assignment]) -> tuple[str, str, str]:
|
||||||
|
if self.config.webserver.kind != "nginx":
|
||||||
|
return (
|
||||||
|
"tls-certs",
|
||||||
|
"ok",
|
||||||
|
f"{len(items)} site(s) handled by "
|
||||||
|
f"{self.config.webserver.kind}, which renews certificates itself",
|
||||||
|
)
|
||||||
|
cert_dir = self.config.webserver.tls.cert_dir
|
||||||
|
missing = [
|
||||||
|
item.fqdn
|
||||||
|
for item in items
|
||||||
|
if not self.webserver.runner.exists(f"{cert_dir}/{item.fqdn}/fullchain.pem")
|
||||||
|
]
|
||||||
|
if not missing:
|
||||||
|
return (
|
||||||
|
"tls-certs",
|
||||||
|
"ok",
|
||||||
|
f"a certificate exists for all {len(items)} managed site(s)",
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
"tls-certs",
|
||||||
|
"warning",
|
||||||
|
f"no certificate for {', '.join(missing)}; re-run assign for those guests",
|
||||||
|
)
|
||||||
|
|
||||||
def init(self, *, dry_run: bool = False) -> ServiceReport:
|
def init(self, *, dry_run: bool = False) -> ServiceReport:
|
||||||
report = ServiceReport("init")
|
report = ServiceReport("init")
|
||||||
try:
|
try:
|
||||||
@@ -528,6 +730,59 @@ class DomainService:
|
|||||||
raise ProxdomainError(f"{fqdn!r} is not a valid DNS name")
|
raise ProxdomainError(f"{fqdn!r} is not a valid DNS name")
|
||||||
return fqdn
|
return fqdn
|
||||||
|
|
||||||
|
def _dns_before_config(self, spec: SiteSpec) -> bool:
|
||||||
|
"""True when ACME needs the public record in place before the vhost."""
|
||||||
|
webserver = self.config.webserver
|
||||||
|
if webserver.tls.mode != "letsencrypt" and webserver.tls.mode != "certbot":
|
||||||
|
return False
|
||||||
|
if webserver.kind == "caddy":
|
||||||
|
# Caddy starts issuing the moment the new site block is loaded.
|
||||||
|
return True
|
||||||
|
return self._certificate_missing(spec)
|
||||||
|
|
||||||
|
def _certificate_missing(self, spec: SiteSpec) -> bool:
|
||||||
|
"""True when a certificate must still be obtained before TLS can serve."""
|
||||||
|
return self.webserver.issues_certificates and not self.webserver.certificate_present(spec)
|
||||||
|
|
||||||
|
def _tls_step(self, spec: SiteSpec) -> tuple[str, str, str] | None:
|
||||||
|
mode = self.config.webserver.tls.mode
|
||||||
|
kind = self.config.webserver.kind
|
||||||
|
if mode == "none":
|
||||||
|
return (
|
||||||
|
"tls",
|
||||||
|
"skipped",
|
||||||
|
"tls.mode = 'none'; set webserver.tls.mode = 'letsencrypt' for HTTPS",
|
||||||
|
)
|
||||||
|
if mode == "files":
|
||||||
|
if self.webserver.certificate_present(spec):
|
||||||
|
return ("tls", "ok", f"certificate files present in {spec.cert_dir}")
|
||||||
|
return (
|
||||||
|
"tls",
|
||||||
|
"warning",
|
||||||
|
f"no certificate at {spec.certificate}; the vhost will fail to load "
|
||||||
|
"once nginx is reloaded",
|
||||||
|
)
|
||||||
|
if kind == "caddy":
|
||||||
|
return (
|
||||||
|
"tls",
|
||||||
|
"ok",
|
||||||
|
"Caddy requests and renews a Let's Encrypt certificate for this site",
|
||||||
|
)
|
||||||
|
if kind == "traefik":
|
||||||
|
return (
|
||||||
|
"tls",
|
||||||
|
"ok",
|
||||||
|
f"Traefik obtains the certificate through certResolver "
|
||||||
|
f"{self.config.webserver.cert_resolver}",
|
||||||
|
)
|
||||||
|
if self.webserver.certificate_present(spec):
|
||||||
|
expiry = self.webserver.certificate_expiry(spec)
|
||||||
|
detail = f"Let's Encrypt certificate present ({spec.certificate})"
|
||||||
|
if expiry:
|
||||||
|
detail = f"Let's Encrypt certificate valid until {expiry}"
|
||||||
|
return ("tls", "ok", detail)
|
||||||
|
return ("tls", "warning", "no certificate yet; run assign again to finish issuance")
|
||||||
|
|
||||||
def _site_spec(
|
def _site_spec(
|
||||||
self, guest: Guest, fqdn: str, address: str, port: int
|
self, guest: Guest, fqdn: str, address: str, port: int
|
||||||
) -> SiteSpec:
|
) -> SiteSpec:
|
||||||
@@ -543,6 +798,9 @@ class DomainService:
|
|||||||
cert_dir=self.config.webserver.tls.cert_dir,
|
cert_dir=self.config.webserver.tls.cert_dir,
|
||||||
webroot=self.config.webserver.tls.webroot,
|
webroot=self.config.webserver.tls.webroot,
|
||||||
cert_resolver=self.config.webserver.cert_resolver,
|
cert_resolver=self.config.webserver.cert_resolver,
|
||||||
|
tls_email=self.config.webserver.tls.email,
|
||||||
|
acme_ca=self.config.webserver.tls.acme_ca,
|
||||||
|
renew_hook=self.webserver.renew_hook,
|
||||||
)
|
)
|
||||||
|
|
||||||
def _find_zone(
|
def _find_zone(
|
||||||
|
|||||||
@@ -28,7 +28,9 @@ class Assignment:
|
|||||||
kind: str
|
kind: str
|
||||||
name: str = ""
|
name: str = ""
|
||||||
ip: str = ""
|
ip: str = ""
|
||||||
|
dns_ip: str = ""
|
||||||
port: int = 80
|
port: int = 80
|
||||||
|
tls: str = "none"
|
||||||
webserver: str = ""
|
webserver: str = ""
|
||||||
zone_id: str = ""
|
zone_id: str = ""
|
||||||
zone_name: str = ""
|
zone_name: str = ""
|
||||||
@@ -55,7 +57,9 @@ class Assignment:
|
|||||||
kind=kind,
|
kind=kind,
|
||||||
name=str(payload.get("name") or ""),
|
name=str(payload.get("name") or ""),
|
||||||
ip=str(payload.get("ip") or ""),
|
ip=str(payload.get("ip") or ""),
|
||||||
|
dns_ip=str(payload.get("dns_ip") or ""),
|
||||||
port=int(payload.get("port") or 80),
|
port=int(payload.get("port") or 80),
|
||||||
|
tls=str(payload.get("tls") or "none"),
|
||||||
webserver=str(payload.get("webserver") or ""),
|
webserver=str(payload.get("webserver") or ""),
|
||||||
zone_id=str(payload.get("zone_id") or ""),
|
zone_id=str(payload.get("zone_id") or ""),
|
||||||
zone_name=str(payload.get("zone_name") or ""),
|
zone_name=str(payload.get("zone_name") or ""),
|
||||||
|
|||||||
+88
-4
@@ -20,6 +20,12 @@ FQDN_RE = re.compile(
|
|||||||
|
|
||||||
_EXTENSIONS = {"nginx": ".conf", "caddy": ".caddy", "traefik": ".yml"}
|
_EXTENSIONS = {"nginx": ".conf", "caddy": ".caddy", "traefik": ".yml"}
|
||||||
|
|
||||||
|
# Let's Encrypt production directory; overridable through webserver.tls.acme_ca.
|
||||||
|
LETSENCRYPT_DIRECTORY = "https://acme-v02.api.letsencrypt.org/directory"
|
||||||
|
|
||||||
|
# Modes where proxdomain itself obtains a certificate (nginx + certbot).
|
||||||
|
CERTBOT_MODES = ("certbot", "letsencrypt")
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class SiteSpec:
|
class SiteSpec:
|
||||||
@@ -34,6 +40,9 @@ class SiteSpec:
|
|||||||
cert_dir: str = "/etc/letsencrypt/live"
|
cert_dir: str = "/etc/letsencrypt/live"
|
||||||
webroot: str = "/var/www/certbot"
|
webroot: str = "/var/www/certbot"
|
||||||
cert_resolver: str = ""
|
cert_resolver: str = ""
|
||||||
|
tls_email: str = ""
|
||||||
|
acme_ca: str = ""
|
||||||
|
renew_hook: str = ""
|
||||||
upstream_scheme: str = "http"
|
upstream_scheme: str = "http"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@@ -63,6 +72,41 @@ class WebServerManager:
|
|||||||
self.config = config
|
self.config = config
|
||||||
self.runner = runner
|
self.runner = runner
|
||||||
|
|
||||||
|
# -- TLS -------------------------------------------------------------
|
||||||
|
@property
|
||||||
|
def tls_mode(self) -> str:
|
||||||
|
return self.config.tls.mode
|
||||||
|
|
||||||
|
@property
|
||||||
|
def issues_certificates(self) -> bool:
|
||||||
|
"""True when proxdomain runs certbot itself (nginx only)."""
|
||||||
|
return self.config.kind == "nginx" and self.tls_mode in CERTBOT_MODES
|
||||||
|
|
||||||
|
@property
|
||||||
|
def renew_hook(self) -> str:
|
||||||
|
"""Command certbot runs after a renewal, so the server picks up the new cert."""
|
||||||
|
return self.config.tls.renew_hook or " ".join(self.config.reload_command)
|
||||||
|
|
||||||
|
def certificate_present(self, spec: SiteSpec) -> bool:
|
||||||
|
return self.runner.exists(spec.certificate)
|
||||||
|
|
||||||
|
def certificate_expiry(self, spec: SiteSpec) -> str:
|
||||||
|
"""Return the notAfter date of an existing certificate, or ''."""
|
||||||
|
if not self.certificate_present(spec):
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
result = self.runner.run(
|
||||||
|
["openssl", "x509", "-noout", "-enddate", "-in", spec.certificate]
|
||||||
|
)
|
||||||
|
except ProxdomainError:
|
||||||
|
return ""
|
||||||
|
if not result.ok:
|
||||||
|
return ""
|
||||||
|
for line in result.stdout.splitlines():
|
||||||
|
if line.startswith("notAfter="):
|
||||||
|
return line.split("=", 1)[1].strip()
|
||||||
|
return ""
|
||||||
|
|
||||||
# -- rendering ------------------------------------------------------
|
# -- rendering ------------------------------------------------------
|
||||||
def render(self, spec: SiteSpec) -> str:
|
def render(self, spec: SiteSpec) -> str:
|
||||||
if spec.webserver == "nginx":
|
if spec.webserver == "nginx":
|
||||||
@@ -102,11 +146,12 @@ class WebServerManager:
|
|||||||
original = self.runner.read_text(path)
|
original = self.runner.read_text(path)
|
||||||
|
|
||||||
bootstrapped = False
|
bootstrapped = False
|
||||||
if spec.tls_mode == "certbot" and not self.runner.exists(spec.certificate):
|
if self.issues_certificates and not self.certificate_present(spec):
|
||||||
try:
|
try:
|
||||||
self._serve_challenge(spec, path, result)
|
self._serve_challenge(spec, path, result)
|
||||||
self._request_certificate(spec, result)
|
self._request_certificate(spec, result)
|
||||||
except WebServerError:
|
except ProxdomainError:
|
||||||
|
# Do not leave the temporary HTTP vhost behind.
|
||||||
if original is None:
|
if original is None:
|
||||||
self.runner.remove(path)
|
self.runner.remove(path)
|
||||||
else:
|
else:
|
||||||
@@ -187,6 +232,7 @@ class WebServerManager:
|
|||||||
|
|
||||||
def _serve_challenge(self, spec: SiteSpec, path: str, result: ApplyResult) -> None:
|
def _serve_challenge(self, spec: SiteSpec, path: str, result: ApplyResult) -> None:
|
||||||
"""Activate an HTTP-only vhost so certbot's webroot plugin can answer."""
|
"""Activate an HTTP-only vhost so certbot's webroot plugin can answer."""
|
||||||
|
self.runner.mkdir(self.config.tls.webroot)
|
||||||
self.runner.write_text(path, render_nginx_challenge(spec))
|
self.runner.write_text(path, render_nginx_challenge(spec))
|
||||||
try:
|
try:
|
||||||
self.validate()
|
self.validate()
|
||||||
@@ -200,14 +246,26 @@ class WebServerManager:
|
|||||||
|
|
||||||
def _request_certificate(self, spec: SiteSpec, result: ApplyResult) -> None:
|
def _request_certificate(self, spec: SiteSpec, result: ApplyResult) -> None:
|
||||||
command = list(self.config.tls.certbot_command) + [
|
command = list(self.config.tls.certbot_command) + [
|
||||||
|
"--keep-until-expiring",
|
||||||
"-d",
|
"-d",
|
||||||
spec.fqdn,
|
spec.fqdn,
|
||||||
"--email",
|
"--email",
|
||||||
self.config.tls.email,
|
self.config.tls.email,
|
||||||
]
|
]
|
||||||
|
if self.config.tls.acme_ca:
|
||||||
|
command += ["--server", self.config.tls.acme_ca]
|
||||||
|
if self.renew_hook:
|
||||||
|
command += ["--deploy-hook", self.renew_hook]
|
||||||
command.extend(self.config.tls.extra_args)
|
command.extend(self.config.tls.extra_args)
|
||||||
result.messages.append(f"requesting a certificate for {spec.fqdn}")
|
result.messages.append(f"requesting a certificate for {spec.fqdn}")
|
||||||
completed = self.runner.run(command)
|
try:
|
||||||
|
completed = self.runner.run(command)
|
||||||
|
except ProxdomainError as exc:
|
||||||
|
raise WebServerError(
|
||||||
|
f"cannot run certbot for {spec.fqdn}: {exc}\n"
|
||||||
|
"install it (apt install certbot) or set "
|
||||||
|
"webserver.tls.certbot_command to its full path"
|
||||||
|
) from exc
|
||||||
if not completed.ok:
|
if not completed.ok:
|
||||||
raise WebServerError(
|
raise WebServerError(
|
||||||
f"certbot failed for {spec.fqdn}:\n{completed.output()}\n"
|
f"certbot failed for {spec.fqdn}:\n{completed.output()}\n"
|
||||||
@@ -244,13 +302,29 @@ class WebServerManager:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
if self.config.tls.mode == "certbot":
|
if self.issues_certificates:
|
||||||
webroot = self.config.tls.webroot
|
webroot = self.config.tls.webroot
|
||||||
if dry_run:
|
if dry_run:
|
||||||
steps.append(("planned", f"create ACME webroot {webroot}"))
|
steps.append(("planned", f"create ACME webroot {webroot}"))
|
||||||
else:
|
else:
|
||||||
self.runner.mkdir(webroot)
|
self.runner.mkdir(webroot)
|
||||||
steps.append(("ok", f"ACME webroot {webroot} is ready"))
|
steps.append(("ok", f"ACME webroot {webroot} is ready"))
|
||||||
|
if self.tls_mode == "letsencrypt" and self.config.kind in ("caddy", "traefik"):
|
||||||
|
steps.append(
|
||||||
|
(
|
||||||
|
"ok",
|
||||||
|
f"{self.config.kind} obtains and renews Let's Encrypt certificates "
|
||||||
|
"for every managed site",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if self.tls_mode == "letsencrypt" and self.config.kind == "nginx":
|
||||||
|
steps.append(
|
||||||
|
(
|
||||||
|
"next",
|
||||||
|
"certbot's systemd timer renews certificates; verify with "
|
||||||
|
"'systemctl list-timers | grep certbot'",
|
||||||
|
)
|
||||||
|
)
|
||||||
return steps
|
return steps
|
||||||
|
|
||||||
def _bootstrap_nginx(self, manage_dir: str, dry_run: bool) -> list[tuple[str, str]]:
|
def _bootstrap_nginx(self, manage_dir: str, dry_run: bool) -> list[tuple[str, str]]:
|
||||||
@@ -411,6 +485,16 @@ def render_caddy(spec: SiteSpec) -> str:
|
|||||||
]
|
]
|
||||||
if spec.tls_mode == "files":
|
if spec.tls_mode == "files":
|
||||||
lines.append(f"\ttls {spec.certificate} {spec.private_key}")
|
lines.append(f"\ttls {spec.certificate} {spec.private_key}")
|
||||||
|
elif spec.tls_mode == "letsencrypt":
|
||||||
|
# Pin the issuer: without this Caddy may fall back to ZeroSSL.
|
||||||
|
lines.append("\ttls {")
|
||||||
|
lines.append("\t\tissuer acme {")
|
||||||
|
if spec.tls_email:
|
||||||
|
lines.append(f"\t\t\temail {spec.tls_email}")
|
||||||
|
if spec.acme_ca:
|
||||||
|
lines.append(f"\t\t\tdir {spec.acme_ca}")
|
||||||
|
lines.append("\t\t}")
|
||||||
|
lines.append("\t}")
|
||||||
lines.append(f"\treverse_proxy {spec.target}")
|
lines.append(f"\treverse_proxy {spec.target}")
|
||||||
lines.append("}")
|
lines.append("}")
|
||||||
return "\n".join(lines) + "\n"
|
return "\n".join(lines) + "\n"
|
||||||
|
|||||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "proxdomain"
|
name = "proxdomain"
|
||||||
version = "0.1.0"
|
version = "0.3.0"
|
||||||
description = "Assign public domains to Proxmox VMs/containers via Cloudflare DNS and a reverse proxy on the PVE host"
|
description = "Assign public domains to Proxmox VMs/containers via Cloudflare DNS and a reverse proxy on the PVE host"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.11"
|
requires-python = ">=3.11"
|
||||||
|
|||||||
+19
-4
@@ -31,6 +31,7 @@ class Route:
|
|||||||
path: str
|
path: str
|
||||||
handler: Callable[[Call], Any] | Any
|
handler: Callable[[Call], Any] | Any
|
||||||
status: int = 200
|
status: int = 200
|
||||||
|
raw: bool = False
|
||||||
|
|
||||||
|
|
||||||
class FakeTransport:
|
class FakeTransport:
|
||||||
@@ -42,27 +43,38 @@ class FakeTransport:
|
|||||||
self.routes.append(Route(method.upper(), path, response, status))
|
self.routes.append(Route(method.upper(), path, response, status))
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
def add_text(
|
||||||
|
self, method: str, path: str, text: str, *, status: int = 200
|
||||||
|
) -> "FakeTransport":
|
||||||
|
self.routes.append(Route(method.upper(), path, text, status, raw=True))
|
||||||
|
return self
|
||||||
|
|
||||||
# -- Transport protocol --------------------------------------------
|
# -- Transport protocol --------------------------------------------
|
||||||
def request(self, method, url, headers, body, timeout) -> Response:
|
def request(self, method, url, headers, body, timeout) -> Response:
|
||||||
split = urllib.parse.urlsplit(url)
|
split = urllib.parse.urlsplit(url)
|
||||||
call = Call(
|
call = Call(
|
||||||
method=method,
|
method=method,
|
||||||
url=url,
|
url=url,
|
||||||
path=split.path,
|
path=split.path or "/",
|
||||||
query=urllib.parse.parse_qs(split.query),
|
query=urllib.parse.parse_qs(split.query),
|
||||||
body=json.loads(body.decode("utf-8")) if body else None,
|
body=json.loads(body.decode("utf-8")) if body else None,
|
||||||
)
|
)
|
||||||
self.calls.append(call)
|
self.calls.append(call)
|
||||||
for route in reversed(self.routes):
|
for route in reversed(self.routes):
|
||||||
if route.method == method and route.path == split.path:
|
if route.method == method and route.path == (split.path or "/"):
|
||||||
payload = route.handler(call) if callable(route.handler) else route.handler
|
payload = route.handler(call) if callable(route.handler) else route.handler
|
||||||
status = route.status
|
status = route.status
|
||||||
if isinstance(payload, tuple) and len(payload) == 2:
|
if isinstance(payload, tuple) and len(payload) == 2:
|
||||||
status, payload = payload
|
status, payload = payload
|
||||||
|
body = (
|
||||||
|
payload.encode("utf-8")
|
||||||
|
if route.raw
|
||||||
|
else json.dumps(payload).encode("utf-8")
|
||||||
|
)
|
||||||
return Response(
|
return Response(
|
||||||
status=status,
|
status=status,
|
||||||
body=json.dumps(payload).encode("utf-8"),
|
body=body,
|
||||||
headers={"content-type": "application/json"},
|
headers={"content-type": "text/plain" if route.raw else "application/json"},
|
||||||
)
|
)
|
||||||
return Response(
|
return Response(
|
||||||
status=404,
|
status=404,
|
||||||
@@ -153,6 +165,7 @@ def make_config(
|
|||||||
proxmox: dict[str, Any] | None = None,
|
proxmox: dict[str, Any] | None = None,
|
||||||
general: dict[str, Any] | None = None,
|
general: dict[str, Any] | None = None,
|
||||||
cloudflare: dict[str, Any] | None = None,
|
cloudflare: dict[str, Any] | None = None,
|
||||||
|
dns: dict[str, Any] | None = None,
|
||||||
state: dict[str, Any] | None = None,
|
state: dict[str, Any] | None = None,
|
||||||
**webserver: Any,
|
**webserver: Any,
|
||||||
) -> Config:
|
) -> Config:
|
||||||
@@ -164,6 +177,7 @@ def make_config(
|
|||||||
"token_secret": "pve-secret",
|
"token_secret": "pve-secret",
|
||||||
},
|
},
|
||||||
"cloudflare": {"api_token": "cf-token", "proxied": True},
|
"cloudflare": {"api_token": "cf-token", "proxied": True},
|
||||||
|
"dns": {"target": "guest"},
|
||||||
"webserver": {
|
"webserver": {
|
||||||
"kind": "nginx",
|
"kind": "nginx",
|
||||||
"mode": "local",
|
"mode": "local",
|
||||||
@@ -174,6 +188,7 @@ def make_config(
|
|||||||
("general", general),
|
("general", general),
|
||||||
("proxmox", proxmox),
|
("proxmox", proxmox),
|
||||||
("cloudflare", cloudflare),
|
("cloudflare", cloudflare),
|
||||||
|
("dns", dns),
|
||||||
("state", state),
|
("state", state),
|
||||||
):
|
):
|
||||||
if values:
|
if values:
|
||||||
|
|||||||
Executable
+128
@@ -0,0 +1,128 @@
|
|||||||
|
"""Resolving what the public DNS record points at."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from proxdomain.addressing import PublicAddressResolver, extract_address
|
||||||
|
from proxdomain.config import DnsConfig
|
||||||
|
from proxdomain.errors import ProxdomainError
|
||||||
|
from tests.support import FakeTransport
|
||||||
|
|
||||||
|
|
||||||
|
class ExtractTests(unittest.TestCase):
|
||||||
|
def test_plain_address(self) -> None:
|
||||||
|
self.assertEqual(extract_address("93.184.216.34\n"), "93.184.216.34")
|
||||||
|
|
||||||
|
def test_cloudflare_trace(self) -> None:
|
||||||
|
trace = "fl=1f2\nh=cloudflare.com\nip=93.184.216.34\nts=1700000000\n"
|
||||||
|
self.assertEqual(extract_address(trace), "93.184.216.34")
|
||||||
|
|
||||||
|
def test_sentence(self) -> None:
|
||||||
|
self.assertEqual(extract_address("Your IP is 93.184.216.34 today"), "93.184.216.34")
|
||||||
|
|
||||||
|
def test_ipv6(self) -> None:
|
||||||
|
self.assertEqual(extract_address("2001:4860:4860::8888"), "2001:4860:4860::8888")
|
||||||
|
|
||||||
|
def test_nothing_usable(self) -> None:
|
||||||
|
self.assertIsNone(extract_address("not an address\n"))
|
||||||
|
|
||||||
|
|
||||||
|
class ResolverTests(unittest.TestCase):
|
||||||
|
def test_guest_target_keeps_the_guest_address(self) -> None:
|
||||||
|
resolver = PublicAddressResolver(DnsConfig(target="guest"))
|
||||||
|
resolved = resolver.resolve(guest_address="10.3.0.22")
|
||||||
|
self.assertEqual(resolved.address, "10.3.0.22")
|
||||||
|
self.assertEqual(resolved.source, "guest")
|
||||||
|
|
||||||
|
def test_override_wins(self) -> None:
|
||||||
|
resolver = PublicAddressResolver(DnsConfig(target="host"))
|
||||||
|
resolved = resolver.resolve(guest_address="10.3.0.22", override="93.184.216.34")
|
||||||
|
self.assertEqual(resolved.address, "93.184.216.34")
|
||||||
|
self.assertEqual(resolved.source, "command line")
|
||||||
|
|
||||||
|
def test_fixed_target(self) -> None:
|
||||||
|
resolver = PublicAddressResolver(
|
||||||
|
DnsConfig(target="fixed", address="93.184.216.34")
|
||||||
|
)
|
||||||
|
self.assertEqual(resolver.resolve().address, "93.184.216.34")
|
||||||
|
|
||||||
|
def test_host_target_uses_configured_address(self) -> None:
|
||||||
|
resolver = PublicAddressResolver(
|
||||||
|
DnsConfig(target="host", address="93.184.216.34"),
|
||||||
|
fetch_text=lambda url: self.fail("detection must not run"),
|
||||||
|
)
|
||||||
|
resolved = resolver.resolve()
|
||||||
|
self.assertEqual(resolved.address, "93.184.216.34")
|
||||||
|
self.assertEqual(resolved.source, "dns.address")
|
||||||
|
|
||||||
|
def test_hostname_prefers_a_public_address(self) -> None:
|
||||||
|
resolver = PublicAddressResolver(
|
||||||
|
DnsConfig(target="host", hostname="pve.example.com"),
|
||||||
|
hostname_resolver=lambda host: ["10.0.0.1", "93.184.216.34"],
|
||||||
|
)
|
||||||
|
self.assertEqual(resolver.resolve().address, "93.184.216.34")
|
||||||
|
|
||||||
|
def test_hostname_without_public_address_falls_back(self) -> None:
|
||||||
|
resolver = PublicAddressResolver(
|
||||||
|
DnsConfig(target="host", hostname="pve.example.com"),
|
||||||
|
hostname_resolver=lambda host: ["10.0.0.1"],
|
||||||
|
)
|
||||||
|
self.assertEqual(resolver.resolve().address, "10.0.0.1")
|
||||||
|
|
||||||
|
def test_detection_uses_configured_url(self) -> None:
|
||||||
|
seen: list[str] = []
|
||||||
|
|
||||||
|
def fetch(url: str) -> str:
|
||||||
|
seen.append(url)
|
||||||
|
return "93.184.216.34\n"
|
||||||
|
|
||||||
|
resolver = PublicAddressResolver(DnsConfig(target="host"), fetch_text=fetch)
|
||||||
|
self.assertEqual(resolver.resolve().address, "93.184.216.34")
|
||||||
|
self.assertEqual(seen, ["https://ipv4.icanhazip.com"])
|
||||||
|
|
||||||
|
def test_detection_is_cached(self) -> None:
|
||||||
|
calls = []
|
||||||
|
transport = FakeTransport()
|
||||||
|
transport.add_text("GET", "/", "93.184.216.34\n")
|
||||||
|
resolver = PublicAddressResolver(DnsConfig(target="host"), transport=transport)
|
||||||
|
resolver.resolve()
|
||||||
|
resolver.resolve()
|
||||||
|
self.assertEqual(transport.count("GET", "/"), 1)
|
||||||
|
|
||||||
|
def test_ipv6_preference_uses_the_v6_endpoint(self) -> None:
|
||||||
|
seen = []
|
||||||
|
resolver = PublicAddressResolver(
|
||||||
|
DnsConfig(target="host"),
|
||||||
|
preference="ipv6",
|
||||||
|
fetch_text=lambda url: seen.append(url) or "2001:4860:4860::8888\n",
|
||||||
|
)
|
||||||
|
self.assertEqual(resolver.resolve().address, "2001:4860:4860::8888")
|
||||||
|
self.assertEqual(seen, ["https://ipv6.icanhazip.com"])
|
||||||
|
|
||||||
|
def test_detection_rejects_private_results(self) -> None:
|
||||||
|
resolver = PublicAddressResolver(
|
||||||
|
DnsConfig(target="host"), fetch_text=lambda url: "10.0.0.5\n"
|
||||||
|
)
|
||||||
|
with self.assertRaises(ProxdomainError) as ctx:
|
||||||
|
resolver.resolve()
|
||||||
|
self.assertIn("non-public", str(ctx.exception))
|
||||||
|
|
||||||
|
def test_detection_failure_has_actionable_message(self) -> None:
|
||||||
|
def boom(url: str) -> str:
|
||||||
|
raise ProxdomainError(f"GET {url} -> HTTP 503")
|
||||||
|
|
||||||
|
resolver = PublicAddressResolver(DnsConfig(target="host"), fetch_text=boom)
|
||||||
|
with self.assertRaises(ProxdomainError) as ctx:
|
||||||
|
resolver.resolve()
|
||||||
|
message = str(ctx.exception)
|
||||||
|
self.assertIn("dns.address", message)
|
||||||
|
self.assertIn("--address", message)
|
||||||
|
|
||||||
|
def test_missing_target_never_returns_empty(self) -> None:
|
||||||
|
with self.assertRaises(ProxdomainError):
|
||||||
|
PublicAddressResolver(DnsConfig(target="guest")).resolve(guest_address="")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -126,6 +126,14 @@ class CliTests(unittest.TestCase):
|
|||||||
self.assertEqual(before.config, str(config))
|
self.assertEqual(before.config, str(config))
|
||||||
self.assertEqual(after.config, str(config))
|
self.assertEqual(after.config, str(config))
|
||||||
|
|
||||||
|
def test_assign_accepts_published_address(self) -> None:
|
||||||
|
parser = build_parser()
|
||||||
|
args = parser.parse_args(
|
||||||
|
["assign", "--vmid", "101", "--address", "93.184.216.34"]
|
||||||
|
)
|
||||||
|
self.assertEqual(args.address, "93.184.216.34")
|
||||||
|
self.assertIsNone(args.ip)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
@@ -83,6 +83,50 @@ class ConfigTests(unittest.TestCase):
|
|||||||
with self.assertRaises(ConfigError):
|
with self.assertRaises(ConfigError):
|
||||||
parse_config(raw)
|
parse_config(raw)
|
||||||
|
|
||||||
|
def test_letsencrypt_requires_email(self) -> None:
|
||||||
|
raw = raw_config()
|
||||||
|
raw["webserver"]["tls"] = {"mode": "letsencrypt"}
|
||||||
|
with self.assertRaises(ConfigError) as ctx:
|
||||||
|
parse_config(raw)
|
||||||
|
self.assertIn("email", str(ctx.exception))
|
||||||
|
|
||||||
|
def test_letsencrypt_is_valid_for_every_webserver(self) -> None:
|
||||||
|
for kind, extra in (
|
||||||
|
("nginx", {}),
|
||||||
|
("caddy", {}),
|
||||||
|
("traefik", {"cert_resolver": "letsencrypt"}),
|
||||||
|
):
|
||||||
|
with self.subTest(kind=kind):
|
||||||
|
raw = raw_config()
|
||||||
|
raw["webserver"].update(extra)
|
||||||
|
raw["webserver"]["kind"] = kind
|
||||||
|
raw["webserver"]["tls"] = {
|
||||||
|
"mode": "letsencrypt",
|
||||||
|
"email": "ops@example.com",
|
||||||
|
}
|
||||||
|
config = parse_config(raw)
|
||||||
|
self.assertEqual(config.webserver.tls.mode, "letsencrypt")
|
||||||
|
|
||||||
|
def test_traefik_letsencrypt_requires_resolver(self) -> None:
|
||||||
|
raw = raw_config()
|
||||||
|
raw["webserver"]["kind"] = "traefik"
|
||||||
|
raw["webserver"]["cert_resolver"] = ""
|
||||||
|
raw["webserver"]["tls"] = {"mode": "letsencrypt", "email": "ops@example.com"}
|
||||||
|
with self.assertRaises(ConfigError) as ctx:
|
||||||
|
parse_config(raw)
|
||||||
|
self.assertIn("cert_resolver", str(ctx.exception))
|
||||||
|
|
||||||
|
def test_acme_ca_must_be_a_url(self) -> None:
|
||||||
|
raw = raw_config()
|
||||||
|
raw["webserver"]["tls"] = {
|
||||||
|
"mode": "letsencrypt",
|
||||||
|
"email": "ops@example.com",
|
||||||
|
"acme_ca": "acme-staging",
|
||||||
|
}
|
||||||
|
with self.assertRaises(ConfigError) as ctx:
|
||||||
|
parse_config(raw)
|
||||||
|
self.assertIn("acme_ca", str(ctx.exception))
|
||||||
|
|
||||||
def test_ssh_mode_requires_host(self) -> None:
|
def test_ssh_mode_requires_host(self) -> None:
|
||||||
raw = raw_config()
|
raw = raw_config()
|
||||||
raw["webserver"]["mode"] = "ssh"
|
raw["webserver"]["mode"] = "ssh"
|
||||||
@@ -115,6 +159,25 @@ class ConfigTests(unittest.TestCase):
|
|||||||
with self.assertRaises(ConfigError):
|
with self.assertRaises(ConfigError):
|
||||||
config.proxmox.resolve_secret()
|
config.proxmox.resolve_secret()
|
||||||
|
|
||||||
|
def test_secret_env_must_be_a_variable_name(self) -> None:
|
||||||
|
raw = raw_config()
|
||||||
|
raw["proxmox"].pop("token_secret")
|
||||||
|
raw["proxmox"]["token_secret_env"] = "ebd8ac60-61a2-4cd4-89bf-38d12fb5bdf7"
|
||||||
|
config = parse_config(raw)
|
||||||
|
with self.assertRaises(ConfigError) as ctx:
|
||||||
|
config.proxmox.resolve_secret()
|
||||||
|
message = str(ctx.exception)
|
||||||
|
self.assertIn("must be the name of an environment variable", message)
|
||||||
|
self.assertIn("proxmox.token_secret", message)
|
||||||
|
|
||||||
|
def test_cloudflare_token_env_must_be_a_name(self) -> None:
|
||||||
|
raw = raw_config()
|
||||||
|
raw["cloudflare"] = {"api_token_env": "cf-secret-value"}
|
||||||
|
config = parse_config(raw)
|
||||||
|
with self.assertRaises(ConfigError) as ctx:
|
||||||
|
config.cloudflare.resolve_token()
|
||||||
|
self.assertIn("cloudflare.api_token", str(ctx.exception))
|
||||||
|
|
||||||
def test_secret_from_file(self) -> None:
|
def test_secret_from_file(self) -> None:
|
||||||
with tempfile.TemporaryDirectory() as tmp:
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
secret = Path(tmp) / "pve.secret"
|
secret = Path(tmp) / "pve.secret"
|
||||||
@@ -152,6 +215,36 @@ class ConfigTests(unittest.TestCase):
|
|||||||
config = parse_config(raw)
|
config = parse_config(raw)
|
||||||
self.assertEqual(config.webserver.test_command, ())
|
self.assertEqual(config.webserver.test_command, ())
|
||||||
|
|
||||||
|
def test_dns_target_defaults_to_host(self) -> None:
|
||||||
|
raw = raw_config()
|
||||||
|
self.assertEqual(parse_config(raw).dns.target, "host")
|
||||||
|
|
||||||
|
def test_fixed_dns_requires_address(self) -> None:
|
||||||
|
raw = raw_config()
|
||||||
|
raw["dns"] = {"target": "fixed"}
|
||||||
|
with self.assertRaises(ConfigError) as ctx:
|
||||||
|
parse_config(raw)
|
||||||
|
self.assertIn("dns.address", str(ctx.exception))
|
||||||
|
|
||||||
|
def test_invalid_dns_address(self) -> None:
|
||||||
|
raw = raw_config()
|
||||||
|
raw["dns"] = {"target": "fixed", "address": "not-an-ip"}
|
||||||
|
with self.assertRaises(ConfigError):
|
||||||
|
parse_config(raw)
|
||||||
|
|
||||||
|
def test_invalid_dns_target(self) -> None:
|
||||||
|
raw = raw_config()
|
||||||
|
raw["dns"] = {"target": "cloudflare"}
|
||||||
|
with self.assertRaises(ConfigError) as ctx:
|
||||||
|
parse_config(raw)
|
||||||
|
self.assertIn("guest, host, fixed", str(ctx.exception))
|
||||||
|
|
||||||
|
def test_invalid_detect_url(self) -> None:
|
||||||
|
raw = raw_config()
|
||||||
|
raw["dns"] = {"detect_url_v4": "ftp://example.com"}
|
||||||
|
with self.assertRaises(ConfigError):
|
||||||
|
parse_config(raw)
|
||||||
|
|
||||||
def test_bad_toml(self) -> None:
|
def test_bad_toml(self) -> None:
|
||||||
with tempfile.TemporaryDirectory() as tmp:
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
path = Path(tmp) / "broken.toml"
|
path = Path(tmp) / "broken.toml"
|
||||||
|
|||||||
+230
-2
@@ -4,7 +4,9 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
|
from proxdomain.addressing import PublicAddressResolver, ResolvedAddress
|
||||||
from proxdomain.cloudflare import CloudflareClient
|
from proxdomain.cloudflare import CloudflareClient
|
||||||
|
from proxdomain.errors import ProxdomainError
|
||||||
from proxdomain.proxmox import ProxmoxClient
|
from proxdomain.proxmox import ProxmoxClient
|
||||||
from proxdomain.service import DomainService, sanitize_hostname
|
from proxdomain.service import DomainService, sanitize_hostname
|
||||||
from proxdomain.state import Assignment, StateStore
|
from proxdomain.state import Assignment, StateStore
|
||||||
@@ -20,6 +22,10 @@ def build(
|
|||||||
guests: list[dict] | None = None,
|
guests: list[dict] | None = None,
|
||||||
agent_ips: list[str] | None = None,
|
agent_ips: list[str] | None = None,
|
||||||
records: list[dict] | None = None,
|
records: list[dict] | None = None,
|
||||||
|
dns: dict | None = None,
|
||||||
|
resolver_factory=None,
|
||||||
|
files: dict[str, str] | None = None,
|
||||||
|
**webserver,
|
||||||
):
|
):
|
||||||
guests = guests if guests is not None else [
|
guests = guests if guests is not None else [
|
||||||
{
|
{
|
||||||
@@ -66,19 +72,36 @@ def build(
|
|||||||
transport.add("PATCH", f"{DNS_PATH}/rec-1", update)
|
transport.add("PATCH", f"{DNS_PATH}/rec-1", update)
|
||||||
transport.add("DELETE", f"{DNS_PATH}/rec-1", cf({"id": "rec-1"}))
|
transport.add("DELETE", f"{DNS_PATH}/rec-1", cf({"id": "rec-1"}))
|
||||||
|
|
||||||
config = make_config()
|
config = make_config(dns=dns, **webserver)
|
||||||
runner = FakeRunner()
|
runner = FakeRunner(files)
|
||||||
service = DomainService(
|
service = DomainService(
|
||||||
config,
|
config,
|
||||||
proxmox=ProxmoxClient(config.proxmox, transport=transport),
|
proxmox=ProxmoxClient(config.proxmox, transport=transport),
|
||||||
cloudflare=CloudflareClient(config.cloudflare, transport=transport),
|
cloudflare=CloudflareClient(config.cloudflare, transport=transport),
|
||||||
webserver=WebServerManager(config.webserver, runner),
|
webserver=WebServerManager(config.webserver, runner),
|
||||||
state=StateStore(":memory:"),
|
state=StateStore(":memory:"),
|
||||||
|
dns_resolver=resolver_factory(config.dns) if resolver_factory else None,
|
||||||
)
|
)
|
||||||
return service, transport, runner, stored
|
return service, transport, runner, stored
|
||||||
|
|
||||||
|
|
||||||
SITE_FILE = "/etc/nginx/conf.d/proxdomain.d/web01.example.com.conf"
|
SITE_FILE = "/etc/nginx/conf.d/proxdomain.d/web01.example.com.conf"
|
||||||
|
PUBLIC_IP = "93.184.216.34"
|
||||||
|
|
||||||
|
|
||||||
|
class _StubResolver:
|
||||||
|
def __init__(self, address: str) -> None:
|
||||||
|
self.address = address
|
||||||
|
|
||||||
|
def resolve(self, *, guest_address: str = "", override: str | None = None):
|
||||||
|
return ResolvedAddress(self.address, "test")
|
||||||
|
|
||||||
|
|
||||||
|
class _FailingResolver:
|
||||||
|
def resolve(self, *, guest_address: str = "", override: str | None = None):
|
||||||
|
raise ProxdomainError(
|
||||||
|
"cannot determine the Proxmox host's public address; set dns.address"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class AssignTests(unittest.TestCase):
|
class AssignTests(unittest.TestCase):
|
||||||
@@ -126,6 +149,62 @@ class AssignTests(unittest.TestCase):
|
|||||||
self.assertTrue(report.ok)
|
self.assertTrue(report.ok)
|
||||||
self.assertFalse(transport.calls_to("POST", DNS_PATH)[0].body["proxied"])
|
self.assertFalse(transport.calls_to("POST", DNS_PATH)[0].body["proxied"])
|
||||||
|
|
||||||
|
def test_address_override(self) -> None:
|
||||||
|
service, transport, _, _ = build()
|
||||||
|
report = service.assign(vmid=101, address=PUBLIC_IP)
|
||||||
|
self.assertTrue(report.ok, report.to_dict())
|
||||||
|
body = transport.calls_to("POST", DNS_PATH)[0].body
|
||||||
|
self.assertEqual(body["content"], PUBLIC_IP)
|
||||||
|
self.assertTrue(body["proxied"])
|
||||||
|
self.assertEqual(report.assignment.ip, "10.0.0.5")
|
||||||
|
|
||||||
|
def test_fixed_address_is_published_not_the_guest_ip(self) -> None:
|
||||||
|
service, transport, runner, _ = build(
|
||||||
|
dns={"target": "fixed", "address": PUBLIC_IP}
|
||||||
|
)
|
||||||
|
report = service.assign(vmid=101)
|
||||||
|
self.assertTrue(report.ok, report.to_dict())
|
||||||
|
body = transport.calls_to("POST", DNS_PATH)[0].body
|
||||||
|
self.assertEqual(body["content"], PUBLIC_IP)
|
||||||
|
self.assertTrue(body["proxied"])
|
||||||
|
self.assertIn("proxy_pass http://10.0.0.5:80;", runner.files[SITE_FILE])
|
||||||
|
self.assertEqual(report.assignment.dns_ip, PUBLIC_IP)
|
||||||
|
self.assertEqual(report.assignment.ip, "10.0.0.5")
|
||||||
|
|
||||||
|
def test_host_target_uses_detected_public_address(self) -> None:
|
||||||
|
service, transport, _, _ = build(
|
||||||
|
dns={"target": "host"},
|
||||||
|
resolver_factory=lambda cfg: PublicAddressResolver(
|
||||||
|
cfg, fetch_text=lambda url: PUBLIC_IP + "\n"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
report = service.assign(vmid=101)
|
||||||
|
self.assertTrue(report.ok, report.to_dict())
|
||||||
|
self.assertEqual(
|
||||||
|
transport.calls_to("POST", DNS_PATH)[0].body["content"], PUBLIC_IP
|
||||||
|
)
|
||||||
|
details = " ".join(step.detail for step in report.steps)
|
||||||
|
self.assertIn(PUBLIC_IP, details)
|
||||||
|
self.assertIn("detected via", details)
|
||||||
|
|
||||||
|
def test_unresolvable_host_target_stops_before_writing(self) -> None:
|
||||||
|
service, transport, runner, _ = build(
|
||||||
|
dns={"target": "host"}, resolver_factory=lambda cfg: _FailingResolver()
|
||||||
|
)
|
||||||
|
report = service.assign(vmid=101)
|
||||||
|
self.assertFalse(report.ok)
|
||||||
|
self.assertEqual(report.steps[-1].name, "dns-address")
|
||||||
|
self.assertEqual(runner.files, {})
|
||||||
|
self.assertEqual(transport.count("POST", DNS_PATH), 0)
|
||||||
|
|
||||||
|
def test_dry_run_reports_the_published_address(self) -> None:
|
||||||
|
service, _, runner, _ = build(dns={"target": "fixed", "address": PUBLIC_IP})
|
||||||
|
report = service.assign(vmid=101, dry_run=True)
|
||||||
|
self.assertTrue(report.ok, report.to_dict())
|
||||||
|
details = " ".join(step.detail for step in report.steps)
|
||||||
|
self.assertIn(PUBLIC_IP, details)
|
||||||
|
self.assertEqual(runner.files, {})
|
||||||
|
|
||||||
def test_dry_run_changes_nothing(self) -> None:
|
def test_dry_run_changes_nothing(self) -> None:
|
||||||
service, transport, runner, stored = build()
|
service, transport, runner, stored = build()
|
||||||
report = service.assign(vmid=101, dry_run=True)
|
report = service.assign(vmid=101, dry_run=True)
|
||||||
@@ -254,6 +333,23 @@ class SyncTests(unittest.TestCase):
|
|||||||
self.assertEqual(service.state.get("web01.example.com").ip, "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])
|
self.assertIn("10.0.0.77", runner.files[SITE_FILE])
|
||||||
|
|
||||||
|
def test_sync_updates_published_address(self) -> None:
|
||||||
|
stub = _StubResolver(PUBLIC_IP)
|
||||||
|
service, transport, _, stored = build(
|
||||||
|
dns={"target": "host"}, resolver_factory=lambda cfg: stub
|
||||||
|
)
|
||||||
|
service.assign(vmid=101)
|
||||||
|
self.assertEqual(stored[0]["content"], PUBLIC_IP)
|
||||||
|
|
||||||
|
stub.address = "93.184.216.35"
|
||||||
|
report = service.sync()
|
||||||
|
self.assertTrue(report.ok, report.to_dict())
|
||||||
|
self.assertEqual(stored[0]["content"], "93.184.216.35")
|
||||||
|
self.assertEqual(
|
||||||
|
service.state.get("web01.example.com").dns_ip, "93.184.216.35"
|
||||||
|
)
|
||||||
|
self.assertEqual(transport.count("PATCH", f"{DNS_PATH}/rec-1"), 1)
|
||||||
|
|
||||||
|
|
||||||
class DiscoveryTests(unittest.TestCase):
|
class DiscoveryTests(unittest.TestCase):
|
||||||
def test_watch_candidates_respects_tag_and_state(self) -> None:
|
def test_watch_candidates_respects_tag_and_state(self) -> None:
|
||||||
@@ -277,6 +373,14 @@ class DiscoveryTests(unittest.TestCase):
|
|||||||
names = {step.name for step in report.steps}
|
names = {step.name for step in report.steps}
|
||||||
self.assertTrue({"proxmox", "cloudflare", "web-server", "state"} <= names)
|
self.assertTrue({"proxmox", "cloudflare", "web-server", "state"} <= names)
|
||||||
|
|
||||||
|
def test_doctor_shows_the_dns_target(self) -> None:
|
||||||
|
service, _, _, _ = build(dns={"target": "fixed", "address": PUBLIC_IP})
|
||||||
|
report = service.doctor()
|
||||||
|
self.assertTrue(report.ok, report.to_dict())
|
||||||
|
step = next(step for step in report.steps if step.name == "dns-target")
|
||||||
|
self.assertIn(PUBLIC_IP, step.detail)
|
||||||
|
self.assertIn("dns.address", step.detail)
|
||||||
|
|
||||||
def test_init_dry_run(self) -> None:
|
def test_init_dry_run(self) -> None:
|
||||||
service, _, runner, _ = build()
|
service, _, runner, _ = build()
|
||||||
report = service.init(dry_run=True)
|
report = service.init(dry_run=True)
|
||||||
@@ -284,6 +388,130 @@ class DiscoveryTests(unittest.TestCase):
|
|||||||
self.assertEqual(runner.files, {})
|
self.assertEqual(runner.files, {})
|
||||||
|
|
||||||
|
|
||||||
|
class TlsTests(unittest.TestCase):
|
||||||
|
"""Automatic Let's Encrypt certificates."""
|
||||||
|
|
||||||
|
CERT = "/etc/letsencrypt/live/web01.example.com/fullchain.pem"
|
||||||
|
|
||||||
|
def _service(self, **kwargs):
|
||||||
|
return build(
|
||||||
|
tls={"mode": "letsencrypt", "email": "ops@example.com"},
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_dns_is_published_before_the_certificate_request(self) -> None:
|
||||||
|
service, transport, runner, _ = self._service()
|
||||||
|
report = service.assign(vmid=101)
|
||||||
|
self.assertTrue(report.ok, report.to_dict())
|
||||||
|
|
||||||
|
# The A record must exist before certbot validates the name, and certbot
|
||||||
|
# must run before the TLS vhost replaces the HTTP challenge vhost.
|
||||||
|
commands = [" ".join(command) for command in runner.commands]
|
||||||
|
certbot_index = next(i for i, c in enumerate(commands) if c.startswith("certbot"))
|
||||||
|
self.assertTrue(commands[certbot_index:])
|
||||||
|
self.assertEqual(transport.count("POST", DNS_PATH), 1)
|
||||||
|
names = [step.name for step in report.steps]
|
||||||
|
self.assertLess(names.index("dns"), names.index("web-config"))
|
||||||
|
|
||||||
|
content = runner.files["/etc/nginx/conf.d/proxdomain.d/web01.example.com.conf"]
|
||||||
|
self.assertIn(
|
||||||
|
"ssl_certificate /etc/letsencrypt/live/web01.example.com/fullchain.pem",
|
||||||
|
content,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_caddy_publishes_dns_before_the_site(self) -> None:
|
||||||
|
service, transport, runner, _ = build(
|
||||||
|
kind="caddy",
|
||||||
|
tls={"mode": "letsencrypt", "email": "ops@example.com"},
|
||||||
|
)
|
||||||
|
report = service.assign(vmid=101)
|
||||||
|
self.assertTrue(report.ok, report.to_dict())
|
||||||
|
names = [step.name for step in report.steps]
|
||||||
|
self.assertLess(names.index("dns"), names.index("web-config"))
|
||||||
|
self.assertEqual(transport.count("POST", DNS_PATH), 1)
|
||||||
|
self.assertIn("issuer acme", runner.files[
|
||||||
|
"/etc/caddy/proxdomain.d/web01.example.com.caddy"
|
||||||
|
])
|
||||||
|
|
||||||
|
def test_caddy_without_tls_keeps_config_first(self) -> None:
|
||||||
|
service, _, _, _ = build(kind="caddy")
|
||||||
|
report = service.assign(vmid=101)
|
||||||
|
self.assertTrue(report.ok, report.to_dict())
|
||||||
|
names = [step.name for step in report.steps]
|
||||||
|
self.assertLess(names.index("web-config"), names.index("dns"))
|
||||||
|
|
||||||
|
def test_assign_reports_the_certificate(self) -> None:
|
||||||
|
service, _, runner, _ = self._service(files={self.CERT: "cert"})
|
||||||
|
report = service.assign(vmid=101)
|
||||||
|
self.assertTrue(report.ok, report.to_dict())
|
||||||
|
step = next(s for s in report.steps if s.name == "tls")
|
||||||
|
self.assertEqual(step.status, "ok")
|
||||||
|
self.assertIn("Let's Encrypt", step.detail)
|
||||||
|
self.assertFalse(any(c[0] == "certbot" for c in runner.commands))
|
||||||
|
|
||||||
|
def test_existing_assignment_syncs_without_reissuing(self) -> None:
|
||||||
|
service, _, runner, _ = self._service(files={self.CERT: "cert"})
|
||||||
|
service.assign(vmid=101)
|
||||||
|
certbot_calls = [c for c in runner.commands if c[0] == "certbot"]
|
||||||
|
self.assertEqual(certbot_calls, [])
|
||||||
|
report = service.sync()
|
||||||
|
self.assertTrue(report.ok, report.to_dict())
|
||||||
|
self.assertEqual(
|
||||||
|
service.state.get("web01.example.com").tls, "letsencrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_failed_issuance_keeps_no_vhost(self) -> None:
|
||||||
|
service, transport, runner, stored = build(
|
||||||
|
tls={"mode": "letsencrypt", "email": "ops@example.com"}
|
||||||
|
)
|
||||||
|
runner.failures.append(("certbot", 1, "dns problem"))
|
||||||
|
report = service.assign(vmid=101)
|
||||||
|
self.assertFalse(report.ok)
|
||||||
|
self.assertIn("certbot failed", " ".join(s.detail for s in report.steps))
|
||||||
|
self.assertEqual([p for p in runner.files if p.endswith(".conf")], [])
|
||||||
|
# The name stays published so a retry can validate immediately.
|
||||||
|
self.assertEqual(len(stored), 1)
|
||||||
|
self.assertEqual(transport.count("POST", DNS_PATH), 1)
|
||||||
|
self.assertEqual(service.state.all(), [])
|
||||||
|
|
||||||
|
def test_doctor_reports_the_tls_mode(self) -> None:
|
||||||
|
service, _, _, _ = self._service(files={self.CERT: "cert"})
|
||||||
|
report = service.doctor()
|
||||||
|
step = next(s for s in report.steps if s.name == "tls")
|
||||||
|
self.assertEqual(step.status, "ok")
|
||||||
|
self.assertIn("certbot", step.detail)
|
||||||
|
|
||||||
|
def test_doctor_warns_when_certbot_is_missing(self) -> None:
|
||||||
|
service, _, runner, _ = build(
|
||||||
|
tls={"mode": "letsencrypt", "email": "ops@example.com"}
|
||||||
|
)
|
||||||
|
runner.failures.append(("certbot --version", 127, "command not found"))
|
||||||
|
report = service.doctor()
|
||||||
|
step = next(s for s in report.steps if s.name == "tls")
|
||||||
|
self.assertEqual(step.status, "warning")
|
||||||
|
self.assertIn("not installed", step.detail)
|
||||||
|
|
||||||
|
def test_doctor_probes_the_configured_certbot_binary(self) -> None:
|
||||||
|
service, _, runner, _ = build(
|
||||||
|
tls={
|
||||||
|
"mode": "letsencrypt",
|
||||||
|
"email": "ops@example.com",
|
||||||
|
"certbot_command": ["/opt/venv/bin/certbot", "certonly", "--webroot"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
report = service.doctor()
|
||||||
|
step = next(s for s in report.steps if s.name == "tls")
|
||||||
|
self.assertIn("/opt/venv/bin/certbot", step.detail)
|
||||||
|
self.assertTrue(
|
||||||
|
any(command[0] == "/opt/venv/bin/certbot" for command in runner.commands)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_list_records_the_tls_mode(self) -> None:
|
||||||
|
service, _, _, _ = self._service(files={self.CERT: "cert"})
|
||||||
|
service.assign(vmid=101)
|
||||||
|
self.assertEqual(service.state.get("web01.example.com").tls, "letsencrypt")
|
||||||
|
|
||||||
|
|
||||||
class HostnameTests(unittest.TestCase):
|
class HostnameTests(unittest.TestCase):
|
||||||
def test_sanitize(self) -> None:
|
def test_sanitize(self) -> None:
|
||||||
self.assertEqual(sanitize_hostname("Web Server", 1), "web-server")
|
self.assertEqual(sanitize_hostname("Web Server", 1), "web-server")
|
||||||
|
|||||||
+4
-1
@@ -21,7 +21,9 @@ class StateTests(unittest.TestCase):
|
|||||||
path = str(Path(tmp) / "state.json")
|
path = str(Path(tmp) / "state.json")
|
||||||
store = StateStore(path, audit_path=str(Path(tmp) / "audit.jsonl"))
|
store = StateStore(path, audit_path=str(Path(tmp) / "audit.jsonl"))
|
||||||
store.load()
|
store.load()
|
||||||
store.upsert(assignment())
|
item = assignment()
|
||||||
|
item.dns_ip = "93.184.216.34"
|
||||||
|
store.upsert(item)
|
||||||
store.flush()
|
store.flush()
|
||||||
|
|
||||||
reloaded = StateStore(path)
|
reloaded = StateStore(path)
|
||||||
@@ -29,6 +31,7 @@ class StateTests(unittest.TestCase):
|
|||||||
self.assertEqual(len(items), 1)
|
self.assertEqual(len(items), 1)
|
||||||
self.assertEqual(items[0].fqdn, "web01.example.com")
|
self.assertEqual(items[0].fqdn, "web01.example.com")
|
||||||
self.assertEqual(items[0].ip, "10.0.0.5")
|
self.assertEqual(items[0].ip, "10.0.0.5")
|
||||||
|
self.assertEqual(items[0].dns_ip, "93.184.216.34")
|
||||||
self.assertTrue(items[0].created_at)
|
self.assertTrue(items[0].created_at)
|
||||||
|
|
||||||
def test_created_at_is_preserved(self) -> None:
|
def test_created_at_is_preserved(self) -> None:
|
||||||
|
|||||||
+110
-1
@@ -4,7 +4,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
from proxdomain.errors import WebServerError
|
from proxdomain.errors import ProxdomainError, WebServerError
|
||||||
from proxdomain.webserver import SiteSpec, WebServerManager, render_nginx_challenge
|
from proxdomain.webserver import SiteSpec, WebServerManager, render_nginx_challenge
|
||||||
from tests.support import FakeRunner, make_config
|
from tests.support import FakeRunner, make_config
|
||||||
|
|
||||||
@@ -74,6 +74,38 @@ class RenderTests(unittest.TestCase):
|
|||||||
content = manager.render(spec(webserver="traefik"))
|
content = manager.render(spec(webserver="traefik"))
|
||||||
self.assertIn("tls: {}", content)
|
self.assertIn("tls: {}", content)
|
||||||
|
|
||||||
|
def test_caddy_letsencrypt_issuer(self) -> None:
|
||||||
|
manager = WebServerManager(
|
||||||
|
make_config(kind="caddy", tls={"mode": "letsencrypt", "email": "ops@example.com"}).webserver,
|
||||||
|
FakeRunner(),
|
||||||
|
)
|
||||||
|
content = manager.render(
|
||||||
|
spec(webserver="caddy", tls_mode="letsencrypt", tls_email="ops@example.com")
|
||||||
|
)
|
||||||
|
self.assertIn("tls {", content)
|
||||||
|
self.assertIn("issuer acme {", content)
|
||||||
|
self.assertIn("email ops@example.com", content)
|
||||||
|
self.assertNotIn("dir ", content) # default CA is already Let's Encrypt
|
||||||
|
|
||||||
|
def test_caddy_acme_ca_override(self) -> None:
|
||||||
|
staging = "https://acme-staging-v02.api.letsencrypt.org/directory"
|
||||||
|
manager = WebServerManager(
|
||||||
|
make_config(
|
||||||
|
kind="caddy",
|
||||||
|
tls={"mode": "letsencrypt", "email": "ops@example.com", "acme_ca": staging},
|
||||||
|
).webserver,
|
||||||
|
FakeRunner(),
|
||||||
|
)
|
||||||
|
content = manager.render(
|
||||||
|
spec(
|
||||||
|
webserver="caddy",
|
||||||
|
tls_mode="letsencrypt",
|
||||||
|
tls_email="ops@example.com",
|
||||||
|
acme_ca=staging,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.assertIn(f"dir {staging}", content)
|
||||||
|
|
||||||
def test_site_path(self) -> None:
|
def test_site_path(self) -> None:
|
||||||
manager = WebServerManager(make_config().webserver, FakeRunner())
|
manager = WebServerManager(make_config().webserver, FakeRunner())
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
@@ -204,6 +236,21 @@ class CertbotTests(unittest.TestCase):
|
|||||||
self.assertIn("certbot failed", str(ctx.exception))
|
self.assertIn("certbot failed", str(ctx.exception))
|
||||||
self.assertEqual(runner.files, {})
|
self.assertEqual(runner.files, {})
|
||||||
|
|
||||||
|
def test_missing_certbot_binary_is_explained(self) -> None:
|
||||||
|
class ExplodingRunner(FakeRunner):
|
||||||
|
def run(self, argv, *, input_text=None, timeout=120.0):
|
||||||
|
if tuple(argv)[0] == "certbot":
|
||||||
|
raise ProxdomainError("command not found: certbot")
|
||||||
|
return super().run(argv, input_text=input_text, timeout=timeout)
|
||||||
|
|
||||||
|
runner = ExplodingRunner()
|
||||||
|
manager = self._manager(runner)
|
||||||
|
with self.assertRaises(WebServerError) as ctx:
|
||||||
|
manager.apply(spec(tls_mode="certbot"))
|
||||||
|
self.assertIn("cannot run certbot", str(ctx.exception))
|
||||||
|
self.assertIn("apt install certbot", str(ctx.exception))
|
||||||
|
self.assertEqual(runner.files, {})
|
||||||
|
|
||||||
def test_existing_certificate_skips_certbot(self) -> None:
|
def test_existing_certificate_skips_certbot(self) -> None:
|
||||||
runner = FakeRunner(
|
runner = FakeRunner(
|
||||||
{"/etc/letsencrypt/live/web01.example.com/fullchain.pem": "cert"}
|
{"/etc/letsencrypt/live/web01.example.com/fullchain.pem": "cert"}
|
||||||
@@ -213,8 +260,70 @@ class CertbotTests(unittest.TestCase):
|
|||||||
self.assertTrue(result.changed)
|
self.assertTrue(result.changed)
|
||||||
self.assertFalse(any(command[0] == "certbot" for command in runner.commands))
|
self.assertFalse(any(command[0] == "certbot" for command in runner.commands))
|
||||||
|
|
||||||
|
def test_letsencrypt_mode_is_idempotent_and_renewable(self) -> None:
|
||||||
|
config = make_config(tls={"mode": "letsencrypt", "email": "ops@example.com"})
|
||||||
|
runner = FakeRunner()
|
||||||
|
manager = WebServerManager(config.webserver, runner)
|
||||||
|
manager.apply(spec(tls_mode="letsencrypt"))
|
||||||
|
command = next(c for c in runner.commands if c[0] == "certbot")
|
||||||
|
self.assertIn("--keep-until-expiring", command)
|
||||||
|
self.assertIn("--email", command)
|
||||||
|
self.assertEqual(command[command.index("--email") + 1], "ops@example.com")
|
||||||
|
# Renewals must reload nginx, otherwise the new certificate is never used.
|
||||||
|
self.assertEqual(
|
||||||
|
command[command.index("--deploy-hook") + 1], "systemctl reload nginx"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_renew_hook_and_acme_ca_are_passed_through(self) -> None:
|
||||||
|
staging = "https://acme-staging-v02.api.letsencrypt.org/directory"
|
||||||
|
config = make_config(
|
||||||
|
tls={
|
||||||
|
"mode": "letsencrypt",
|
||||||
|
"email": "ops@example.com",
|
||||||
|
"acme_ca": staging,
|
||||||
|
"renew_hook": "systemctl reload nginx && echo done",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
runner = FakeRunner()
|
||||||
|
manager = WebServerManager(config.webserver, runner)
|
||||||
|
manager.apply(spec(tls_mode="letsencrypt"))
|
||||||
|
command = next(c for c in runner.commands if c[0] == "certbot")
|
||||||
|
self.assertEqual(command[command.index("--server") + 1], staging)
|
||||||
|
self.assertEqual(
|
||||||
|
command[command.index("--deploy-hook") + 1],
|
||||||
|
"systemctl reload nginx && echo done",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_webroot_is_created_before_certbot_runs(self) -> None:
|
||||||
|
runner = FakeRunner()
|
||||||
|
manager = self._manager(runner)
|
||||||
|
manager.apply(spec(tls_mode="letsencrypt"))
|
||||||
|
self.assertIn("/var/www/certbot", runner.dirs)
|
||||||
|
commands = [" ".join(c) for c in runner.commands]
|
||||||
|
certbot_index = next(i for i, c in enumerate(commands) if c.startswith("certbot"))
|
||||||
|
self.assertIn("root /var/www/certbot;", runner.files[list(runner.files)[0]])
|
||||||
|
self.assertGreater(certbot_index, 0)
|
||||||
|
|
||||||
|
|
||||||
class BootstrapTests(unittest.TestCase):
|
class BootstrapTests(unittest.TestCase):
|
||||||
|
def test_bootstrap_mentions_automatic_certificates(self) -> None:
|
||||||
|
runner = FakeRunner()
|
||||||
|
config = make_config(kind="caddy", tls={"mode": "letsencrypt", "email": "ops@example.com"})
|
||||||
|
steps = WebServerManager(config.webserver, runner).bootstrap(dry_run=True)
|
||||||
|
self.assertTrue(
|
||||||
|
any("Let's Encrypt" in detail for _, detail in steps), steps
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_bootstrap_creates_the_acme_webroot_for_nginx(self) -> None:
|
||||||
|
runner = FakeRunner()
|
||||||
|
config = make_config(tls={"mode": "letsencrypt", "email": "ops@example.com"})
|
||||||
|
WebServerManager(config.webserver, runner).bootstrap()
|
||||||
|
self.assertIn("/var/www/certbot", runner.dirs)
|
||||||
|
self.assertTrue(
|
||||||
|
any("certbot" in detail for _, detail in
|
||||||
|
WebServerManager(config.webserver, runner).bootstrap())
|
||||||
|
)
|
||||||
|
|
||||||
def test_nginx_include_written_once(self) -> None:
|
def test_nginx_include_written_once(self) -> None:
|
||||||
runner = FakeRunner()
|
runner = FakeRunner()
|
||||||
manager = WebServerManager(make_config().webserver, runner)
|
manager = WebServerManager(make_config().webserver, runner)
|
||||||
|
|||||||
Reference in new issue
Block a user