feat!: complete refactoring of server #1

Merged
mxmehl merged 10 commits from v2 into master 2026-10-22 15:35:55 +02:00
5 changed files with 198 additions and 12 deletions
Showing only changes of commit 835f1642d9 - Show all commits

No files matched your search

+6 -4
View File
@@ -13,7 +13,7 @@ It speaks the common dyndns2 protocol (HTTP Basic Auth, `myip`/`myipv6`, `good`/
3. If the IP equals the last one it stored, it answers `nochg` right away. INWX is not contacted, so polling every minute is cheap.
4. Otherwise it logs in to INWX, looks up the record by name and type, updates it, and only then stores the new IP. If INWX fails, the device gets `911` and retries on its next run.
The record (A and/or AAAA) has to exist at INWX already. The server picks A or AAAA depending on the IP family, and keeps the TTL you set there. The connection to INWX uses IPv4 only, so an IP-restricted INWX API account only needs the server's IPv4 address on its allow-list.
The record (A and/or AAAA) has to exist at INWX; the helper script below creates it for new hosts. The server picks A or AAAA depending on the IP family, and keeps the TTL of the record. The connection to INWX uses IPv4 only, so an IP-restricted INWX API account only needs the server's IPv4 address on its allow-list.
## Requirements
@@ -74,12 +74,14 @@ With another proxy, stop the service (`supervisorctl stop snap-dyndns`), run `nc
### Adding a device
The helper creates a random token, stores only its SHA-256 in the config and prints the token once:
The helper creates a random token, stores only its SHA-256 in the config, prints the token once, and makes sure the DNS record exists at INWX:
```
python3 ~/snap-dyndns-server/snap_dyndns_host.py user1.example.com
```
If the A record does not exist at INWX yet, it is created with the TTL 300 and a placeholder address, which the first update of the device replaces. An existing record is left alone. Use `-t A,AAAA` to handle both types, `--ttl` for another TTL of new records, and `--no-dns` to skip INWX completely. If INWX cannot be reached, nothing is changed in the config. The helper needs the INWX login from the config and is therefore best run on the server itself, as an IP-restricted INWX account refuses logins from elsewhere.
Give the printed token to the device, for the [client](https://src.mehl.mx/mxmehl/snap-dyndns-client) it is the `hostname:token` entry shown in the output. For an existing host it asks before replacing the token (`-y` skips the question), and the old token stops working immediately. Use `-c` for a config in another location and `-z example.co.uk` for a new host whose INWX zone is not the last two labels of its name. Comments and the rest of the config stay untouched. The config is read on every request, so no restart is needed.
The hostname is the Basic Auth user name, the token the password. Without the helper, generate a token and hash yourself with `python3 -c 'import secrets,hashlib;t=secrets.token_urlsafe(32);print(t, hashlib.sha256(t.encode()).hexdigest())'` and add a section `[hosts."user1.example.com"]` with `token_sha256 = "<hash>"`.
@@ -133,7 +135,7 @@ user1.example.com
## Known limits
- Explicit `myip`/`myipv6` values are only checked for syntax, private and reserved addresses are accepted there.
- Missing records are not created, add them at INWX first.
- The server itself never creates records, only the helper script does when adding a host.
- If you change a record at INWX by hand, the server does not notice. Delete `state.json` or change the IP to resync.
- Only one request updates at a time (a lock is held during the INWX call), which is plenty for a personal setup.
- The built-in HTTP server is meant to sit behind a reverse proxy. Do not expose its port directly.
@@ -144,7 +146,7 @@ user1.example.com
uv run --python 3.14 python -m unittest -v
```
The tests use a fake INWX server. An additional smoke test runs against the INWX OT&E test system and is skipped unless `INWX_OTE_USER`, `INWX_OTE_PASS` and `INWX_OTE_HOST` (an existing A record in that account) are set in the environment. It restores the record afterwards.
The tests use a fake INWX server. An additional smoke test runs against the INWX OT&E test system and is skipped unless `INWX_OTE_USER`, `INWX_OTE_PASS` and `INWX_OTE_HOST` (an existing A record in that account) are set in the environment. It restores the record afterwards and removes the record it creates for the helper test.
## License
+29 -1
View File
@@ -132,6 +132,34 @@ def inwx_update(cfg, zone, name, rtype, ip):
return True
PLACEHOLDER = {"A": "192.0.2.1", "AAAA": "2001:db8::1"} # documentation addresses
def zone_of(host, entry):
"""INWX zone of a hostname: the host's `zone` setting, else its last two labels."""
return entry.get("zone") or ".".join(host.split(".")[-2:])
def ensure_record(cfg, zone, name, rtype, ttl=300):
"""Create the record with a placeholder address if missing. Return (created, record)."""
with inwx_session(cfg) as call:
try:
return False, find_record(call, zone, name, rtype)
except NoHost:
content = PLACEHOLDER[rtype]
call(
"nameserver.createRecord",
{
"domain": zone,
"type": rtype,
"name": name,
"content": content,
"ttl": ttl,
},
)
return True, {"content": content, "ttl": ttl}
# --- Request handling -------------------------------------------------------
@@ -214,7 +242,7 @@ def handle(env, cfg, update=inwx_update, note=None):
# shortcut: explicit myip/myipv6 are only syntax-checked (private ranges accepted), tighten if clients misbehave
ips["A" if ip.version == 4 else "AAAA"] = str(ip)
zone = cfg["hosts"][host].get("zone") or ".".join(host.split(".")[-2:])
zone = zone_of(host, cfg["hosts"][host])
state_path = os.path.expanduser(cfg.get("state_file", DEFAULT_STATE))
os.makedirs(os.path.dirname(state_path), exist_ok=True)
+51 -3
View File
@@ -5,6 +5,7 @@
Generates a random token, stores only its SHA-256 in the config and prints the
token once. The token is what the client needs; the server never sees it again.
Also makes sure the DNS record exists at INWX, which needs the server's IP.
"""
import argparse
@@ -16,7 +17,7 @@ import sys
import tempfile
import tomllib
from snap_dyndns import DEFAULT_CONFIG
from snap_dyndns import DEFAULT_CONFIG, InwxError, ensure_record, zone_of
NAME = re.compile(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$")
@@ -90,6 +91,23 @@ def main(argv=None):
action="store_true",
help="replace the token of an existing host without asking",
)
parser.add_argument(
"-t",
"--types",
default="A",
help="record types to check and create, A or AAAA or A,AAAA (default: A)",
)
parser.add_argument(
"--ttl",
type=int,
default=300,
help="TTL of records created at INWX (default: 300)",
)
parser.add_argument(
"--no-dns",
action="store_true",
help="do not touch INWX, e.g. when not running on the server",
)
parser.add_argument(
"-z",
"--zone",
@@ -101,6 +119,9 @@ def main(argv=None):
for value in (host, args.zone):
if value and not NAME.match(value):
sys.exit(f"invalid name: {value}")
types = [t.strip().upper() for t in args.types.split(",")]
if not set(types) <= {"A", "AAAA"}:
sys.exit(f"invalid record types: {args.types}")
path = os.path.expanduser(args.config)
token = secrets.token_urlsafe(32)
@@ -116,11 +137,38 @@ def main(argv=None):
):
sys.exit("Aborted, config unchanged")
new_text, created = set_host(text, host, digest, args.zone)
tomllib.loads(new_text) # never write a config that does not parse
write_config(path, new_text)
cfg = tomllib.loads(new_text) # never write a config that does not parse
except (OSError, ValueError) as e: # TOMLDecodeError is a ValueError
sys.exit(f"{path}: {e}")
# DNS first: if INWX is not reachable, nothing has been changed yet
if not args.no_dns:
zone = zone_of(host, cfg["hosts"][host])
try:
for rtype in types:
was_created, record = ensure_record(cfg, zone, host, rtype, args.ttl)
if was_created:
print(
f"DNS: created {rtype} record {host} ({record['content']} is a placeholder, "
f"TTL {record['ttl']}), the first update sets the real address"
)
else:
print(
f"DNS: {rtype} record {host} exists "
f"({record['content']}, TTL {record.get('ttl')})"
)
except (InwxError, OSError, KeyError, ValueError) as e:
sys.exit(
f"INWX: {type(e).__name__}: {e}\nNothing was changed in the config. The INWX "
"account is usually restricted to the server's IP, so run this there, "
"or use --no-dns."
)
try:
write_config(path, new_text)
except OSError as e:
sys.exit(f"{path}: {e}")
print(f"{'Added' if created else 'Replaced the token of'} {host} in {path}")
print("The server reads the config on every request, no restart needed.")
print(f"Token (shown only once): {token}")
+57 -4
View File
@@ -13,6 +13,7 @@ import http.client
import io
import json
import os
import secrets
import socket
import tempfile
import threading
@@ -229,6 +230,13 @@ class FakeInwxHandler(BaseHTTPRequestHandler):
if r["name"] == p["name"] and r["type"] == p["type"]
]
}
elif method == "nameserver.createRecord":
srv.records.append(
{
"id": 100 + len(srv.records),
**{k: p[k] for k in ("name", "type", "content", "ttl")},
}
)
elif method == "nameserver.updateRecord":
for r in srv.records:
if r["id"] == p["id"]:
@@ -283,6 +291,27 @@ class InwxClientTest(unittest.TestCase):
sd.inwx_update(self.cfg(srv), "example.com", HOST, "A", "1.2.3.4")
self.assertEqual(srv.calls[-1], "account.logout")
def test_ensure_record_creates_missing_record_once(self):
srv = self.start()
created, record = sd.ensure_record(self.cfg(srv), "example.com", HOST, "AAAA")
self.assertEqual(
(created, record), (True, {"content": sd.PLACEHOLDER["AAAA"], "ttl": 300})
)
self.assertEqual(srv.records[-1]["ttl"], 300)
self.assertEqual(
sd.ensure_record(self.cfg(srv), "example.com", HOST, "AAAA")[0], False
)
self.assertEqual(srv.calls.count("nameserver.createRecord"), 1)
def test_ensure_record_keeps_existing_record(self):
srv = self.start()
created, record = sd.ensure_record(
self.cfg(srv), "example.com", HOST, "A", ttl=60
)
self.assertFalse(created)
self.assertEqual(record["content"], "10.0.0.1")
self.assertNotIn("nameserver.createRecord", srv.calls)
def test_missing_record(self):
srv = self.start()
with self.assertRaises(sd.NoHost):
@@ -460,16 +489,21 @@ token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}"
"set INWX_OTE_USER, INWX_OTE_PASS, INWX_OTE_HOST to run against the INWX OT&E system",
)
class OteSmokeTest(unittest.TestCase):
def test_lookup_by_name_and_update(self):
host = os.environ["INWX_OTE_HOST"].lower()
zone = os.environ.get("INWX_OTE_ZONE") or ".".join(host.split(".")[-2:])
cfg = {
def setUp(self):
self.host = os.environ["INWX_OTE_HOST"].lower()
self.zone = os.environ.get("INWX_OTE_ZONE") or ".".join(
self.host.split(".")[-2:]
)
self.cfg = {
"inwx": {
"user": os.environ["INWX_OTE_USER"],
"pass": os.environ["INWX_OTE_PASS"],
"api": "https://api.ote.domrobot.com/jsonrpc/",
}
}
def test_lookup_by_name_and_update(self):
cfg, zone, host = self.cfg, self.zone, self.host
with sd.inwx_session(cfg) as call:
original = sd.find_record(call, zone, host, "A")["content"]
test_ip = "192.0.2.1" if original != "192.0.2.1" else "192.0.2.2"
@@ -482,6 +516,25 @@ class OteSmokeTest(unittest.TestCase):
finally:
sd.inwx_update(cfg, zone, host, "A", original)
def test_ensure_record_creates_once_and_is_cleaned_up(self):
cfg, zone = self.cfg, self.zone
name = f"snap-test-{secrets.token_hex(3)}.{zone}"
try:
self.assertTrue(sd.ensure_record(cfg, zone, name, "A")[0])
with sd.inwx_session(cfg) as call:
record = sd.find_record(call, zone, name, "A")
self.assertEqual(
(record["content"], int(record["ttl"])), (sd.PLACEHOLDER["A"], 300)
)
self.assertFalse(sd.ensure_record(cfg, zone, name, "A")[0])
finally:
with (
sd.inwx_session(cfg) as call,
contextlib.suppress(sd.NoHost),
):
record = sd.find_record(call, zone, name, "A")
call("nameserver.deleteRecord", {"id": record["id"]})
if __name__ == "__main__":
unittest.main()
+55
View File
@@ -80,6 +80,14 @@ class MainTest(unittest.TestCase):
with open(self.path, "w") as f:
f.write(CONFIG)
os.chmod(self.path, 0o600)
# Never talk to the real INWX from tests
patcher = mock.patch.object(
sh,
"ensure_record",
return_value=(True, {"content": "192.0.2.1", "ttl": 300}),
)
self.ensure = patcher.start()
self.addCleanup(patcher.stop)
def run_main(self, *args):
out = io.StringIO()
@@ -126,6 +134,53 @@ class MainTest(unittest.TestCase):
with open(self.path, "rb") as f:
return tomllib.load(f)["hosts"][host]["token_sha256"]
def test_creates_missing_record_with_default_ttl(self):
output = self.run_main("fresh.example.com")
args = self.ensure.call_args.args
self.assertEqual(args[1:], ("example.com", "fresh.example.com", "A", 300))
self.assertIn("DNS: created A record fresh.example.com", output)
def test_types_ttl_and_zone_are_passed_on(self):
self.run_main(
"fresh.example.co.uk", "-z", "example.co.uk", "-t", "a,aaaa", "--ttl", "60"
)
calls = [c.args[1:] for c in self.ensure.call_args_list]
self.assertEqual(
calls,
[
("example.co.uk", "fresh.example.co.uk", "A", 60),
("example.co.uk", "fresh.example.co.uk", "AAAA", 60),
],
)
def test_existing_record_is_reported_not_changed(self):
self.ensure.return_value = (False, {"content": "1.2.3.4", "ttl": 3600})
output = self.run_main("fresh.example.com")
self.assertIn("A record fresh.example.com exists (1.2.3.4, TTL 3600)", output)
def test_zone_of_existing_host_comes_from_config(self):
self.run_main("b.example.com", "--yes")
self.assertEqual(self.ensure.call_args.args[1], "example.com")
def test_no_dns_skips_inwx(self):
self.run_main("fresh.example.com", "--no-dns")
self.ensure.assert_not_called()
def test_inwx_failure_changes_nothing(self):
self.ensure.side_effect = sh.InwxError(
"account.login: 2200 Authentication error"
)
with self.assertRaises(SystemExit) as ctx:
self.run_main("fresh.example.com")
self.assertIn("Nothing was changed", str(ctx.exception))
with open(self.path) as f:
self.assertEqual(f.read(), CONFIG)
def test_invalid_record_type(self):
with self.assertRaises(SystemExit):
self.run_main("fresh.example.com", "-t", "MX")
self.ensure.assert_not_called()
def test_invalid_hostname_leaves_config_untouched(self):
for bad in ('x"] \n[evil', "no_dots", "a..b", "-a.example.com"):
with self.assertRaises(SystemExit):