Files
snap-dyndns-server/test_snap_dyndns.py
T

340 lines
13 KiB
Python
Raw Normal View History

2026-10-22 12:22:14 +02:00
# 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 hashlib
import http.client
2026-10-22 12:22:14 +02:00
import io
import json
import os
import socket
2026-10-22 12:22:14 +02:00
import tempfile
import threading
import unittest
from unittest import mock
2026-10-22 12:22:14 +02:00
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
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.fail = None
def update(self, cfg, zone, name, rtype, ip):
self.calls.append((zone, name, rtype, ip))
if self.fail:
raise self.fail
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="2001:db8::1"), (200, "good 2001:db8::1"))
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_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.fail = 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.assertEqual(self.run_handle(), (502, "911"))
self.fail = 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))
2026-10-22 12:22:14 +02:00
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.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, *args):
pass
def do_POST(self):
srv = 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 (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.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_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):
with 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))
2026-10-22 12:22:14 +02:00
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 MainTest(unittest.TestCase):
def run_main(self, env, cfg_text):
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "config.toml")
with open(path, "w") as f:
f.write(cfg_text.replace("STATE", os.path.join(tmp, "state.json")))
out = io.StringIO()
sd.main({**env, "SNAP_DYNDNS_CONFIG": path}, out)
return out.getvalue()
CFG = f"""
state_file = "STATE"
[inwx]
user = "u"
pass = "p"
api = "http://127.0.0.1:1/"
[hosts."{HOST}"]
token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}"
"""
def test_unauthorized_has_challenge(self):
out = self.run_main(make_env(auth=basic(HOST, "bad")), self.CFG)
head, _, body = out.partition("\n\n")
self.assertTrue(head.startswith("Status: 401 Unauthorized"))
self.assertIn('WWW-Authenticate: Basic realm="Snap DynDNS"', head)
self.assertEqual(body, "badauth\n")
def test_unreachable_inwx_is_911(self):
out = self.run_main(make_env(), self.CFG)
self.assertTrue(out.startswith("Status: 502 Bad Gateway\n"))
self.assertTrue(out.endswith("\n\n911\n"))
def test_broken_config_is_500(self):
out = self.run_main(make_env(), "not = [valid")
self.assertTrue(out.startswith("Status: 500 Internal Server Error\n"))
@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 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 = {
"inwx": {
"user": os.environ["INWX_OTE_USER"],
"pass": os.environ["INWX_OTE_PASS"],
"api": "https://api.ote.domrobot.com/jsonrpc/",
}
}
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)
if __name__ == "__main__":
unittest.main()