chore: improve logging and type fixes

This commit is contained in:
mxmehl committed 2026-10-22 14:09:43 +02:00
1 parent 8bc1cfaf27
commit c43f0dd699
2 files changed
+106 -34

No files matched your search

+25 -6
View File
@@ -27,6 +27,7 @@ import time
import tomllib
import urllib.parse
import urllib.request
from typing import cast
API_LIVE = "https://api.domrobot.com/jsonrpc/"
DEFAULT_CONFIG = "~/etc/snap-dyndns/config.toml"
@@ -191,7 +192,10 @@ def handle(env, cfg, update=inwx_update):
return 400, "badip"
# Guards against publishing the proxy's address if client_ip_header is wrong
if not given and not ip.is_global:
print(f"snap-dyndns: {host}: connection address {ip} is not global, check client_ip_header", file=sys.stderr)
print(
f"snap-dyndns: {host}: connection address {ip} is not global, check client_ip_header",
file=sys.stderr,
)
return 400, "badip"
# 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)
@@ -218,6 +222,8 @@ def handle(env, cfg, update=inwx_update):
print(f"snap-dyndns: {host}: {e}", file=sys.stderr)
return 502, "911"
# shortcut: cache goes stale if the record is edited by hand at INWX, delete state.json to resync
old_ip = state.get(host, {}).get(rtype, "unknown")
print(f"snap-dyndns: {host}: {rtype} {old_ip} -> {ip}", file=sys.stderr)
state.setdefault(host, {})[rtype] = ip
_save_state(state_path, state)
lines.append(f"good {ip}")
@@ -239,6 +245,10 @@ INDEX_HTML = """<!DOCTYPE html>
"""
class Server(http.server.ThreadingHTTPServer):
config_path: str
class RequestHandler(http.server.BaseHTTPRequestHandler):
timeout = 30 # do not let stalled connections hold a thread forever
@@ -250,7 +260,7 @@ class RequestHandler(http.server.BaseHTTPRequestHandler):
return self._reply(404, "not found")
try:
# Read per request, so devices can be added without restarting
with open(self.server.config_path, "rb") as f:
with open(cast(Server, self.server).config_path, "rb") as f:
cfg = tomllib.load(f)
env = {
"QUERY_STRING": url.query,
@@ -283,15 +293,24 @@ class RequestHandler(http.server.BaseHTTPRequestHandler):
def make_server(config_path, port, host="0.0.0.0"):
server = http.server.ThreadingHTTPServer((host, port), RequestHandler)
server = Server((host, port), RequestHandler)
server.config_path = config_path
return server
def main(argv=None):
parser = argparse.ArgumentParser(description="Snap DynDNS Server (serves /nic/update)")
parser.add_argument("-c", "--config", default=DEFAULT_CONFIG, help=f"config file (default: {DEFAULT_CONFIG})")
parser.add_argument("-p", "--port", type=int, default=8080, help="port to listen on (default: 8080)")
parser = argparse.ArgumentParser(
description="Snap DynDNS Server (serves /nic/update)"
)
parser.add_argument(
"-c",
"--config",
default=DEFAULT_CONFIG,
help=f"config file (default: {DEFAULT_CONFIG})",
)
parser.add_argument(
"-p", "--port", type=int, default=8080, help="port to listen on (default: 8080)"
)
args = parser.parse_args(argv)
path = os.path.expanduser(args.config)
try: # fail fast on a broken config; it is re-read on every request later
+81 -28
View File
@@ -15,8 +15,9 @@ import socket
import tempfile
import threading
import unittest
from unittest import mock
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import cast
from unittest import mock
import snap_dyndns as sd
@@ -56,12 +57,12 @@ class HandleTest(unittest.TestCase):
self.addCleanup(tmp.cleanup)
self.cfg = make_cfg(tmp.name)
self.calls = []
self.fail = None
self.error = None
def update(self, cfg, zone, name, rtype, ip):
self.calls.append((zone, name, rtype, ip))
if self.fail:
raise self.fail
if self.error:
raise self.error
return True
def run_handle(self, **kw):
@@ -78,7 +79,10 @@ class HandleTest(unittest.TestCase):
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.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):
@@ -86,7 +90,9 @@ class HandleTest(unittest.TestCase):
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")
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"])
@@ -99,7 +105,12 @@ class HandleTest(unittest.TestCase):
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"):
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, [])
@@ -109,7 +120,9 @@ class HandleTest(unittest.TestCase):
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"))
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", ""):
@@ -117,20 +130,27 @@ class HandleTest(unittest.TestCase):
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)
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.run_handle(query=f"hostname={HOST}&myip=1.2.3.4;rm"), (400, "badip")
)
self.assertEqual(self.calls, [])
def test_missing_record(self):
self.fail = sd.NoHost("gone")
self.error = sd.NoHost("gone")
self.assertEqual(self.run_handle(), (404, "nohost"))
def test_inwx_failure_keeps_state_and_retries(self):
self.fail = sd.InwxError("boom")
self.error = sd.InwxError("boom")
self.assertEqual(self.run_handle(), (502, "911"))
self.fail = None
self.error = None
self.assertEqual(self.run_handle(), (200, "good 1.2.3.4"))
self.assertEqual(len(self.calls), 2)
@@ -150,7 +170,9 @@ class Ipv4BindTest(unittest.TestCase):
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))
socket.create_connection(
("localhost", port), timeout=2, source_address=("0.0.0.0", 0)
)
class FakeInwx(ThreadingHTTPServer):
@@ -170,11 +192,11 @@ class FakeInwx(ThreadingHTTPServer):
class FakeInwxHandler(BaseHTTPRequestHandler):
def log_message(self, *args):
def log_message(self, format: str, *args: object) -> None:
pass
def do_POST(self):
srv = self.server
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)
@@ -188,13 +210,22 @@ class FakeInwxHandler(BaseHTTPRequestHandler):
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)}
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"]]}
res = {
"record": [
r
for r in srv.records
if r["name"] == p["name"] and r["type"] == p["type"]
]
}
elif method == "nameserver.updateRecord":
for r in srv.records:
if r["id"] == p["id"]:
@@ -220,20 +251,26 @@ class InwxClientTest(unittest.TestCase):
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.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.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")
sd.inwx_update(
self.cfg(srv, totp_secret=secret), "example.com", HOST, "A", "1.2.3.4"
)
)
self.assertIn("account.unlock", srv.calls)
@@ -265,9 +302,11 @@ class InwxClientTest(unittest.TestCase):
raise OSError("stop here")
cfg = {"inwx": {"user": "u", "pass": "p", "api": "https://inwx.invalid/"}}
with mock.patch("http.client.HTTPSConnection", FakeConnection):
with self.assertRaises(OSError):
sd.inwx_update(cfg, "example.com", HOST, "A", "1.2.3.4")
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):
@@ -301,7 +340,13 @@ 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):
for cleanup in (
tmp.cleanup,
inwx.server_close,
inwx.shutdown,
server.server_close,
server.shutdown,
):
self.addCleanup(cleanup)
self.inwx = inwx
return server
@@ -311,7 +356,11 @@ token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}"
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()
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")
@@ -332,7 +381,9 @@ token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}"
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"))
self.assertEqual(
(status, challenge, body), (401, 'Basic realm="Snap DynDNS"', "badauth\n")
)
def test_start_page_without_credentials(self):
server = self.start()
@@ -384,7 +435,9 @@ class OteSmokeTest(unittest.TestCase):
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)
self.assertEqual(
sd.find_record(call, zone, host, "A")["content"], test_ip
)
finally:
sd.inwx_update(cfg, zone, host, "A", original)