387 lines
15 KiB
Python
387 lines
15 KiB
Python
# 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
|
|
import json
|
|
import os
|
|
import socket
|
|
import tempfile
|
|
import threading
|
|
import unittest
|
|
from unittest import mock
|
|
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="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.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))
|
|
|
|
|
|
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))
|
|
|
|
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_other_paths_are_not_found(self):
|
|
server = self.start()
|
|
self.assertEqual(self.get(server, "/")[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 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()
|