# SPDX-FileCopyrightText: 2016 Max Mehl # SPDX-License-Identifier: AGPL-3.0-or-later import contextlib import hashlib import io import os import stat import tempfile import tomllib import unittest from unittest import mock import snap_dyndns_host as sh CONFIG = """\ # my comment state_file = "/tmp/state.json" [inwx] user = "u" pass = "p" [hosts."a.example.com"] token_sha256 = "aaaa" # keep this comment [hosts."b.example.com"] zone = "example.com" 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" ) 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["a.example.com"], {"token_sha256": "aaaa"}) self.assertTrue(text.startswith(CONFIG.rstrip("\n"))) def test_existing_host_gets_new_hash_only(self): 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["a.example.com"]["token_sha256"], "aaaa") self.assertIn("# keep this comment", text) def test_existing_host_with_unusual_header_is_refused(self): odd = CONFIG.replace('[hosts."a.example.com"]', "[hosts.'a.example.com']") with self.assertRaises(ValueError): sh.set_host(odd, "a.example.com", "new") def test_zone_for_existing_host_is_refused(self): with self.assertRaises(ValueError): 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" ) self.assertTrue(created) self.assertEqual( tomllib.loads(text)["hosts"]["a.example.com"]["token_sha256"], "aaaa" ) class MainTest(unittest.TestCase): def setUp(self): tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) self.path = os.path.join(tmp.name, "config.toml") with open(self.path, "w") as f: f.write(CONFIG) os.chmod(self.path, 0o600) def run_main(self, *args): out = io.StringIO() with contextlib.redirect_stdout(out): sh.main(["-c", self.path, *args]) return out.getvalue() def test_printed_token_matches_stored_hash(self): output = self.run_main("New.Example.com") token = output.split("Token (shown only once): ")[1].split("\n")[0] self.assertIn(f"Client entry for HOSTS: new.example.com:{token}", output) with open(self.path, "rb") as f: stored = tomllib.load(f)["hosts"]["new.example.com"]["token_sha256"] self.assertEqual(stored, hashlib.sha256(token.encode()).hexdigest()) def test_rotation_changes_the_hash_and_keeps_permissions(self): 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.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): self.run_main(bad) with open(self.path) as f: self.assertEqual(f.read(), CONFIG) def test_missing_config(self): os.unlink(self.path) with self.assertRaises(SystemExit): self.run_main("a.example.com") if __name__ == "__main__": unittest.main()