feat!: complete refactoring of server #1

Merged
mxmehl merged 10 commits from v2 into master 2026-10-22 15:35:55 +02:00
2 changed files with 89 additions and 19 deletions
Showing only changes of commit af8fe5e4c0 - Show all commits

No files matched your search

+47 -18
View File
@@ -135,20 +135,27 @@ def inwx_update(cfg, zone, name, rtype, ip):
# --- Request handling ------------------------------------------------------- # --- Request handling -------------------------------------------------------
def _check_auth(env, cfg): def _check_auth(env, cfg, note):
"""Return the authenticated hostname or None.""" """Return the authenticated hostname or None. note() gets the reason for a refusal."""
header = env.get("HTTP_AUTHORIZATION", "") header = env.get("HTTP_AUTHORIZATION", "")
if not header.lower().startswith("basic "): if not header.lower().startswith("basic "):
note("badauth: missing or malformed Authorization header")
return None return None
try: try:
user, _, token = base64.b64decode(header[6:]).decode().partition(":") user, _, token = base64.b64decode(header[6:]).decode().partition(":")
except ValueError: except ValueError:
note("badauth: undecodable Authorization header")
return None return None
host = cfg.get("hosts", {}).get(user.lower()) host = cfg.get("hosts", {}).get(user.lower())
expected = (host or {}).get("token_sha256", "").lower() expected = (host or {}).get("token_sha256", "").lower()
given = hashlib.sha256(token.encode()).hexdigest() given = hashlib.sha256(token.encode()).hexdigest()
# Always compare, so unknown users and wrong tokens take the same path. # Always compare, so unknown users and wrong tokens take the same path.
if hmac.compare_digest(given, expected) and host is not None: ok = hmac.compare_digest(given, expected)
if host is None:
note(f"badauth: unknown host {user[:64]!r}")
elif not ok:
note(f"{user.lower()}: badauth: wrong token")
else:
return user.lower() return user.lower()
return None return None
@@ -171,15 +178,22 @@ def _save_state(path, state):
os.replace(tmp, path) os.replace(tmp, path)
def handle(env, cfg, update=inwx_update): def handle(env, cfg, update=inwx_update, note=None):
"""Process one request. Return (http_status, body).""" """Process one request. Return (http_status, body).
note(text) receives one human-readable line per outcome for the log.
"""
note = note or (lambda text: None)
query = urllib.parse.parse_qs(env.get("QUERY_STRING", "")) query = urllib.parse.parse_qs(env.get("QUERY_STRING", ""))
host = _check_auth(env, cfg) host = _check_auth(env, cfg, note)
if host is None: if host is None:
return 401, "badauth" return 401, "badauth"
requested = query.get("hostname", [host])[0].lower() requested = query.get("hostname", [host])[0].lower()
if requested != host: if requested != host:
note(
f"{host}: nohost: hostname parameter {requested[:64]!r} does not match the login"
)
return 404, "nohost" return 404, "nohost"
# One IP per record type; without myip/myipv6 the connection's address is used. # One IP per record type; without myip/myipv6 the connection's address is used.
@@ -189,12 +203,12 @@ def handle(env, cfg, update=inwx_update):
try: try:
ip = ipaddress.ip_address(raw) ip = ipaddress.ip_address(raw)
except ValueError: except ValueError:
note(f"{host}: badip: invalid address {raw[:64]!r}")
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( note(
f"snap-dyndns: {host}: connection address {ip} is not global, check client_ip_header", f"{host}: badip: 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
@@ -209,21 +223,21 @@ def handle(env, cfg, update=inwx_update):
with _STATE_LOCK: with _STATE_LOCK:
state = _load_state(state_path) state = _load_state(state_path)
for rtype, ip in ips.items(): for rtype, ip in ips.items():
if state.get(host, {}).get(rtype) == ip: old_ip = state.get(host, {}).get(rtype)
if old_ip == ip:
lines.append(f"nochg {ip}") lines.append(f"nochg {ip}")
continue continue
try: try:
update(cfg, zone, host, rtype, ip) update(cfg, zone, host, rtype, ip)
except NoHost as e: except NoHost as e:
# shortcut: missing records are not created, add nameserver.createRecord if wanted # shortcut: missing records are not created, add nameserver.createRecord if wanted
print(f"snap-dyndns: {host}: {e}", file=sys.stderr) note(f"{host}: nohost: {e}")
return 404, "nohost" return 404, "nohost"
except (InwxError, OSError, ValueError) as e: except (InwxError, OSError, ValueError) as e:
print(f"snap-dyndns: {host}: {e}", file=sys.stderr) note(f"{host}: 911: {rtype} update to {ip} failed: {e}")
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") note(f"{host}: good {rtype} {old_ip or 'unknown'} -> {ip}")
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}")
@@ -256,23 +270,38 @@ class RequestHandler(http.server.BaseHTTPRequestHandler):
url = urllib.parse.urlsplit(self.path) url = urllib.parse.urlsplit(self.path)
if url.path in ("/", "/nic", "/nic/"): if url.path in ("/", "/nic", "/nic/"):
return self._reply(200, INDEX_HTML, "text/html") return self._reply(200, INDEX_HTML, "text/html")
notes = []
ip = self.client_address[0]
if url.path != "/nic/update": if url.path != "/nic/update":
return self._reply(404, "not found") status, body = 404, "not found"
notes.append(f"not found: {url.path[:100]!r}")
else:
try: try:
# Read per request, so devices can be added without restarting # Read per request, so devices can be added without restarting
with open(cast(Server, 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)
ip = self._client_ip(cfg) or "-"
env = { env = {
"QUERY_STRING": url.query, "QUERY_STRING": url.query,
"HTTP_AUTHORIZATION": self.headers.get("Authorization", ""), "HTTP_AUTHORIZATION": self.headers.get("Authorization", ""),
"REMOTE_ADDR": self._client_ip(cfg), "REMOTE_ADDR": ip,
} }
status, body = handle(env, cfg) status, body = handle(env, cfg, note=notes.append)
except Exception as e: # noqa: BLE001 - always answer the client except Exception as e: # noqa: BLE001 - always answer the client
print(f"snap-dyndns: {type(e).__name__}: {e}", file=sys.stderr) notes.append(f"500: {type(e).__name__}: {e}")
status, body = 500, "911" status, body = 500, "911"
# One line per noteworthy request: time, device address, HTTP status, what happened.
# A plain nochg is not noteworthy, devices poll every minute.
if notes:
print(
f"{time.strftime('%Y-%m-%d %H:%M:%S')} {ip} {status} {'; '.join(notes)}",
file=sys.stderr,
)
self._reply(status, body) self._reply(status, body)
def log_request(self, code="-", size="-"):
"""Silence the default access log, do_GET writes a more useful line."""
def _client_ip(self, cfg): def _client_ip(self, cfg):
"""Address of the device: last entry of client_ip_header (added by our proxy), else the peer.""" """Address of the device: last entry of client_ip_header (added by our proxy), else the peer."""
name = cfg.get("client_ip_header") name = cfg.get("client_ip_header")
+42 -1
View File
@@ -7,8 +7,10 @@ INWX_OTE_HOST (an existing A record there) are set in the environment.
""" """
import base64 import base64
import contextlib
import hashlib import hashlib
import http.client import http.client
import io
import json import json
import os import os
import socket import socket
@@ -181,6 +183,7 @@ class FakeInwx(ThreadingHTTPServer):
def __init__(self, tfa_secret=None): def __init__(self, tfa_secret=None):
super().__init__(("127.0.0.1", 0), FakeInwxHandler) super().__init__(("127.0.0.1", 0), FakeInwxHandler)
self.tfa_secret = tfa_secret self.tfa_secret = tfa_secret
self.wrong_login = False
self.unlocked = False self.unlocked = False
self.calls = [] self.calls = []
self.records = [ self.records = [
@@ -202,7 +205,7 @@ class FakeInwxHandler(BaseHTTPRequestHandler):
srv.calls.append(method) srv.calls.append(method)
cookie, code, res = None, 1000, {} cookie, code, res = None, 1000, {}
if method == "account.login": if method == "account.login":
if (p["user"], p["pass"]) != ("u", "p"): if srv.wrong_login or (p["user"], p["pass"]) != ("u", "p"):
code = 2200 code = 2200
cookie = "sid=abc; Path=/" cookie = "sid=abc; Path=/"
srv.unlocked = srv.tfa_secret is None srv.unlocked = srv.tfa_secret is None
@@ -392,6 +395,44 @@ token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}"
self.assertEqual((status, challenge), (200, None), path) self.assertEqual((status, challenge), (200, None), path)
self.assertIn("<h1>Snap DynDNS Server</h1>", body) 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"1\.2\.3\.4 401 {HOST}: badauth: wrong token")
_, log = self.logged(server, Authorization=basic("who.example.com", "x"), **xff)
self.assertIn("401 badauth: unknown host 'who.example.com'", log)
_, log = self.logged(server, "/nic/update?hostname=other.example.com", **xff)
self.assertIn(
"404 home.example.com: nohost: hostname parameter 'other.example.com'", log
)
_, log = self.logged(server, **xff)
self.assertIn("200 home.example.com: good A unknown -> 1.2.3.4", 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(
"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): def test_other_paths_are_not_found(self):
server = self.start() server = self.start()
self.assertEqual(self.get(server, "/elsewhere")[0], 404) self.assertEqual(self.get(server, "/elsewhere")[0], 404)