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")