feat!: complete refactoring of server #1

Merged
mxmehl merged 10 commits from v2 into master 2026-10-22 15:35:55 +02:00
3 changed files with 84 additions and 13 deletions
Showing only changes of commit 8bc1cfaf27 - Show all commits

No files matched your search

+1 -1
View File
@@ -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 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 = "<hash>"`. 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 = "<hash>"`.
Regular → Executable
+40 -5
View File
@@ -40,7 +40,9 @@ def set_host(text, host, digest, zone=None):
header = f'[hosts."{host}"]' header = f'[hosts."{host}"]'
start = next((i for i, line in enumerate(lines) if line.strip() == header), None) start = next((i for i, line in enumerate(lines) if line.strip() == header), None)
if start is 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)): for i in range(start + 1, len(lines)):
if lines[i].lstrip().startswith("["): if lines[i].lstrip().startswith("["):
break break
@@ -63,11 +65,36 @@ def write_config(path, text):
raise 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): def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) 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(
parser.add_argument("-c", "--config", default=DEFAULT_CONFIG, help=f"config file (default: {DEFAULT_CONFIG})") "hostname", help="e.g. home.example.com; an existing host gets a new token"
parser.add_argument("-z", "--zone", help="INWX zone for a new host, if not the last two labels of the hostname") )
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) args = parser.parse_args(argv)
host = args.hostname.lower() host = args.hostname.lower()
@@ -80,7 +107,15 @@ def main(argv=None):
digest = hashlib.sha256(token.encode()).hexdigest() digest = hashlib.sha256(token.encode()).hexdigest()
try: try:
with open(path) as f: 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 tomllib.loads(new_text) # never write a config that does not parse
write_config(path, new_text) write_config(path, new_text)
except (OSError, ValueError) as e: # TOMLDecodeError is a ValueError except (OSError, ValueError) as e: # TOMLDecodeError is a ValueError
+43 -7
View File
@@ -8,6 +8,7 @@ import stat
import tempfile import tempfile
import tomllib import tomllib
import unittest import unittest
from unittest import mock
import snap_dyndns_host as sh import snap_dyndns_host as sh
@@ -31,10 +32,14 @@ token_sha256 = "bbbb" # trailing
class SetHostTest(unittest.TestCase): class SetHostTest(unittest.TestCase):
def test_new_host_is_appended(self): 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) self.assertTrue(created)
hosts = tomllib.loads(text)["hosts"] 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.assertEqual(hosts["a.example.com"], {"token_sha256": "aaaa"})
self.assertTrue(text.startswith(CONFIG.rstrip("\n"))) 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) text, created = sh.set_host(CONFIG, "b.example.com", "new", None)
self.assertFalse(created) self.assertFalse(created)
parsed = tomllib.loads(text)["hosts"] 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.assertEqual(parsed["a.example.com"]["token_sha256"], "aaaa")
self.assertIn("# keep this comment", text) 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") sh.set_host(CONFIG, "a.example.com", "new", zone="example.com")
def test_config_without_hosts(self): 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.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): class MainTest(unittest.TestCase):
@@ -85,11 +96,36 @@ class MainTest(unittest.TestCase):
self.assertEqual(stored, hashlib.sha256(token.encode()).hexdigest()) self.assertEqual(stored, hashlib.sha256(token.encode()).hexdigest())
def test_rotation_changes_the_hash_and_keeps_permissions(self): 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: 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) 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): def test_invalid_hostname_leaves_config_untouched(self):
for bad in ('x"] \n[evil', "no_dots", "a..b", "-a.example.com"): for bad in ('x"] \n[evil', "no_dots", "a..b", "-a.example.com"):
with self.assertRaises(SystemExit): with self.assertRaises(SystemExit):