feat!: complete refactoring of server #1
No files matched your search
+25
-6
@@ -27,6 +27,7 @@ import time
|
|||||||
import tomllib
|
import tomllib
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
import urllib.request
|
import urllib.request
|
||||||
|
from typing import cast
|
||||||
|
|
||||||
API_LIVE = "https://api.domrobot.com/jsonrpc/"
|
API_LIVE = "https://api.domrobot.com/jsonrpc/"
|
||||||
DEFAULT_CONFIG = "~/etc/snap-dyndns/config.toml"
|
DEFAULT_CONFIG = "~/etc/snap-dyndns/config.toml"
|
||||||
@@ -191,7 +192,10 @@ def handle(env, cfg, update=inwx_update):
|
|||||||
return 400, "badip"
|
return 400, "badip"
|
||||||
# Guards against publishing the proxy's address if client_ip_header is wrong
|
# Guards against publishing the proxy's address if client_ip_header is wrong
|
||||||
if not given and not ip.is_global:
|
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"
|
return 400, "badip"
|
||||||
# shortcut: explicit myip/myipv6 are only syntax-checked (private ranges accepted), tighten if clients misbehave
|
# 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)
|
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)
|
print(f"snap-dyndns: {host}: {e}", file=sys.stderr)
|
||||||
return 502, "911"
|
return 502, "911"
|
||||||
# shortcut: cache goes stale if the record is edited by hand at INWX, delete state.json to resync
|
# 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
|
state.setdefault(host, {})[rtype] = ip
|
||||||
_save_state(state_path, state)
|
_save_state(state_path, state)
|
||||||
lines.append(f"good {ip}")
|
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):
|
class RequestHandler(http.server.BaseHTTPRequestHandler):
|
||||||
timeout = 30 # do not let stalled connections hold a thread forever
|
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")
|
return self._reply(404, "not found")
|
||||||
try:
|
try:
|
||||||
# Read per request, so devices can be added without restarting
|
# 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)
|
cfg = tomllib.load(f)
|
||||||
env = {
|
env = {
|
||||||
"QUERY_STRING": url.query,
|
"QUERY_STRING": url.query,
|
||||||
@@ -283,15 +293,24 @@ class RequestHandler(http.server.BaseHTTPRequestHandler):
|
|||||||
|
|
||||||
|
|
||||||
def make_server(config_path, port, host="0.0.0.0"):
|
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
|
server.config_path = config_path
|
||||||
return server
|
return server
|
||||||
|
|
||||||
|
|
||||||
def main(argv=None):
|
def main(argv=None):
|
||||||
parser = argparse.ArgumentParser(description="Snap DynDNS Server (serves /nic/update)")
|
parser = argparse.ArgumentParser(
|
||||||
parser.add_argument("-c", "--config", default=DEFAULT_CONFIG, help=f"config file (default: {DEFAULT_CONFIG})")
|
description="Snap DynDNS Server (serves /nic/update)"
|
||||||
parser.add_argument("-p", "--port", type=int, default=8080, help="port to listen on (default: 8080)")
|
)
|
||||||
|
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)
|
args = parser.parse_args(argv)
|
||||||
path = os.path.expanduser(args.config)
|
path = os.path.expanduser(args.config)
|
||||||
try: # fail fast on a broken config; it is re-read on every request later
|
try: # fail fast on a broken config; it is re-read on every request later
|
||||||
|
|||||||
+80
-27
@@ -15,8 +15,9 @@ import socket
|
|||||||
import tempfile
|
import tempfile
|
||||||
import threading
|
import threading
|
||||||
import unittest
|
import unittest
|
||||||
from unittest import mock
|
|
||||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
from typing import cast
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
import snap_dyndns as sd
|
import snap_dyndns as sd
|
||||||
|
|
||||||
@@ -56,12 +57,12 @@ class HandleTest(unittest.TestCase):
|
|||||||
self.addCleanup(tmp.cleanup)
|
self.addCleanup(tmp.cleanup)
|
||||||
self.cfg = make_cfg(tmp.name)
|
self.cfg = make_cfg(tmp.name)
|
||||||
self.calls = []
|
self.calls = []
|
||||||
self.fail = None
|
self.error = None
|
||||||
|
|
||||||
def update(self, cfg, zone, name, rtype, ip):
|
def update(self, cfg, zone, name, rtype, ip):
|
||||||
self.calls.append((zone, name, rtype, ip))
|
self.calls.append((zone, name, rtype, ip))
|
||||||
if self.fail:
|
if self.error:
|
||||||
raise self.fail
|
raise self.error
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def run_handle(self, **kw):
|
def run_handle(self, **kw):
|
||||||
@@ -78,7 +79,10 @@ class HandleTest(unittest.TestCase):
|
|||||||
self.assertEqual(len(self.calls), 2)
|
self.assertEqual(len(self.calls), 2)
|
||||||
|
|
||||||
def test_ipv6_connection_updates_aaaa(self):
|
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")
|
self.assertEqual(self.calls[0][2], "AAAA")
|
||||||
|
|
||||||
def test_myip_overrides_remote_addr(self):
|
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")
|
self.assertEqual(self.calls[0][3], "9.9.9.9")
|
||||||
|
|
||||||
def test_dual_stack(self):
|
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((status, body), (200, "good 9.9.9.9\ngood 2001:db8::2"))
|
||||||
self.assertEqual([c[2] for c in self.calls], ["A", "AAAA"])
|
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")
|
self.assertEqual(self.calls[0][0], "example.co.uk")
|
||||||
|
|
||||||
def test_bad_credentials(self):
|
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.run_handle(auth=auth), (401, "badauth"), auth)
|
||||||
self.assertEqual(self.calls, [])
|
self.assertEqual(self.calls, [])
|
||||||
|
|
||||||
@@ -109,7 +120,9 @@ class HandleTest(unittest.TestCase):
|
|||||||
self.assertEqual(sd.handle(env, self.cfg, self.update), (401, "badauth"))
|
self.assertEqual(sd.handle(env, self.cfg, self.update), (401, "badauth"))
|
||||||
|
|
||||||
def test_hostname_mismatch(self):
|
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):
|
def test_non_global_connection_address_is_rejected(self):
|
||||||
for remote in ("127.0.0.1", "10.0.0.5", "::1", ""):
|
for remote in ("127.0.0.1", "10.0.0.5", "::1", ""):
|
||||||
@@ -117,20 +130,27 @@ class HandleTest(unittest.TestCase):
|
|||||||
self.assertEqual(self.calls, [])
|
self.assertEqual(self.calls, [])
|
||||||
|
|
||||||
def test_explicit_ip_may_be_private(self):
|
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):
|
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, [])
|
self.assertEqual(self.calls, [])
|
||||||
|
|
||||||
def test_missing_record(self):
|
def test_missing_record(self):
|
||||||
self.fail = sd.NoHost("gone")
|
self.error = sd.NoHost("gone")
|
||||||
self.assertEqual(self.run_handle(), (404, "nohost"))
|
self.assertEqual(self.run_handle(), (404, "nohost"))
|
||||||
|
|
||||||
def test_inwx_failure_keeps_state_and_retries(self):
|
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.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(self.run_handle(), (200, "good 1.2.3.4"))
|
||||||
self.assertEqual(len(self.calls), 2)
|
self.assertEqual(len(self.calls), 2)
|
||||||
|
|
||||||
@@ -150,7 +170,9 @@ class Ipv4BindTest(unittest.TestCase):
|
|||||||
except OSError:
|
except OSError:
|
||||||
self.skipTest("localhost does not resolve to ::1")
|
self.skipTest("localhost does not resolve to ::1")
|
||||||
with self.assertRaises(OSError):
|
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):
|
class FakeInwx(ThreadingHTTPServer):
|
||||||
@@ -170,11 +192,11 @@ class FakeInwx(ThreadingHTTPServer):
|
|||||||
|
|
||||||
|
|
||||||
class FakeInwxHandler(BaseHTTPRequestHandler):
|
class FakeInwxHandler(BaseHTTPRequestHandler):
|
||||||
def log_message(self, *args):
|
def log_message(self, format: str, *args: object) -> None:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def do_POST(self):
|
def do_POST(self):
|
||||||
srv = self.server
|
srv = cast(FakeInwx, self.server)
|
||||||
req = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
req = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
||||||
method, p = req["method"], req["params"]
|
method, p = req["method"], req["params"]
|
||||||
srv.calls.append(method)
|
srv.calls.append(method)
|
||||||
@@ -188,13 +210,22 @@ class FakeInwxHandler(BaseHTTPRequestHandler):
|
|||||||
elif "sid=abc" not in self.headers.get("Cookie", ""):
|
elif "sid=abc" not in self.headers.get("Cookie", ""):
|
||||||
code = 2002
|
code = 2002
|
||||||
elif method == "account.unlock":
|
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
|
srv.unlocked = p["tan"] in valid
|
||||||
code = 1000 if srv.unlocked else 2200
|
code = 1000 if srv.unlocked else 2200
|
||||||
elif not srv.unlocked:
|
elif not srv.unlocked:
|
||||||
code = 2200
|
code = 2200
|
||||||
elif method == "nameserver.info":
|
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":
|
elif method == "nameserver.updateRecord":
|
||||||
for r in srv.records:
|
for r in srv.records:
|
||||||
if r["id"] == p["id"]:
|
if r["id"] == p["id"]:
|
||||||
@@ -220,20 +251,26 @@ class InwxClientTest(unittest.TestCase):
|
|||||||
|
|
||||||
def test_update_changes_record(self):
|
def test_update_changes_record(self):
|
||||||
srv = self.start()
|
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.records[0]["content"], "1.2.3.4")
|
||||||
self.assertEqual(srv.calls[-1], "account.logout")
|
self.assertEqual(srv.calls[-1], "account.logout")
|
||||||
|
|
||||||
def test_same_content_skips_update(self):
|
def test_same_content_skips_update(self):
|
||||||
srv = self.start()
|
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)
|
self.assertNotIn("nameserver.updateRecord", srv.calls)
|
||||||
|
|
||||||
def test_two_factor(self):
|
def test_two_factor(self):
|
||||||
secret = base64.b32encode(b"12345678901234567890").decode()
|
secret = base64.b32encode(b"12345678901234567890").decode()
|
||||||
srv = self.start(tfa_secret=secret)
|
srv = self.start(tfa_secret=secret)
|
||||||
self.assertTrue(
|
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)
|
self.assertIn("account.unlock", srv.calls)
|
||||||
|
|
||||||
@@ -265,8 +302,10 @@ class InwxClientTest(unittest.TestCase):
|
|||||||
raise OSError("stop here")
|
raise OSError("stop here")
|
||||||
|
|
||||||
cfg = {"inwx": {"user": "u", "pass": "p", "api": "https://inwx.invalid/"}}
|
cfg = {"inwx": {"user": "u", "pass": "p", "api": "https://inwx.invalid/"}}
|
||||||
with mock.patch("http.client.HTTPSConnection", FakeConnection):
|
with (
|
||||||
with self.assertRaises(OSError):
|
mock.patch("http.client.HTTPSConnection", FakeConnection),
|
||||||
|
self.assertRaises(OSError),
|
||||||
|
):
|
||||||
sd.inwx_update(cfg, "example.com", HOST, "A", "1.2.3.4")
|
sd.inwx_update(cfg, "example.com", HOST, "A", "1.2.3.4")
|
||||||
self.assertEqual(seen["source_address"], ("0.0.0.0", 0))
|
self.assertEqual(seen["source_address"], ("0.0.0.0", 0))
|
||||||
|
|
||||||
@@ -301,7 +340,13 @@ token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}"
|
|||||||
)
|
)
|
||||||
server = sd.make_server(path, 0, "127.0.0.1")
|
server = sd.make_server(path, 0, "127.0.0.1")
|
||||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
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.addCleanup(cleanup)
|
||||||
self.inwx = inwx
|
self.inwx = inwx
|
||||||
return server
|
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 = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=5)
|
||||||
conn.request("GET", path, headers=headers)
|
conn.request("GET", path, headers=headers)
|
||||||
response = conn.getresponse()
|
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):
|
def test_update_via_forwarded_header_then_nochg(self):
|
||||||
server = self.start(client_ip_header="X-Forwarded-For")
|
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):
|
def test_unauthorized_has_challenge(self):
|
||||||
server = self.start()
|
server = self.start()
|
||||||
status, challenge, body = self.get(server, Authorization=basic(HOST, "bad"))
|
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):
|
def test_start_page_without_credentials(self):
|
||||||
server = self.start()
|
server = self.start()
|
||||||
@@ -384,7 +435,9 @@ class OteSmokeTest(unittest.TestCase):
|
|||||||
try:
|
try:
|
||||||
self.assertTrue(sd.inwx_update(cfg, zone, host, "A", test_ip))
|
self.assertTrue(sd.inwx_update(cfg, zone, host, "A", test_ip))
|
||||||
with sd.inwx_session(cfg) as call:
|
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:
|
finally:
|
||||||
sd.inwx_update(cfg, zone, host, "A", original)
|
sd.inwx_update(cfg, zone, host, "A", original)
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user