diff options
| -rw-r--r-- | .gitignore | 2 | ||||
| -rw-r--r-- | README.md | 132 | ||||
| -rw-r--r-- | deploy/ip-echo-daemon.service | 16 | ||||
| -rw-r--r-- | deploy/ip.mfamily.org.nginx | 28 | ||||
| -rwxr-xr-x | he-dyndns | 406 | ||||
| -rwxr-xr-x | ip-echo-daemon | 76 | ||||
| -rw-r--r-- | tests/test_he_dyndns.py | 129 |
7 files changed, 622 insertions, 167 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..43ae0e2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.py[cod] @@ -2,11 +2,29 @@ A collection of scripts to manage various aspects of using dynamic DNS, usually to cope with dynamic IP addressing -## he-dyndns +## he-dyndns A Python-based script to update dynamic DNS records when using the -Hurricant Electric DNS service at ``dns.he.net``. This code is -designed to ba maximally portable by relying on standard -Python 3 libraries. It is not compatible with Python 2. +Hurricane Electric DNS service at `dns.he.net`. It uses only Python 3's +standard library. + +Unless an address is supplied with `--addr4` or `--addr6`, the script asks +`https://ip.mfamily.org/` for its public address over the selected IP family. +It compares that address with local state and contacts HE only when the address +has changed. IPv4 is selected by default; use `--v6` for IPv6. + +State defaults to `/var/lib/he-dyndns/state.json`. The file contains entries +for multiple records and both address families. Updates are locked and written +atomically, so separate IPv4 and IPv6 cron jobs can share it. State is recorded +only after HE returns `good` or `nochg`. Both address discovery and HE updates +use certificate-validated HTTPS. + +Explicit addresses retain unconditional update behavior and do not read or +write the state file: + +``` +he-dyndns --addr4 192.0.2.10 home.example.com +he-dyndns --addr6 2001:db8::10 home.example.com +``` ## ddns-update-rfc2136 A Python-based script to update DNS records in a master server @@ -22,18 +40,15 @@ get that. If there's no A, you get AAAA. If there's neither, the script will bomb. # he-dyndns Installation / Use -There is really nothing to install unless you need to add -Python3 stock libraries to your system. Copy he-dyndns somewhere useful -such as `/usr/local/bin`. - -For Debian/Ubuntu systems: ``apt install python3-dns python3-dnspython python3-urllib3`` - -For Fedora systems: ``dnf install python3-dns python3-urllib3`` +Copy `he-dyndns` somewhere useful such as `/usr/local/bin`. No third-party +Python modules are required. If it runs as a non-root service account, create +the state directory for that account first, or select a writable path with +`--state-file`. ## Configuration -Unless using the ``--key`` argument, keys for the dyanmic record -are read from ``/etc/he-dyndns.conf`` or from an alternative -location specified by ``--keyfile``. The configuration file +Unless using the `--key` argument, keys for the dynamic record +are read from `/etc/he-dyndns.conf` or from an alternative +location specified by `--keyfile`. The configuration file format is one section [keys] with record = key pairs. For example: ``` @@ -45,21 +60,27 @@ Other configuration sections will be ignored. ## Usage ``` -usage: he-dyndns [-h] [--v4] [--v6] [--addr4 ADDR4] [--addr6 ADDR6] [--key KEY] [--debug] record +usage: he-dyndns [-h] [--v4 | --v6] [--addr4 ADDR4 | --addr6 ADDR6] + [--check-url CHECK_URL] [--state-file STATE_FILE] + [--keyfile KEYFILE] [--key KEY] [--timeout TIMEOUT] [--debug] + record Update Hurricane Electric DNS dynamic record positional arguments: record DNS record to update -optional arguments: +options: -h, --help show this help message and exit --v4 Update IPv4 A record (default) --v6 Update IPv6 AAAA record - --addr4 ADDR4 Update A record with provided IP rather than detected IP - --addr6 ADDR6 Update AAAA record with provided IP rather than detected IP - --keyfile KEYFILE Alternate location for key config file (default /etc/he-dns-secret.conf) - --key KEY HE DDNS key for record (by default read from /etc/he-dns-secret.conf or --keyfile) + --addr4 ADDR4 Use this IPv4 address; bypass discovery/state comparison + --addr6 ADDR6 Use this IPv6 address; bypass discovery/state comparison + --check-url URL Public address service (default https://ip.mfamily.org/) + --state-file FILE Local comparison state (default /var/lib/he-dyndns/state.json) + --keyfile KEYFILE Key config file (default /etc/he-dyndns.conf) + --key KEY HE DDNS key for record; overrides --keyfile + --timeout SECONDS Network timeout in seconds (default 10) --debug Enable debug logging ``` @@ -68,6 +89,77 @@ optional arguments: Returns 0 on success (successful change or no change) or 1 on failure. Failures also include a single line error message. +For example, two cron entries can check both families while sharing the state +file: + +``` +*/5 * * * * /usr/local/bin/he-dyndns home.example.com +*/5 * * * * /usr/local/bin/he-dyndns --v6 home.example.com +``` + +# ip.mfamily.org address service + +`ip-echo-daemon` is the backend for the dual-stack public address check. It +binds to `127.0.0.1:8080` by default and trusts `X-Real-IP` only when the +connection comes from loopback. The included nginx configuration overwrites +that header with nginx's actual peer address. + +The hostname must have both an A record and an AAAA record pointing to the +VPS, and nginx must have a valid certificate for it. The included paths assume +a Let's Encrypt certificate. On the VPS: + +``` +install -m 0755 ip-echo-daemon /usr/local/bin/ip-echo-daemon +install -m 0644 deploy/ip-echo-daemon.service /etc/systemd/system/ip-echo-daemon.service +install -m 0644 deploy/ip.mfamily.org.nginx /etc/nginx/sites-available/ip.mfamily.org +ln -s /etc/nginx/sites-available/ip.mfamily.org /etc/nginx/sites-enabled/ip.mfamily.org +systemctl daemon-reload +systemctl enable --now ip-echo-daemon.service +nginx -t +systemctl reload nginx +``` + +The nginx server block redirects HTTP to HTTPS, listens on IPv4 and IPv6, and +proxies only `/`: + +``` +server { + listen 80; + listen [::]:80; + server_name ip.mfamily.org; + + return 301 https://$host$request_uri; +} + +server { + listen 443 ssl; + listen [::]:443 ssl; + server_name ip.mfamily.org; + + ssl_certificate /etc/letsencrypt/live/ip.mfamily.org/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/ip.mfamily.org/privkey.pem; + + location = / { + proxy_pass http://127.0.0.1:8080/; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_pass_request_body off; + proxy_set_header Content-Length ""; + } + + location / { + return 404; + } +} +``` + +Verify both paths from another dual-stack system: + +``` +curl -4 https://ip.mfamily.org/ +curl -6 https://ip.mfamily.org/ +``` + # ddns-update-rfc2136 Installation/Use This script relies on the `netifaces` and `subprocess` libraries that are not always installed by default in Python3. Install those diff --git a/deploy/ip-echo-daemon.service b/deploy/ip-echo-daemon.service new file mode 100644 index 0000000..b275067 --- /dev/null +++ b/deploy/ip-echo-daemon.service @@ -0,0 +1,16 @@ +[Unit] +Description=IP address echo service for ip.mfamily.org +After=network.target + +[Service] +Type=simple +ExecStart=/usr/local/bin/ip-echo-daemon +DynamicUser=yes +Restart=on-failure +PrivateTmp=yes +ProtectSystem=strict +ProtectHome=yes +NoNewPrivileges=yes + +[Install] +WantedBy=multi-user.target diff --git a/deploy/ip.mfamily.org.nginx b/deploy/ip.mfamily.org.nginx new file mode 100644 index 0000000..08cbeb5 --- /dev/null +++ b/deploy/ip.mfamily.org.nginx @@ -0,0 +1,28 @@ +server { + listen 80; + listen [::]:80; + server_name ip.mfamily.org; + + return 301 https://$host$request_uri; +} + +server { + listen 443 ssl; + listen [::]:443 ssl; + server_name ip.mfamily.org; + + ssl_certificate /etc/letsencrypt/live/ip.mfamily.org/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/ip.mfamily.org/privkey.pem; + + location = / { + proxy_pass http://127.0.0.1:8080/; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_pass_request_body off; + proxy_set_header Content-Length ""; + } + + location / { + return 404; + } +} @@ -3,160 +3,272 @@ import argparse import base64 import configparser -import dns.resolver +import contextlib +import fcntl +import http.client import ipaddress +import json import logging -import logging.handlers -import os.path +import os import socket +import ssl import sys -import urllib +import tempfile +import urllib.parse HE_DNS_API_HOST = "dyn.dns.he.net" +DEFAULT_CHECK_URL = "https://ip.mfamily.org/" +DEFAULT_STATE_FILE = "/var/lib/he-dyndns/state.json" + + +def parse_ip(value, version=None): + try: + address = ipaddress.ip_address(value.strip()) + except ValueError as exc: + raise ValueError("invalid IP address: {}".format(value)) from exc + if version is not None and address.version != version: + raise ValueError("expected an IPv{} address, got {}".format(version, address)) + return address + + +def get_key(keyfile, record): + if not os.path.exists(keyfile): + raise RuntimeError("missing keyfile {}".format(keyfile)) + config = configparser.ConfigParser() + config.read(keyfile) + if "keys" not in config: + raise RuntimeError("keyfile lacks [keys] section") + if record not in config["keys"]: + raise RuntimeError("keyfile has no entry for {}".format(record)) + return config["keys"][record] + + +def http_get(host, port, target, family, headers=None, timeout=10, use_tls=False): + """Make an HTTP request using only addresses from the requested family.""" + request_headers = { + "Host": host if port == 80 else "{}:{}".format(host, port), + "Connection": "close", + "User-Agent": "he-dyndns/1", + } + request_headers.update(headers or {}) + request = "GET {} HTTP/1.1\r\n{}\r\n\r\n".format( + target, + "\r\n".join("{}: {}".format(name, value) for name, value in request_headers.items()), + ).encode("ascii") + + errors = [] + addresses = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM) + for af, socktype, proto, _canonname, sockaddr in addresses: + connection = socket.socket(af, socktype, proto) + connection.settimeout(timeout) + try: + connection.connect(sockaddr) + if use_tls: + context = ssl.create_default_context() + connection = context.wrap_socket(connection, server_hostname=host) + connection.sendall(request) + response = http.client.HTTPResponse(connection) + response.begin() + body = response.read(4097) + if len(body) > 4096: + raise RuntimeError("HTTP response was too large") + return response.status, body + except (OSError, http.client.HTTPException, RuntimeError) as exc: + errors.append(str(exc)) + finally: + connection.close() + + detail = "; ".join(errors) if errors else "no addresses returned" + raise RuntimeError( + "could not connect to {} over IPv{}: {}".format( + host, 4 if family == socket.AF_INET else 6, detail + ) + ) + + +def discover_address(check_url, version, timeout=10): + parsed = urllib.parse.urlsplit(check_url) + if parsed.scheme not in ("http", "https") or not parsed.hostname: + raise ValueError("check URL must be an http:// or https:// URL with a hostname") + if parsed.username or parsed.password or parsed.fragment: + raise ValueError("check URL must not contain credentials or a fragment") + family = socket.AF_INET if version == 4 else socket.AF_INET6 + target = parsed.path or "/" + if parsed.query: + target += "?" + parsed.query + use_tls = parsed.scheme == "https" + port = parsed.port or (443 if use_tls else 80) + status, body = http_get( + parsed.hostname, port, target, family, timeout=timeout, use_tls=use_tls + ) + if status != 200: + raise RuntimeError("address check returned HTTP {}".format(status)) + try: + value = body.decode("ascii").strip() + except UnicodeDecodeError as exc: + raise RuntimeError("address check returned non-ASCII data") from exc + return parse_ip(value, version) + + +def update_he(record, key, address, timeout=10): + family = socket.AF_INET if address.version == 4 else socket.AF_INET6 + query = urllib.parse.urlencode({"hostname": record, "myip": str(address)}) + credentials = base64.b64encode( + "{}:{}".format(record, key).encode("ascii") + ).decode("ascii") + status, body = http_get( + HE_DNS_API_HOST, + 443, + "/nic/update?" + query, + family, + headers={"Authorization": "Basic " + credentials}, + timeout=timeout, + use_tls=True, + ) + if status != 200: + raise RuntimeError("HE returned HTTP {}".format(status)) + response = body.decode("ascii", errors="replace").strip() + result = response.split()[0] if response else "" + log.debug("HE response: %s", response) + if result in ("good", "nochg"): + return + if result == "badauth": + raise RuntimeError( + "HE badauth: wrong key or record not configured for dynamic updates" + ) + raise RuntimeError("HE returned {!r}: unknown response code".format(result)) + + +def read_state(path): + try: + with open(path, "r", encoding="utf-8") as state_file: + state = json.load(state_file) + except FileNotFoundError: + return {} + except (OSError, json.JSONDecodeError) as exc: + raise RuntimeError("could not read state file {}: {}".format(path, exc)) from exc + if not isinstance(state, dict): + raise RuntimeError("state file {} does not contain an object".format(path)) + return state + + +def write_state(path, state): + directory = os.path.dirname(os.path.abspath(path)) + os.makedirs(directory, mode=0o755, exist_ok=True) + fd, temporary_path = tempfile.mkstemp(prefix=".state-", dir=directory, text=True) + try: + os.fchmod(fd, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as state_file: + json.dump(state, state_file, indent=2, sort_keys=True) + state_file.write("\n") + state_file.flush() + os.fsync(state_file.fileno()) + os.replace(temporary_path, path) + except Exception: + with contextlib.suppress(FileNotFoundError): + os.unlink(temporary_path) + raise + + +@contextlib.contextmanager +def state_lock(path): + directory = os.path.dirname(os.path.abspath(path)) + os.makedirs(directory, mode=0o755, exist_ok=True) + lock_file = open(path + ".lock", "a", encoding="ascii") + try: + fcntl.flock(lock_file, fcntl.LOCK_EX) + yield + finally: + fcntl.flock(lock_file, fcntl.LOCK_UN) + lock_file.close() + + +def selected_version(args, parser): + if args.v4 and args.addr6: + parser.error("--v4 cannot be combined with --addr6") + if args.v6 and args.addr4: + parser.error("--v6 cannot be combined with --addr4") + return 6 if args.v6 or args.addr6 else 4 + + +def make_parser(): + parser = argparse.ArgumentParser( + description="Update a Hurricane Electric DNS dynamic record" + ) + versions = parser.add_mutually_exclusive_group() + versions.add_argument("--v4", action="store_true", help="update IPv4 A record (default)") + versions.add_argument("--v6", action="store_true", help="update IPv6 AAAA record") + addresses = parser.add_mutually_exclusive_group() + addresses.add_argument( + "--addr4", help="use this IPv4 address; bypass discovery/state comparison" + ) + addresses.add_argument( + "--addr6", help="use this IPv6 address; bypass discovery/state comparison" + ) + parser.add_argument("record", help="DNS record to update") + parser.add_argument( + "--check-url", default=DEFAULT_CHECK_URL, + help="public address service (default: %(default)s)", + ) + parser.add_argument( + "--state-file", default=DEFAULT_STATE_FILE, + help="local comparison state (default: %(default)s)", + ) + parser.add_argument( + "--keyfile", default="/etc/he-dyndns.conf", + help="key config file (default: %(default)s)", + ) + parser.add_argument("--key", help="HE DDNS key; overrides --keyfile") + parser.add_argument("--timeout", type=float, default=10, help="network timeout in seconds") + parser.add_argument("--debug", action="store_true", help="enable debug logging") + return parser + + +def run(args, parser): + version = selected_version(args, parser) + explicit_value = args.addr4 if version == 4 else args.addr6 + key = args.key if args.key is not None else get_key(args.keyfile, args.record) + if explicit_value is not None: + address = parse_ip(explicit_value, version) + update_he(args.record, key, address, timeout=args.timeout) + return + + with state_lock(args.state_file): + address = discover_address(args.check_url, version, timeout=args.timeout) + log.debug("discovered IPv%s address %s", version, address) + state = read_state(args.state_file) + record_state = state.get(args.record) + if not isinstance(record_state, dict): + record_state = {} + previous = record_state.get(str(version)) + if previous == str(address): + log.debug("address is unchanged; skipping HE update") + return + update_he(args.record, key, address, timeout=args.timeout) + state[args.record] = record_state + record_state[str(version)] = str(address) + write_state(args.state_file, state) + + +def main(argv=None): + parser = make_parser() + args = parser.parse_args(argv) + log.setLevel(logging.DEBUG if args.debug else logging.ERROR) + try: + run(args, parser) + except (OSError, RuntimeError, ValueError, configparser.Error) as exc: + log.error("%s", exc) + return 1 + return 0 + + +log = logging.getLogger("he-dyndns") +if not log.handlers: + handler = logging.StreamHandler() + handler.setFormatter(logging.Formatter("%(name)s: %(levelname)s: %(message)s")) + log.addHandler(handler) -def build_ip(ip_string): - try: - ip = ipaddress.ip_address(ip_string) - except ValueError: - log.error("manually specified address is invalid format: %s" % ip_string) - sys.exit(1) - except: - log.error(str(e)) - sys.exit(1) - - return ip - -def haveIPv6(): - haveIPv6 = True - try: - s = socket.socket(socket.AF_INET6) - s.connect((HE_DNS_API_HOST,80)) - except socket.gaierror as e: - log.debug("Exception {}".format(e.__class__)) - log.error("Testing IPv6 connection: " + str(e)) - sys.exit(1) - except OSError as e: - log.debug("Exception {}".format(e.__class__)) - log.debug(str(e)) - haveIPv6 = False - except TimeoutError as e: - log.error("Testing IPv6 connection: " + str(e)) - sys.exit(1) - except Exception as e: - log.debug("Exception {}".format(e.__class__)) - log.error(str(e)) - haveIPv6 = False - return haveIPv6 - -def getKey(keyfile, record): - if not os.path.exists(keyfile): - raise Exception("missing keyfile {}".format(keyfile)) - - config = configparser.ConfigParser() - config.read(keyfile) - - if not "keys" in config: - raise Exception("keyfile lacks [keys] section") - - if not record in config["keys"]: - raise Exception("keyfile has no entry for {}".format(record)) - - return config["keys"][record] - -def main(): - ap = argparse.ArgumentParser(description="Update Hurricane Electric DNS dynamic record") - ap.add_argument("record", help="DNS record to update") - ap.add_argument("--v4", help="Update IPv4 A record (default)", action="store_true", default=True) - ap.add_argument("--v6", help="Update IPv6 AAAA record", action="store_true", default=False) - ap.add_argument("--addr4", help="Update A record with provided IP rather than detected IP") - ap.add_argument("--addr6", help="Update AAAA record with provided IP rather than detected IP") - ap.add_argument("--keyfile", help="Alternate location for key config file (default /etc/he-dns-secret.conf)") - ap.add_argument("--key", help="HE DDNS key for record (by default read from /etc/he-dns-secret.conf or --keyfile)") - ap.add_argument("--debug", help="Enable debug logging", action="store_true", default=False) - args = ap.parse_args() - - if args.debug: - log.setLevel(logging.DEBUG) - else: - log.setLevel(logging.ERROR) - - if args.keyfile: - log.debug("KEYFILE: {}".format(args.keyfile)) - keyfile = args.keyfile - else: - log.debug("KEYFILE: /etc/he-dyndns.conf") - keyfile = "/etc/he-dyndns.conf" - - if args.addr4: - ip = build_ip(args.addr4) - - if args.addr6: - ip = build_ip(args.addr6) - - if args.v6: - if not haveIPv6 and not args.addr6: - log.error("no IPv6 detected and --v6 specified without --addr6 (try --debug?)") - sys.exit(1) - - try: - - if args.key: - log.debug("--key override; ignore --kefile") - apikey = args.key - else: - apikey = getKey(keyfile, args.record) - - if args.v6: - ans = dns.resolver.resolve(HE_DNS_API_HOST, "AAAA")[0] - log.debug("DNS resolved: {}".format(ans.to_text())) - apihost = "[{}]".format(ans.to_text()) - else: - ans = dns.resolver.resolve(HE_DNS_API_HOST, "A")[0] - log.debug("DNS resolved: {}".format(ans.to_text())) - apihost = ans.to_text() - - # build the API URL to be called - url = "http://{}/nic/update?hostname={}".format(apihost, args.record) - if args.addr4 or args.addr6: - url += "&myip={}".format(ip) - log.debug("API request URL: " + url) - - # make the HTTP request - authstr = base64.b64encode(bytes("%s:%s" % ( args.record, apikey ), "ascii")) - log.debug("auth string: %s" % authstr.decode("utf-8")) - req = urllib.request.Request(url) - req.add_header("Host", HE_DNS_API_HOST) - req.add_header("Authorization", "Basic %s" % authstr.decode("utf-8")) - with urllib.request.urlopen(req) as response: - this_page = response.read() - log.debug("HE response: " + this_page.decode("utf-8")) - res = this_page.decode("utf-8").split()[0] - - if res == "good": - return True - elif res == "badauth": - raise Exception("HE badauth: wrong key or record not configured for dynamic updates") - elif res == "nochg": - return True - else: - raise Exception("HE returned {}: unknown response code".format(res)) - - except dns.resolver.NXDOMAIN as e: - log.debug("Exception class: {}".format(e.__class__)) - log.error(str(e)) - sys.exit(1) - - except Exception as e: - log.debug("Exception class: {}".format(e.__class__)) - log.error(str(e)) - sys.exit(1) if __name__ == "__main__": - log = logging.getLogger("he-dyndns") - lh = logging.StreamHandler() - lf = logging.Formatter(fmt='%(name)s: %(levelname)s: %(message)s') - lh.setFormatter(lf) - log.addHandler(lh) - main() - sys.exit(0) + sys.exit(main()) diff --git a/ip-echo-daemon b/ip-echo-daemon new file mode 100755 index 0000000..5b66801 --- /dev/null +++ b/ip-echo-daemon @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 + +import argparse +import ipaddress +import logging +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + +log = logging.getLogger("ip-echo-daemon") + + +def proxied_address(peer_address, forwarded_address): + peer = ipaddress.ip_address(peer_address) + if not peer.is_loopback: + raise ValueError("proxy connection did not originate on loopback") + if forwarded_address is None: + raise ValueError("missing X-Real-IP header") + return ipaddress.ip_address(forwarded_address.strip()) + + +class AddressHandler(BaseHTTPRequestHandler): + server_version = "ip-echo-daemon" + sys_version = "" + + def do_GET(self): + if self.path != "/": + self.send_error(404) + return + try: + address = proxied_address(self.client_address[0], self.headers.get("X-Real-IP")) + except ValueError as exc: + self.send_error(400, str(exc)) + return + body = (str(address) + "\n").encode("ascii") + self.send_response(200) + self.send_header("Content-Type", "text/plain; charset=us-ascii") + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(body) + + def do_HEAD(self): + self.send_error(405) + + def log_message(self, fmt, *args): + log.info("%s - %s", self.client_address[0], fmt % args) + + +def make_server(address, port): + return ThreadingHTTPServer((address, port), AddressHandler) + + +def main(): + parser = argparse.ArgumentParser( + description="Return the client IP address supplied by a local reverse proxy" + ) + parser.add_argument("--listen", default="127.0.0.1") + parser.add_argument("--port", type=int, default=8080) + parser.add_argument("--debug", action="store_true") + args = parser.parse_args() + logging.basicConfig( + level=logging.DEBUG if args.debug else logging.INFO, + format="%(name)s: %(levelname)s: %(message)s", + ) + server = make_server(args.listen, args.port) + log.info("listening on %s:%s", args.listen, args.port) + try: + server.serve_forever() + except KeyboardInterrupt: + pass + finally: + server.server_close() + + +if __name__ == "__main__": + main() diff --git a/tests/test_he_dyndns.py b/tests/test_he_dyndns.py new file mode 100644 index 0000000..d839a26 --- /dev/null +++ b/tests/test_he_dyndns.py @@ -0,0 +1,129 @@ +import importlib.machinery +import importlib.util +import ipaddress +import json +import pathlib +import tempfile +import unittest +from unittest import mock + + +ROOT = pathlib.Path(__file__).resolve().parents[1] + + +def load_script(name): + loader = importlib.machinery.SourceFileLoader(name, str(ROOT / name)) + spec = importlib.util.spec_from_loader(name, loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + return module + + +he_dyndns = load_script("he-dyndns") +ip_echo = load_script("ip-echo-daemon") + + +class EchoTests(unittest.TestCase): + def test_accepts_address_from_loopback_proxy(self): + self.assertEqual( + ip_echo.proxied_address("127.0.0.1", "2001:db8::123"), + ipaddress.ip_address("2001:db8::123"), + ) + + def test_rejects_header_from_non_loopback_peer(self): + with self.assertRaisesRegex(ValueError, "loopback"): + ip_echo.proxied_address("192.0.2.10", "198.51.100.20") + + +class DiscoveryTests(unittest.TestCase): + @mock.patch.object(he_dyndns, "http_get") + def test_ipv6_discovery_pins_family_and_validates_response(self, http_get): + http_get.return_value = (200, b"2001:db8::5\n") + result = he_dyndns.discover_address("https://ip.mfamily.org/", 6) + self.assertEqual(result, ipaddress.ip_address("2001:db8::5")) + self.assertEqual(http_get.call_args.args[3], he_dyndns.socket.AF_INET6) + self.assertTrue(http_get.call_args.kwargs["use_tls"]) + + @mock.patch.object(he_dyndns, "http_get") + def test_rejects_wrong_address_family(self, http_get): + http_get.return_value = (200, b"192.0.2.1\n") + with self.assertRaisesRegex(ValueError, "IPv6"): + he_dyndns.discover_address("https://ip.mfamily.org/", 6) + + +class HeUpdateTests(unittest.TestCase): + @mock.patch.object(he_dyndns, "http_get") + def test_update_uses_family_pinned_https(self, http_get): + http_get.return_value = (200, b"good 192.0.2.9\n") + + he_dyndns.update_he( + "home.example", "secret", ipaddress.ip_address("192.0.2.9") + ) + + self.assertEqual(http_get.call_args.args[1], 443) + self.assertEqual(http_get.call_args.args[3], he_dyndns.socket.AF_INET) + self.assertTrue(http_get.call_args.kwargs["use_tls"]) + + +class StateTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.state_path = str(pathlib.Path(self.directory.name) / "state.json") + self.parser = he_dyndns.make_parser() + + def tearDown(self): + self.directory.cleanup() + + @mock.patch.object(he_dyndns, "update_he") + @mock.patch.object(he_dyndns, "discover_address") + def test_unchanged_discovered_address_skips_update(self, discover, update): + address = ipaddress.ip_address("192.0.2.44") + discover.return_value = address + he_dyndns.write_state(self.state_path, {"home.example": {"4": str(address)}}) + args = self.parser.parse_args([ + "home.example", "--key", "secret", "--state-file", self.state_path + ]) + he_dyndns.run(args, self.parser) + update.assert_not_called() + + @mock.patch.object(he_dyndns, "update_he") + @mock.patch.object(he_dyndns, "discover_address") + def test_changed_address_updates_then_writes_state(self, discover, update): + address = ipaddress.ip_address("2001:db8::44") + discover.return_value = address + args = self.parser.parse_args([ + "home.example", "--v6", "--key", "secret", + "--state-file", self.state_path, + ]) + he_dyndns.run(args, self.parser) + update.assert_called_once_with("home.example", "secret", address, timeout=10) + with open(self.state_path, encoding="utf-8") as state_file: + self.assertEqual(json.load(state_file)["home.example"]["6"], str(address)) + + @mock.patch.object(he_dyndns, "update_he") + @mock.patch.object(he_dyndns, "discover_address") + def test_failed_update_does_not_write_state(self, discover, update): + discover.return_value = ipaddress.ip_address("192.0.2.55") + update.side_effect = RuntimeError("failed") + args = self.parser.parse_args([ + "home.example", "--key", "secret", "--state-file", self.state_path + ]) + with self.assertRaisesRegex(RuntimeError, "failed"): + he_dyndns.run(args, self.parser) + self.assertFalse(pathlib.Path(self.state_path).exists()) + + @mock.patch.object(he_dyndns, "update_he") + @mock.patch.object(he_dyndns, "discover_address") + def test_explicit_address_bypasses_discovery_and_state(self, discover, update): + args = self.parser.parse_args([ + "home.example", "--addr4", "192.0.2.88", "--key", "secret", + "--state-file", self.state_path, + ]) + he_dyndns.run(args, self.parser) + discover.assert_not_called() + update.assert_called_once() + self.assertFalse(pathlib.Path(self.state_path).exists()) + + +if __name__ == "__main__": + unittest.main() |
