feat!: complete refactoring of server (#1)

* make a python server
* improve authentication by token/hash
* better logging
* add helper tool for new hosts

Reviewed-on: #1
Co-authored-by: Max Mehl <mail@mehl.mx>
This commit was merged in pull request #1.
This commit is contained in:
mxmehl authored and mxmehl committed 2026-10-22 15:35:54 +02:00
1 parent a1c55f4574
commit 0cd8438ab3
15 files changed
+1485 -327

No files matched your search

+564
View File
@@ -0,0 +1,564 @@
# SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx>
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Run with: uv run --python 3.14 python -m unittest -v
The OT&E smoke test is skipped unless INWX_OTE_USER, INWX_OTE_PASS and
INWX_OTE_HOST (an existing A record there) are set in the environment.
"""
import base64
import contextlib
import hashlib
import http.client
import io
import json
import os
import secrets
import socket
import tempfile
import threading
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import cast
from unittest import mock
import snap_dyndns as sd
TOKEN = "s3cret"
HOST = "home.example.com"
def basic(user, token):
return "Basic " + base64.b64encode(f"{user}:{token}".encode()).decode()
def make_cfg(tmp, **inwx):
return {
"state_file": os.path.join(tmp, "state.json"),
"inwx": {"user": "u", "pass": "p", **inwx},
"hosts": {HOST: {"token_sha256": hashlib.sha256(TOKEN.encode()).hexdigest()}},
}
def make_env(query=f"hostname={HOST}", remote="1.2.3.4", auth=None):
return {
"QUERY_STRING": query,
"REMOTE_ADDR": remote,
"HTTP_AUTHORIZATION": auth or basic(HOST, TOKEN),
}
class TotpTest(unittest.TestCase):
def test_rfc6238_vector(self):
secret = base64.b32encode(b"12345678901234567890").decode()
self.assertEqual(sd.totp(secret, now=59), "287082")
class HandleTest(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.cfg = make_cfg(tmp.name)
self.calls = []
self.error = None
def update(self, cfg, zone, name, rtype, ip):
self.calls.append((zone, name, rtype, ip))
if self.error:
raise self.error
return True
def run_handle(self, **kw):
return sd.handle(make_env(**kw), self.cfg, self.update)
def test_first_update_then_nochg(self):
self.assertEqual(self.run_handle(), (200, "good 1.2.3.4"))
self.assertEqual(self.run_handle(), (200, "nochg 1.2.3.4"))
self.assertEqual(self.calls, [("example.com", HOST, "A", "1.2.3.4")])
def test_ip_change_updates_again(self):
self.run_handle()
self.assertEqual(self.run_handle(remote="5.6.7.8"), (200, "good 5.6.7.8"))
self.assertEqual(len(self.calls), 2)
def test_ipv6_connection_updates_aaaa(self):
self.assertEqual(
self.run_handle(remote="2606:4700:4700::1111"),
(200, "good 2606:4700:4700::1111"),
)
self.assertEqual(self.calls[0][2], "AAAA")
def test_myip_overrides_remote_addr(self):
self.run_handle(query=f"hostname={HOST}&myip=9.9.9.9")
self.assertEqual(self.calls[0][3], "9.9.9.9")
def test_dual_stack(self):
status, body = self.run_handle(
query=f"hostname={HOST}&myip=9.9.9.9&myipv6=2001:db8::2"
)
self.assertEqual((status, body), (200, "good 9.9.9.9\ngood 2001:db8::2"))
self.assertEqual([c[2] for c in self.calls], ["A", "AAAA"])
def test_hostname_param_optional(self):
self.assertEqual(self.run_handle(query="")[0], 200)
def test_zone_override(self):
self.cfg["hosts"][HOST]["zone"] = "example.co.uk"
self.run_handle()
self.assertEqual(self.calls[0][0], "example.co.uk")
def test_bad_credentials(self):
for auth in (
basic(HOST, "wrong"),
basic("other.example.com", TOKEN),
"Basic !!!",
"Bearer x",
):
self.assertEqual(self.run_handle(auth=auth), (401, "badauth"), auth)
self.assertEqual(self.calls, [])
def test_missing_auth(self):
env = make_env()
del env["HTTP_AUTHORIZATION"]
self.assertEqual(sd.handle(env, self.cfg, self.update), (401, "badauth"))
def test_hostname_mismatch(self):
self.assertEqual(
self.run_handle(query="hostname=other.example.com"), (404, "nohost")
)
def test_non_global_connection_address_is_rejected(self):
for remote in ("127.0.0.1", "10.0.0.5", "::1", ""):
self.assertEqual(self.run_handle(remote=remote), (400, "badip"), remote)
self.assertEqual(self.calls, [])
def test_explicit_ip_may_be_private(self):
self.assertEqual(
self.run_handle(
query=f"hostname={HOST}&myip=192.168.1.5", remote="127.0.0.1"
)[0],
200,
)
def test_invalid_ip(self):
self.assertEqual(
self.run_handle(query=f"hostname={HOST}&myip=1.2.3.4;rm"), (400, "badip")
)
self.assertEqual(self.calls, [])
def test_missing_record(self):
self.error = sd.NoHost("gone")
self.assertEqual(self.run_handle(), (404, "nohost"))
def test_inwx_failure_keeps_state_and_retries(self):
self.error = sd.InwxError("boom")
self.assertEqual(self.run_handle(), (502, "911"))
self.error = None
self.assertEqual(self.run_handle(), (200, "good 1.2.3.4"))
self.assertEqual(len(self.calls), 2)
class Ipv4BindTest(unittest.TestCase):
"""Checks the premise of _IPv4Https: binding to 0.0.0.0 skips IPv6 addresses."""
def test_source_address_skips_ipv6(self):
try:
server = socket.create_server(("::1", 0), family=socket.AF_INET6)
except OSError:
self.skipTest("no IPv6 loopback")
self.addCleanup(server.close)
port = server.getsockname()[1]
try:
socket.create_connection(("localhost", port), timeout=2).close()
except OSError:
self.skipTest("localhost does not resolve to ::1")
with self.assertRaises(OSError):
socket.create_connection(
("localhost", port), timeout=2, source_address=("0.0.0.0", 0)
)
class FakeInwx(ThreadingHTTPServer):
"""Minimal INWX JSON-RPC stand-in with cookie session and optional 2FA."""
def __init__(self, tfa_secret=None):
super().__init__(("127.0.0.1", 0), FakeInwxHandler)
self.tfa_secret = tfa_secret
self.wrong_login = False
self.unlocked = False
self.calls = []
self.records = [
{"id": 1, "name": HOST, "type": "A", "content": "10.0.0.1"},
{"id": 2, "name": "other.example.com", "type": "A", "content": "10.0.0.2"},
]
self.url = f"http://127.0.0.1:{self.server_port}/jsonrpc/"
threading.Thread(target=self.serve_forever, daemon=True).start()
class FakeInwxHandler(BaseHTTPRequestHandler):
def log_message(self, format: str, *args: object) -> None:
pass
def do_POST(self):
srv = cast(FakeInwx, self.server)
req = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
method, p = req["method"], req["params"]
srv.calls.append(method)
cookie, code, res = None, 1000, {}
if method == "account.login":
if srv.wrong_login or (p["user"], p["pass"]) != ("u", "p"):
code = 2200
cookie = "sid=abc; Path=/"
srv.unlocked = srv.tfa_secret is None
res = {"tfa": "GOOGLE-AUTH" if srv.tfa_secret else "0"}
elif "sid=abc" not in self.headers.get("Cookie", ""):
code = 2002
elif method == "account.unlock":
valid = {
sd.totp(srv.tfa_secret, now=__import__("time").time() + d)
for d in (-30, 0, 30)
}
srv.unlocked = p["tan"] in valid
code = 1000 if srv.unlocked else 2200
elif not srv.unlocked:
code = 2200
elif method == "nameserver.info":
res = {
"record": [
r
for r in srv.records
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"]:
r["content"] = p["content"]
body = json.dumps({"code": code, "msg": "x", "resData": res}).encode()
self.send_response(200)
if cookie:
self.send_header("Set-Cookie", cookie)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
class InwxClientTest(unittest.TestCase):
def start(self, **kw):
srv = FakeInwx(**kw)
self.addCleanup(srv.server_close)
self.addCleanup(srv.shutdown)
return srv
def cfg(self, srv, **inwx):
return {"inwx": {"user": "u", "pass": "p", "api": srv.url, **inwx}}
def test_update_changes_record(self):
srv = self.start()
self.assertTrue(
sd.inwx_update(self.cfg(srv), "example.com", HOST, "A", "1.2.3.4")
)
self.assertEqual(srv.records[0]["content"], "1.2.3.4")
self.assertEqual(srv.calls[-1], "account.logout")
def test_same_content_skips_update(self):
srv = self.start()
self.assertFalse(
sd.inwx_update(self.cfg(srv), "example.com", HOST, "A", "10.0.0.1")
)
self.assertNotIn("nameserver.updateRecord", srv.calls)
def test_two_factor(self):
secret = base64.b32encode(b"12345678901234567890").decode()
srv = self.start(tfa_secret=secret)
self.assertTrue(
sd.inwx_update(
self.cfg(srv, totp_secret=secret), "example.com", HOST, "A", "1.2.3.4"
)
)
self.assertIn("account.unlock", srv.calls)
def test_two_factor_without_secret(self):
srv = self.start(tfa_secret="GEZDGNBVGY3TQOJQ")
with self.assertRaises(sd.InwxError):
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):
sd.inwx_update(self.cfg(srv), "example.com", HOST, "AAAA", "2001:db8::1")
def test_api_error_hides_password(self):
srv = self.start()
cfg = self.cfg(srv)
cfg["inwx"]["pass"] = "wrong-password"
with self.assertRaises(sd.InwxError) as ctx:
sd.inwx_update(cfg, "example.com", HOST, "A", "1.2.3.4")
self.assertNotIn("wrong-password", str(ctx.exception))
def test_https_connection_is_ipv4_only(self):
seen = {}
class FakeConnection(http.client.HTTPSConnection):
def __init__(self, *args, **kwargs):
seen.update(kwargs)
raise OSError("stop here")
cfg = {"inwx": {"user": "u", "pass": "p", "api": "https://inwx.invalid/"}}
with (
mock.patch("http.client.HTTPSConnection", FakeConnection),
self.assertRaises(OSError),
):
sd.inwx_update(cfg, "example.com", HOST, "A", "1.2.3.4")
self.assertEqual(seen["source_address"], ("0.0.0.0", 0))
def test_end_to_end_only_changes_reach_inwx(self):
srv = self.start()
with tempfile.TemporaryDirectory() as tmp:
cfg = make_cfg(tmp, api=srv.url)
for _ in range(3):
sd.handle(make_env(), cfg)
self.assertEqual(srv.calls.count("nameserver.updateRecord"), 1)
self.assertEqual(srv.calls.count("account.login"), 1)
class ServerTest(unittest.TestCase):
"""Real HTTP requests against make_server() with a fake INWX behind it."""
def start(self, **config):
inwx = FakeInwx()
tmp = tempfile.TemporaryDirectory()
path = os.path.join(tmp.name, "config.toml")
with open(path, "w") as f:
f.write(
f'''state_file = "{tmp.name}/state.json"
{"".join(f'{k} = "{v}"' + chr(10) for k, v in config.items())}
[inwx]
user = "u"
pass = "p"
api = "{inwx.url}"
[hosts."{HOST}"]
token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}"
'''
)
server = sd.make_server(path, 0, "127.0.0.1")
threading.Thread(target=server.serve_forever, daemon=True).start()
for cleanup in (
tmp.cleanup,
inwx.server_close,
inwx.shutdown,
server.server_close,
server.shutdown,
):
self.addCleanup(cleanup)
self.inwx = inwx
return server
def get(self, server, path="/nic/update?hostname=" + HOST, **headers):
headers.setdefault("Authorization", basic(HOST, TOKEN))
conn = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=5)
conn.request("GET", path, headers=headers)
response = conn.getresponse()
return (
response.status,
response.getheader("WWW-Authenticate"),
response.read().decode(),
)
def test_update_via_forwarded_header_then_nochg(self):
server = self.start(client_ip_header="X-Forwarded-For")
# Only the last entry (added by our proxy) counts, earlier ones are client-controlled
headers = {"X-Forwarded-For": "6.6.6.6, 1.2.3.4"}
self.assertEqual(self.get(server, **headers), (200, None, "good 1.2.3.4\n"))
self.assertEqual(self.get(server, **headers), (200, None, "nochg 1.2.3.4\n"))
self.assertEqual(self.inwx.calls.count("nameserver.updateRecord"), 1)
def test_loopback_peer_without_header_is_rejected(self):
server = self.start()
self.assertEqual(self.get(server), (400, None, "badip\n"))
def test_missing_configured_header_is_rejected(self):
server = self.start(client_ip_header="X-Forwarded-For")
self.assertEqual(self.get(server), (400, None, "badip\n"))
def test_unauthorized_has_challenge(self):
server = self.start()
status, challenge, body = self.get(server, Authorization=basic(HOST, "bad"))
self.assertEqual(
(status, challenge, body), (401, 'Basic realm="Snap DynDNS"', "badauth\n")
)
def test_start_page_without_credentials(self):
server = self.start()
for path in ("/", "/nic", "/nic/"):
status, challenge, body = self.get(server, path, Authorization="")
self.assertEqual((status, challenge), (200, None), path)
self.assertIn("<h1>Snap DynDNS Server</h1>", body)
def logged(self, server, *args, **kw):
"""Run get() and return (response, text written to stderr)."""
err = io.StringIO()
with contextlib.redirect_stderr(err):
response = self.get(server, *args, **kw)
return response, err.getvalue()
def test_log_names_the_reason(self):
server = self.start(client_ip_header="X-Forwarded-For")
xff = {"X-Forwarded-For": "1.2.3.4"}
_, log = self.logged(server, Authorization=basic(HOST, "bad"), **xff)
self.assertRegex(
log,
rf"^\[\d{{4}}-\d\d-\d\d \d\d:\d\d:\d\d\] 1\.2\.3\.4: 401 - {HOST}: badauth: wrong token\n$",
)
_, log = self.logged(server, Authorization=basic("who.example.com", "x"), **xff)
self.assertIn("1.2.3.4: 401 - badauth: unknown host 'who.example.com'", log)
_, log = self.logged(server, "/nic/update?hostname=other.example.com", **xff)
self.assertIn(
"1.2.3.4: 404 - home.example.com: nohost: hostname parameter 'other.example.com'",
log,
)
_, log = self.logged(server, **xff)
self.assertIn("1.2.3.4: 200 - home.example.com: good A unknown -> 1.2.3.4", log)
def test_log_names_the_missing_record(self):
server = self.start(client_ip_header="X-Forwarded-For")
# Only an A record exists, the device also reports IPv6
response, log = self.logged(
server, **{"X-Forwarded-For": "2606:4700:4700::1111"}
)
self.assertEqual(response[0], 404)
self.assertIn(
"2606:4700:4700::1111: 404 - home.example.com: nohost: "
"no AAAA record home.example.com in zone example.com, create it at INWX first",
log,
)
def test_log_reports_both_results_of_a_combined_request(self):
server = self.start()
query = f"/nic/update?hostname={HOST}&myip=1.2.3.4&myipv6=2606:4700:4700::1111"
_, log = self.logged(server, query)
self.assertIn("good A unknown -> 1.2.3.4; ", log)
self.assertIn("nohost: no AAAA record", log)
def test_nochg_is_not_logged(self):
server = self.start(client_ip_header="X-Forwarded-For")
xff = {"X-Forwarded-For": "1.2.3.4"}
self.get(server, **xff)
response, log = self.logged(server, **xff)
self.assertEqual(response[2], "nochg 1.2.3.4\n")
self.assertEqual(log, "")
def test_log_names_the_inwx_failure(self):
server = self.start(client_ip_header="X-Forwarded-For")
self.inwx.wrong_login = True
_, log = self.logged(server, **{"X-Forwarded-For": "1.2.3.4"})
self.assertIn(
"1.2.3.4: 502 - home.example.com: 911: A update to 1.2.3.4 failed: account.login: 2200",
log,
)
def test_other_paths_are_not_found(self):
server = self.start()
self.assertEqual(self.get(server, "/elsewhere")[0], 404)
def test_unreachable_inwx_is_911(self):
server = self.start(client_ip_header="X-Forwarded-For")
self.inwx.shutdown()
self.inwx.server_close()
status, _, body = self.get(server, **{"X-Forwarded-For": "1.2.3.4"})
self.assertEqual((status, body), (502, "911\n"))
def test_broken_config_is_500(self):
server = self.start()
with open(server.config_path, "w") as f:
f.write("not = [valid")
self.assertEqual(self.get(server), (500, None, "911\n"))
def test_main_refuses_unreadable_config(self):
with self.assertRaises(SystemExit):
sd.main(["--config", "/nonexistent/config.toml"])
@unittest.skipUnless(
all(os.environ.get(k) for k in ("INWX_OTE_USER", "INWX_OTE_PASS", "INWX_OTE_HOST")),
"set INWX_OTE_USER, INWX_OTE_PASS, INWX_OTE_HOST to run against the INWX OT&E system",
)
class OteSmokeTest(unittest.TestCase):
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"
try:
self.assertTrue(sd.inwx_update(cfg, zone, host, "A", test_ip))
with sd.inwx_session(cfg) as call:
self.assertEqual(
sd.find_record(call, zone, host, "A")["content"], test_ip
)
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()