diff --git a/README.md b/README.md index 2a7497c..05a911b 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ The helper creates a random token, stores only its SHA-256 in the config and pri python3 ~/snap-dyndns-server/snap_dyndns_host.py user1.example.com ``` -Give the printed token to the device, for the [client](https://src.mehl.mx/mxmehl/snap-dyndns-client) it is the `hostname:token` entry shown in the output. The same command for an existing host replaces its token, and the old one stops working immediately. Use `-c` for a config in another location and `-z example.co.uk` for a new host whose INWX zone is not the last two labels of its name. Comments and the rest of the config stay untouched. The config is read on every request, so no restart is needed. +Give the printed token to the device, for the [client](https://src.mehl.mx/mxmehl/snap-dyndns-client) it is the `hostname:token` entry shown in the output. For an existing host it asks before replacing the token (`-y` skips the question), and the old token stops working immediately. Use `-c` for a config in another location and `-z example.co.uk` for a new host whose INWX zone is not the last two labels of its name. Comments and the rest of the config stay untouched. The config is read on every request, so no restart is needed. The hostname is the Basic Auth user name, the token the password. Without the helper, generate a token and hash yourself with `python3 -c 'import secrets,hashlib;t=secrets.token_urlsafe(32);print(t, hashlib.sha256(t.encode()).hexdigest())'` and add a section `[hosts."user1.example.com"]` with `token_sha256 = ""`. diff --git a/snap_dyndns_host.py b/snap_dyndns_host.py old mode 100644 new mode 100755 index 595e7be..81b9ea2 --- a/snap_dyndns_host.py +++ b/snap_dyndns_host.py @@ -40,7 +40,9 @@ def set_host(text, host, digest, zone=None): header = f'[hosts."{host}"]' start = next((i for i, line in enumerate(lines) if line.strip() == header), None) if start is None: - raise ValueError(f"cannot find the line {header} in the config, edit {host} by hand") + raise ValueError( + f"cannot find the line {header} in the config, edit {host} by hand" + ) for i in range(start + 1, len(lines)): if lines[i].lstrip().startswith("["): break @@ -63,11 +65,36 @@ def write_config(path, text): raise +def confirm(question): + """Ask on the terminal; anything but yes, including no input, means no.""" + try: + return input(question).strip().lower() in ("y", "yes") + except EOFError: + return False + + def main(argv=None): parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - parser.add_argument("hostname", help="e.g. home.example.com; an existing host gets a new token") - parser.add_argument("-c", "--config", default=DEFAULT_CONFIG, help=f"config file (default: {DEFAULT_CONFIG})") - parser.add_argument("-z", "--zone", help="INWX zone for a new host, if not the last two labels of the hostname") + parser.add_argument( + "hostname", help="e.g. home.example.com; an existing host gets a new token" + ) + parser.add_argument( + "-c", + "--config", + default=DEFAULT_CONFIG, + help=f"config file (default: {DEFAULT_CONFIG})", + ) + parser.add_argument( + "-y", + "--yes", + action="store_true", + help="replace the token of an existing host without asking", + ) + parser.add_argument( + "-z", + "--zone", + help="INWX zone for a new host, if not the last two labels of the hostname", + ) args = parser.parse_args(argv) host = args.hostname.lower() @@ -80,7 +107,15 @@ def main(argv=None): digest = hashlib.sha256(token.encode()).hexdigest() try: with open(path) as f: - new_text, created = set_host(f.read(), host, digest, args.zone) + text = f.read() + exists = host in tomllib.loads(text).get("hosts", {}) + if ( + exists + and not args.yes + and not confirm(f"{host} already exists. Replace its token? [y/N] ") + ): + sys.exit("Aborted, config unchanged") + new_text, created = set_host(text, host, digest, args.zone) tomllib.loads(new_text) # never write a config that does not parse write_config(path, new_text) except (OSError, ValueError) as e: # TOMLDecodeError is a ValueError diff --git a/test_snap_dyndns_host.py b/test_snap_dyndns_host.py index bd54aff..ed28395 100644 --- a/test_snap_dyndns_host.py +++ b/test_snap_dyndns_host.py @@ -8,6 +8,7 @@ import stat import tempfile import tomllib import unittest +from unittest import mock import snap_dyndns_host as sh @@ -31,10 +32,14 @@ token_sha256 = "bbbb" # trailing class SetHostTest(unittest.TestCase): def test_new_host_is_appended(self): - text, created = sh.set_host(CONFIG, "c.example.co.uk", "cccc", zone="example.co.uk") + text, created = sh.set_host( + CONFIG, "c.example.co.uk", "cccc", zone="example.co.uk" + ) self.assertTrue(created) hosts = tomllib.loads(text)["hosts"] - self.assertEqual(hosts["c.example.co.uk"], {"token_sha256": "cccc", "zone": "example.co.uk"}) + self.assertEqual( + hosts["c.example.co.uk"], {"token_sha256": "cccc", "zone": "example.co.uk"} + ) self.assertEqual(hosts["a.example.com"], {"token_sha256": "aaaa"}) self.assertTrue(text.startswith(CONFIG.rstrip("\n"))) @@ -42,7 +47,9 @@ class SetHostTest(unittest.TestCase): text, created = sh.set_host(CONFIG, "b.example.com", "new", None) self.assertFalse(created) parsed = tomllib.loads(text)["hosts"] - self.assertEqual(parsed["b.example.com"], {"zone": "example.com", "token_sha256": "new"}) + self.assertEqual( + parsed["b.example.com"], {"zone": "example.com", "token_sha256": "new"} + ) self.assertEqual(parsed["a.example.com"]["token_sha256"], "aaaa") self.assertIn("# keep this comment", text) @@ -56,9 +63,13 @@ class SetHostTest(unittest.TestCase): sh.set_host(CONFIG, "a.example.com", "new", zone="example.com") def test_config_without_hosts(self): - text, created = sh.set_host('[inwx]\nuser = "u"\npass = "p"', "a.example.com", "aaaa") + text, created = sh.set_host( + '[inwx]\nuser = "u"\npass = "p"', "a.example.com", "aaaa" + ) self.assertTrue(created) - self.assertEqual(tomllib.loads(text)["hosts"]["a.example.com"]["token_sha256"], "aaaa") + self.assertEqual( + tomllib.loads(text)["hosts"]["a.example.com"]["token_sha256"], "aaaa" + ) class MainTest(unittest.TestCase): @@ -85,11 +96,36 @@ class MainTest(unittest.TestCase): self.assertEqual(stored, hashlib.sha256(token.encode()).hexdigest()) def test_rotation_changes_the_hash_and_keeps_permissions(self): - self.run_main("a.example.com") + self.run_main("a.example.com", "--yes") with open(self.path, "rb") as f: - self.assertNotEqual(tomllib.load(f)["hosts"]["a.example.com"]["token_sha256"], "aaaa") + self.assertNotEqual( + tomllib.load(f)["hosts"]["a.example.com"]["token_sha256"], "aaaa" + ) self.assertEqual(stat.S_IMODE(os.stat(self.path).st_mode), 0o600) + def test_existing_host_asks_and_replaces_on_yes(self): + with mock.patch("builtins.input", return_value="y") as ask: + self.run_main("a.example.com") + self.assertIn("already exists", ask.call_args.args[0]) + self.assertNotEqual(self.stored_hash("a.example.com"), "aaaa") + + def test_existing_host_is_kept_on_no_or_without_input(self): + for answer in ("", "n", EOFError()): + with ( + mock.patch("builtins.input", side_effect=[answer]), + self.assertRaises(SystemExit), + ): + self.run_main("a.example.com") + self.assertEqual(self.stored_hash("a.example.com"), "aaaa") + + def test_new_host_does_not_ask(self): + with mock.patch("builtins.input", side_effect=AssertionError("asked")): + self.run_main("fresh.example.com") + + def stored_hash(self, host): + with open(self.path, "rb") as f: + return tomllib.load(f)["hosts"][host]["token_sha256"] + def test_invalid_hostname_leaves_config_untouched(self): for bad in ('x"] \n[evil', "no_dots", "a..b", "-a.example.com"): with self.assertRaises(SystemExit):