feat: add proper logging

This commit is contained in:
mxmehl committed 2026-10-22 14:19:43 +02:00
1 parent c43f0dd699
commit af8fe5e4c0
2 files changed
+99 -29

No files matched your search

+57 -28
View File
@@ -135,20 +135,27 @@ def inwx_update(cfg, zone, name, rtype, ip):
# --- Request handling -------------------------------------------------------
def _check_auth(env, cfg):
"""Return the authenticated hostname or None."""
def _check_auth(env, cfg, note):
"""Return the authenticated hostname or None. note() gets the reason for a refusal."""
header = env.get("HTTP_AUTHORIZATION", "")
if not header.lower().startswith("basic "):
note("badauth: missing or malformed Authorization header")
return None
try:
user, _, token = base64.b64decode(header[6:]).decode().partition(":")
except ValueError:
note("badauth: undecodable Authorization header")
return None
host = cfg.get("hosts", {}).get(user.lower())
expected = (host or {}).get("token_sha256", "").lower()
given = hashlib.sha256(token.encode()).hexdigest()
# 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 None
@@ -171,15 +178,22 @@ def _save_state(path, state):
os.replace(tmp, path)
def handle(env, cfg, update=inwx_update):
"""Process one request. Return (http_status, body)."""
def handle(env, cfg, update=inwx_update, note=None):
"""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", ""))
host = _check_auth(env, cfg)
host = _check_auth(env, cfg, note)
if host is None:
return 401, "badauth"
requested = query.get("hostname", [host])[0].lower()
if requested != host:
note(
f"{host}: nohost: hostname parameter {requested[:64]!r} does not match the login"
)
return 404, "nohost"
# 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:
ip = ipaddress.ip_address(raw)
except ValueError:
note(f"{host}: badip: invalid address {raw[:64]!r}")
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,
note(
f"{host}: badip: connection address {ip} is not global, check client_ip_header"
)
return 400, "badip"
# 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:
state = _load_state(state_path)
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}")
continue
try:
update(cfg, zone, host, rtype, ip)
except NoHost as e:
# 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"
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"
# 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)
note(f"{host}: good {rtype} {old_ip or 'unknown'} -> {ip}")
state.setdefault(host, {})[rtype] = ip
_save_state(state_path, state)
lines.append(f"good {ip}")
@@ -256,23 +270,38 @@ class RequestHandler(http.server.BaseHTTPRequestHandler):
url = urllib.parse.urlsplit(self.path)
if url.path in ("/", "/nic", "/nic/"):
return self._reply(200, INDEX_HTML, "text/html")
notes = []
ip = self.client_address[0]
if url.path != "/nic/update":
return self._reply(404, "not found")
try:
# Read per request, so devices can be added without restarting
with open(cast(Server, self.server).config_path, "rb") as f:
cfg = tomllib.load(f)
env = {
"QUERY_STRING": url.query,
"HTTP_AUTHORIZATION": self.headers.get("Authorization", ""),
"REMOTE_ADDR": self._client_ip(cfg),
}
status, body = handle(env, cfg)
except Exception as e: # noqa: BLE001 - always answer the client
print(f"snap-dyndns: {type(e).__name__}: {e}", file=sys.stderr)
status, body = 500, "911"
status, body = 404, "not found"
notes.append(f"not found: {url.path[:100]!r}")
else:
try:
# Read per request, so devices can be added without restarting
with open(cast(Server, self.server).config_path, "rb") as f:
cfg = tomllib.load(f)
ip = self._client_ip(cfg) or "-"
env = {
"QUERY_STRING": url.query,
"HTTP_AUTHORIZATION": self.headers.get("Authorization", ""),
"REMOTE_ADDR": ip,
}
status, body = handle(env, cfg, note=notes.append)
except Exception as e: # noqa: BLE001 - always answer the client
notes.append(f"500: {type(e).__name__}: {e}")
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)
def log_request(self, code="-", size="-"):
"""Silence the default access log, do_GET writes a more useful line."""
def _client_ip(self, cfg):
"""Address of the device: last entry of client_ip_header (added by our proxy), else the peer."""
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 contextlib
import hashlib
import http.client
import io
import json
import os
import socket
@@ -181,6 +183,7 @@ class FakeInwx(ThreadingHTTPServer):
def __init__(self, tfa_secret=None):
super().__init__(("127.0.0.1", 0), FakeInwxHandler)
self.tfa_secret = tfa_secret
self.wrong_login = False
self.unlocked = False
self.calls = []
self.records = [
@@ -202,7 +205,7 @@ class FakeInwxHandler(BaseHTTPRequestHandler):
srv.calls.append(method)
cookie, code, res = None, 1000, {}
if method == "account.login":
if (p["user"], p["pass"]) != ("u", "p"):
if srv.wrong_login or (p["user"], p["pass"]) != ("u", "p"):
code = 2200
cookie = "sid=abc; Path=/"
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.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):
server = self.start()
self.assertEqual(self.get(server, "/elsewhere")[0], 404)