`-element you should find a string with around 9 numbers. This number is the domain entry's ID. Please see the screenshot for how it should look like.
+Generate a token and its hash:
-
+```
+python3 -c 'import secrets,hashlib;t=secrets.token_urlsafe(32);print(t, hashlib.sha256(t.encode()).hexdigest())'
+```
-Back in `users.db`, type in the domain name (`user1.example.com`) and its INWX ID. For username and password, you can freely create one and give to your users. Each request to your service requires the correct domain name, a username and a password. Only if all three match, the IP change request will be executed.
+Put the hash into a new section of `config.toml` and give the token to the device:
+
+```toml
+[hosts."user1.example.com"]
+token_sha256 = "
"
+```
+
+The hostname is the Basic Auth user name, the token the password. The INWX zone is guessed as the last two labels of the hostname. For zones such as `example.co.uk` set `zone = "example.co.uk"` in that section.
## Usage
-Please feel free to use [Snap DynDNS client](https://src.mehl.mx/mxmehl/snap-dyndns-client) which is the perfect combination for this server application.
-
-Please note: You cannot define whether it shall be an A, AAAA or whatever record. You would have to do that in the INWX webpanel once, the ID should stay the same.
-
-### curl
-
-You can use curl with a POST request:
-
- curl -X POST -d "domain=user1.example.com&user=myuser&pass=mypassword&ip=1.2.3.4" "https://yourdyndnsservice.net/update.php"
-
-You can also use GET requests which is **not** recommended. The advantage of POST requests is that the request is encrypted via SSL if you use a HTTPS domain. GET requests can be intercepted quite easily which is bad because you send sensitive data. A GET request would look like this
-
- curl -d "domain=user1.example.com&user=myuser&pass=mypassword&ip=1.2.3.4" "https://yourdyndnsservice.net/update.php"
-
-This will send following data to your **Snap DynDNS server** which is running under the domain `https://yourdyndnsservice.net` in this example:
-
-* `domain=user1.example.com`: This is the client's personal DynDNS domain
-* `user=myuser`: This is the client's username which you can define freely
-* `pass=mypassword`: This is the client's personal password which you can define freely.
-* `ip=1.2.3.4`: This is the IP which shall be set to this single domain
-
-## AVM FritzBox
-
-In the AVM Fritz!Boxes you can choose a custom DynDNS provider. In order to connect it with your Snap DynDNS server, use following data:
+With curl (the `-u` option keeps the credentials out of the URL):
```
-Update-URL: yourdyndnsservice.net/update.php?domain=&user=&pass=&ip=
-Domainname: user1.example.com
-Username: myuser
-Password: mypassword
+curl -fsS -u user1.example.com:TOKEN "https://dyndns.mydomain.net/update.cgi"
+curl -fsS -u user1.example.com:TOKEN "https://dyndns.mydomain.net/update.cgi?myip=1.2.3.4"
```
-Be sure to not add an URI scheme like `https://`, the device will throw an error. The IP address is set automatically by the device. Note that you can also set your IPv6 address by using `` in the URL.
+Parameters, all optional:
+
+- `hostname`: must equal the Basic Auth user name
+- `myip`: IPv4 or IPv6 address to set, defaults to the address of the request
+- `myipv6`: IPv6 address, to update A and AAAA in one request
+
+Answers (HTTP status in brackets):
+
+- `good ` (200): the record was updated
+- `nochg ` (200): the IP is what the server stored last, INWX was not contacted
+- `badauth` (401): unknown hostname or wrong token
+- `nohost` (404): hostname mismatch, or the record does not exist at INWX
+- `badip` (400): the IP could not be parsed
+- `911` (502 or 500): INWX or the server config failed, see the Apache error log
+
+### AVM FritzBox
+
+Choose a custom DynDNS provider:
+
+```
+Update-URL: https://dyndns.mydomain.net/update.cgi?hostname=&myip=&myipv6=
+Domain name: user1.example.com
+User name: user1.example.com
+Password: TOKEN
+```
+
+### ddclient
+
+```
+protocol=dyndns2
+server=dyndns.mydomain.net
+script=/dyn/update.cgi
+ssl=yes
+login=user1.example.com
+password=TOKEN
+user1.example.com
+```
+
+## Known limits
+
+- The IP is only checked for syntax, private and reserved addresses are accepted.
+- Missing records are not created, add them at INWX first.
+- If you change a record at INWX by hand, the server does not notice. Delete `state.json` or change the IP to resync.
+- Only one request updates at a time (a file lock is held during the INWX call), which is plenty for a personal setup.
+
+## Development
+
+```
+uv run --python 3.14 python -m unittest -v
+```
+
+The tests use a fake INWX server. An additional smoke test runs against the INWX OT&E test system and is skipped unless `INWX_OTE_USER`, `INWX_OTE_PASS` and `INWX_OTE_HOST` (an existing A record in that account) are set in the environment. It restores the record afterwards.
+
+## License
+
+AGPL-3.0-or-later, see `LICENSE`.
diff --git a/config.cfg.sample b/config.cfg.sample
deleted file mode 100644
index e6853f2..0000000
--- a/config.cfg.sample
+++ /dev/null
@@ -1,11 +0,0 @@
-# INWX USERNAME
-USERNAME=myusername
-
-# INWX PASSWORD
-PASSWORD=mypassword
-
-# API-Host
-APIHOST=https://api.domrobot.com/xmlrpc/
-
-# Activate debugging? Use true or false
-DEBUG=false
diff --git a/config.toml.sample b/config.toml.sample
new file mode 100644
index 0000000..d83840e
--- /dev/null
+++ b/config.toml.sample
@@ -0,0 +1,24 @@
+# Copy to ~/etc/snap-dyndns/config.toml (outside the web root) and chmod 600.
+
+# Where the last known IPs are cached (default shown)
+state_file = "~/etc/snap-dyndns/state.json"
+
+[inwx]
+user = "api-user"
+pass = "api-password"
+# Only needed if the INWX account has 2FA enabled (base32 secret of the authenticator)
+# totp_secret = "JBSWY3DPEHPK3PXP"
+# Default is the live API. Use the OT&E test system for experiments:
+# api = "https://api.ote.domrobot.com/jsonrpc/"
+
+# One section per hostname. The hostname is the Basic Auth user, the token the password.
+# The record (A and/or AAAA) must already exist at INWX.
+# Generate a token and its hash with:
+# python3 -c 'import secrets,hashlib;t=secrets.token_urlsafe(32);print(t, hashlib.sha256(t.encode()).hexdigest())'
+[hosts."user1.example.com"]
+token_sha256 = "replace-with-sha256-hex-of-the-token"
+# INWX zone, defaults to the last two labels of the hostname
+# zone = "example.co.uk"
+
+[hosts."user2.example.com"]
+token_sha256 = "replace-with-another-hash"
diff --git a/index.html b/index.html
deleted file mode 100644
index b081b84..0000000
--- a/index.html
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
- Snap DynDNS Server
-
-
-Snap DynDNS Server
-This is a Dynamic DNS service. It is running with the Snap DynDNS Server software.
-Please contact the site owner for more information on this specific service.
-
-
diff --git a/screen-inwx-id.png b/screen-inwx-id.png
deleted file mode 100644
index 338d9b3..0000000
Binary files a/screen-inwx-id.png and /dev/null differ
diff --git a/snap_dyndns.py b/snap_dyndns.py
new file mode 100644
index 0000000..ecab47c
--- /dev/null
+++ b/snap_dyndns.py
@@ -0,0 +1,217 @@
+# SPDX-FileCopyrightText: 2016 Max Mehl
+# SPDX-License-Identifier: AGPL-3.0-or-later
+"""Snap DynDNS Server: dyndns2-style CGI broker that updates INWX records.
+
+Clients authenticate with HTTP Basic Auth (user = hostname, password = token).
+The INWX credentials never leave this server, and INWX is only contacted when
+the IP of a hostname actually changed.
+"""
+
+import base64
+import contextlib
+import fcntl
+import hashlib
+import hmac
+import http
+import http.cookiejar
+import ipaddress
+import json
+import os
+import struct
+import sys
+import time
+import tomllib
+import urllib.parse
+import urllib.request
+
+API_LIVE = "https://api.domrobot.com/jsonrpc/"
+DEFAULT_CONFIG = "~/etc/snap-dyndns/config.toml"
+DEFAULT_STATE = "~/etc/snap-dyndns/state.json"
+
+
+class InwxError(Exception):
+ """INWX API call failed. Messages must never contain credentials."""
+
+
+class NoHost(InwxError):
+ """The record to update does not exist at INWX."""
+
+
+# --- INWX JSON-RPC client ---------------------------------------------------
+
+
+def totp(secret, now=None):
+ """RFC 6238 code (HMAC-SHA1, 30 s step, 6 digits) for a base32 secret."""
+ key = base64.b32decode(secret.replace(" ", "").upper())
+ counter = int((time.time() if now is None else now) // 30)
+ digest = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
+ offset = digest[-1] & 15
+ code = (struct.unpack(">I", digest[offset : offset + 4])[0] & 0x7FFFFFFF) % 10**6
+ return f"{code:06d}"
+
+
+@contextlib.contextmanager
+def inwx_session(cfg):
+ """Yield call(method, params) -> resData for a logged-in INWX session."""
+ inwx = cfg["inwx"]
+ url = inwx.get("api", API_LIVE)
+ opener = urllib.request.build_opener(
+ urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())
+ )
+
+ def call(method, params):
+ request = urllib.request.Request(
+ url,
+ json.dumps({"method": method, "params": params}).encode(),
+ {"Content-Type": "application/json"},
+ )
+ with opener.open(request, timeout=20) as response:
+ result = json.load(response)
+ if result.get("code") != 1000:
+ raise InwxError(f"{method}: {result.get('code')} {result.get('msg')}")
+ return result.get("resData") or {}
+
+ login = call(
+ "account.login", {"user": inwx["user"], "pass": inwx["pass"], "lang": "en"}
+ )
+ try:
+ if str(login.get("tfa", "0")) != "0":
+ if not inwx.get("totp_secret"):
+ raise InwxError("account requires 2FA but no totp_secret is configured")
+ call("account.unlock", {"tan": totp(inwx["totp_secret"])})
+ yield call
+ finally:
+ with contextlib.suppress(Exception):
+ call("account.logout", {})
+
+
+def find_record(call, zone, name, rtype):
+ """Return the single INWX record with this name and type, else raise NoHost."""
+ info = call("nameserver.info", {"domain": zone, "name": name, "type": rtype})
+ matches = [
+ r
+ for r in info.get("record", [])
+ if r.get("type") == rtype and r.get("name", "").rstrip(".").lower() == name
+ ]
+ if not matches:
+ raise NoHost(f"no {rtype} record {name} in zone {zone}")
+ if len(matches) > 1:
+ raise InwxError(f"{len(matches)} {rtype} records named {name}, expected one")
+ return matches[0]
+
+
+def inwx_update(cfg, zone, name, rtype, ip):
+ """Set the record content to ip. Return True if INWX was changed."""
+ with inwx_session(cfg) as call:
+ record = find_record(call, zone, name, rtype)
+ if record.get("content") == ip:
+ return False
+ call("nameserver.updateRecord", {"id": record["id"], "content": ip})
+ return True
+
+
+# --- Request handling -------------------------------------------------------
+
+
+def _check_auth(env, cfg):
+ """Return the authenticated hostname or None."""
+ header = env.get("HTTP_AUTHORIZATION", "")
+ if not header.lower().startswith("basic "):
+ return None
+ try:
+ user, _, token = base64.b64decode(header[6:]).decode().partition(":")
+ except ValueError:
+ 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:
+ return user.lower()
+ return None
+
+
+def _load_state(path):
+ try:
+ with open(path) as f:
+ return json.load(f)
+ except FileNotFoundError:
+ return {}
+
+
+def _save_state(path, state):
+ tmp = f"{path}.tmp"
+ with open(tmp, "w") as f:
+ json.dump(state, f)
+ os.replace(tmp, path)
+
+
+def handle(env, cfg, update=inwx_update):
+ """Process one request. Return (http_status, body)."""
+ query = urllib.parse.parse_qs(env.get("QUERY_STRING", ""))
+ host = _check_auth(env, cfg)
+ if host is None:
+ return 401, "badauth"
+
+ requested = query.get("hostname", [host])[0].lower()
+ if requested != host:
+ return 404, "nohost"
+
+ # One IP per record type; without myip/myipv6 the connection's address is used.
+ given = [query[k][0] for k in ("myip", "myipv6") if query.get(k, [""])[0]]
+ ips = {}
+ for raw in given or [env.get("REMOTE_ADDR", "")]:
+ try:
+ ip = ipaddress.ip_address(raw)
+ except ValueError:
+ return 400, "badip"
+ # shortcut: syntax-only check (private/reserved IPs are accepted), reject them if clients misbehave
+ ips["A" if ip.version == 4 else "AAAA"] = str(ip)
+
+ zone = cfg["hosts"][host].get("zone") or ".".join(host.split(".")[-2:])
+ state_path = os.path.expanduser(cfg.get("state_file", DEFAULT_STATE))
+ os.makedirs(os.path.dirname(state_path), exist_ok=True)
+
+ lines = []
+ # shortcut: lock is held during the INWX call, fine at this load, split if updates ever get slow
+ with open(f"{state_path}.lock", "a") as lock:
+ fcntl.flock(lock, fcntl.LOCK_EX)
+ state = _load_state(state_path)
+ for rtype, ip in ips.items():
+ if state.get(host, {}).get(rtype) == 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)
+ return 404, "nohost"
+ except (InwxError, OSError, ValueError) as e:
+ print(f"snap-dyndns: {host}: {e}", file=sys.stderr)
+ return 502, "911"
+ # shortcut: cache goes stale if the record is edited by hand at INWX, delete state.json to resync
+ state.setdefault(host, {})[rtype] = ip
+ _save_state(state_path, state)
+ lines.append(f"good {ip}")
+ return 200, "\n".join(lines)
+
+
+def main(env=os.environ, out=sys.stdout):
+ """CGI entry point."""
+ try:
+ path = os.path.expanduser(env.get("SNAP_DYNDNS_CONFIG", DEFAULT_CONFIG))
+ with open(path, "rb") as f:
+ cfg = tomllib.load(f)
+ status, body = handle(env, cfg)
+ except Exception as e: # noqa: BLE001 - a CGI must always answer
+ print(f"snap-dyndns: {type(e).__name__}: {e}", file=sys.stderr)
+ status, body = 500, "911"
+ headers = [
+ f"Status: {status} {http.HTTPStatus(status).phrase}",
+ "Content-Type: text/plain; charset=utf-8",
+ "Cache-Control: no-store",
+ ]
+ if status == 401:
+ headers.append('WWW-Authenticate: Basic realm="Snap DynDNS"')
+ out.write("\n".join(headers) + "\n\n" + body + "\n")
diff --git a/test_snap_dyndns.py b/test_snap_dyndns.py
new file mode 100644
index 0000000..8e9dfac
--- /dev/null
+++ b/test_snap_dyndns.py
@@ -0,0 +1,305 @@
+# SPDX-FileCopyrightText: 2016 Max Mehl
+# 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 io
+import json
+import os
+import tempfile
+import threading
+import unittest
+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="2001:db8::1"), (200, "good 2001:db8::1"))
+ 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_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 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_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 MainTest(unittest.TestCase):
+ def run_main(self, env, cfg_text):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = os.path.join(tmp, "config.toml")
+ with open(path, "w") as f:
+ f.write(cfg_text.replace("STATE", os.path.join(tmp, "state.json")))
+ out = io.StringIO()
+ sd.main({**env, "SNAP_DYNDNS_CONFIG": path}, out)
+ return out.getvalue()
+
+ CFG = f"""
+state_file = "STATE"
+[inwx]
+user = "u"
+pass = "p"
+api = "http://127.0.0.1:1/"
+[hosts."{HOST}"]
+token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}"
+"""
+
+ def test_unauthorized_has_challenge(self):
+ out = self.run_main(make_env(auth=basic(HOST, "bad")), self.CFG)
+ head, _, body = out.partition("\n\n")
+ self.assertTrue(head.startswith("Status: 401 Unauthorized"))
+ self.assertIn('WWW-Authenticate: Basic realm="Snap DynDNS"', head)
+ self.assertEqual(body, "badauth\n")
+
+ def test_unreachable_inwx_is_911(self):
+ out = self.run_main(make_env(), self.CFG)
+ self.assertTrue(out.startswith("Status: 502 Bad Gateway\n"))
+ self.assertTrue(out.endswith("\n\n911\n"))
+
+ def test_broken_config_is_500(self):
+ out = self.run_main(make_env(), "not = [valid")
+ self.assertTrue(out.startswith("Status: 500 Internal Server Error\n"))
+
+
+@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()
diff --git a/update.api b/update.api
deleted file mode 100644
index 6ef226a..0000000
--- a/update.api
+++ /dev/null
@@ -1,49 +0,0 @@
-
-
- nameserver.updateRecord
-
-
-
-
-
- user
-
- %USER%
-
-
-
- lang
-
- en
-
-
-
- pass
-
- %PASSWD%
-
-
-
- id
-
- %DNSID%
-
-
-
- content
-
- %NEWIP%
-
-
-
- ttl
-
- 3600
-
-
-
-
-
-
-
-
diff --git a/update.cgi b/update.cgi
new file mode 100755
index 0000000..2e30de7
--- /dev/null
+++ b/update.cgi
@@ -0,0 +1,10 @@
+#!/usr/bin/python3.14
+# SPDX-FileCopyrightText: 2016 Max Mehl
+# SPDX-License-Identifier: AGPL-3.0-or-later
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
+from snap_dyndns import main
+
+main()
diff --git a/update.php b/update.php
deleted file mode 100644
index 7a83d7d..0000000
--- a/update.php
+++ /dev/null
@@ -1,108 +0,0 @@
-
-************************************************************************
-*
-* This program is free software: you can redistribute it and/or modify
-* it under the terms of the GNU Affero General Public License as
-* published by the Free Software Foundation, either version 3 of the
-* License, or (at your option) any later version.
-*
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU Affero General Public License for more details.
-*
-* You should have received a copy of the GNU Affero General Public
-* License along with this program. If not, see
-* .
-*
-************************************************************************
-*
-* This file receives the requests, sanitises them, forwards the input
-* to update.sh and prints the results. It is also responsible for
-* debug logs.
-*
-***********************************************************************/
-?>
-$output";
-}
-
-
-// DEBUGGING
-if($debug === true) {
-$date = date("Y-m-d H:i:s");
-$browser = $_SERVER['HTTP_USER_AGENT'];
-$postdata = print_r($_POST, TRUE);
-$getdata = print_r($_GET, TRUE);
-
-$debug =
-// basic info
-'$date: ' . $date . '
' .
-'$browser: ' . $browser . '
' .
-'$debug: ' . $debug . '
' .
-'$method: ' . $method . '
' .
-// Specific set variables
-'$domain: ' . $domain . '
' .
-'$ip: ' . $ip . '
' .
-'$user: ' . $user . '
' .
-'$pass: ' . $pass . '
' .
-// all POST and GET
-'$postdata: ' . $postdata . '
' .
-'$getdata: ' . $getdata . '
'
-;
-
-echo "Debug information:
";
-print_r($debug); // Show debug in browser
-
-$debug_log = str_replace('
', "\r\n", $debug); //
-
-file_put_contents('debug.log', $debug_log, FILE_APPEND | LOCK_EX);
-}
-
-?>
diff --git a/update.sh b/update.sh
deleted file mode 100755
index dacdd55..0000000
--- a/update.sh
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/bin/bash
-########################################################################
-# Copyright (C) 2016 Max Mehl
-########################################################################
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Affero General Public License as
-# published by the Free Software Foundation, either version 3 of the
-# License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Affero General Public License for more details.
-#
-# You should have received a copy of the GNU Affero General Public
-# License along with this program. If not, see
-# .
-#
-########################################################################
-#
-# This file uses the data forwarded by update.php, validates the given
-# login data in the user database, and does the API call to the INWX
-# API.
-#
-########################################################################
-
-
-cd "$(dirname "$(readlink -f "$0")")"
-
-# Test if config.cfg exists and set needed variables
-if [ ! -e config.cfg ]; then echo "Missing config.cfg file. Edit and rename config.cfg.sample"; exit 1; fi
-source config.cfg
-
-# Check dependencies
-deperrors=''
-for depend in curl; do
- if ! command -v "$depend" >/dev/null 2>&1; then
- deperrors="$depend $deperrors"
- fi
-done
-if [ -n "$deperrors" ]; then
- cat <<-EOF
- This program depends on some other programs to function.
- Not all of those programs could be located on your system.
- Please use your package manager to install the following programs:
- EOF
- echo "$deperrors"
- exit 1
-fi
-
-USERDB=users.db
-
-DOMAIN="$1"
-NEWIP="$2"
-U_USER="$3"
-U_PASS="$4"
-
-E=$(grep "^$DOMAIN;" $USERDB)
-
-if [ "$E" != "" ]; then
- DNSID=$(echo $E | cut -d";" -f2)
- E_USER=$(echo $E | cut -d";" -f3)
- E_PASS=$(echo $E | cut -d";" -f4)
-
- # Check if user as given correct user and password
- if [ "$U_USER" == "$E_USER" ] && [ "$U_PASS" == "$E_PASS" ]; then
- DATA=$(cat update.api | sed "s/%PASSWD%/$PASSWORD/g;s/%USER%/$USERNAME/g;s/%DNSID%/$DNSID/g;s/%NEWIP%/$NEWIP/g")
- curl -X POST -d "$DATA" "$APIHOST" --header "Content-Type:text/xml" --insecure > update.log
- echo "" >> update.log
- echo "Updated IP address for $DNSID ($DOMAIN) to $NEWIP." >> update.log
- echo "Success: Updated $DOMAIN to $NEWIP."
- else
- echo "Wrong user or password."
- fi
-else
- echo "Domain does not exist in database"
-fi
-
-
diff --git a/users.db.sample b/users.db.sample
deleted file mode 100644
index a47fe0e..0000000
--- a/users.db.sample
+++ /dev/null
@@ -1,3 +0,0 @@
-# DOMAIN; DOMAIN-ID; USER; PASSWORD
-user1.example.com;123456789;myuser;mypassword
-user2.example.com;987654321;otheruser;otherpassword