# 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) # Never talk to the real INWX from tests patcher = mock.patch.object( sh, "ensure_record", return_value=(True, {"content": "192.0.2.1", "ttl": 300}), ) self.ensure = patcher.start() self.addCleanup(patcher.stop) 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_creates_missing_record_with_default_ttl(self): output = self.run_main("fresh.example.com") args = self.ensure.call_args.args self.assertEqual(args[1:], ("example.com", "fresh.example.com", "A", 300)) self.assertIn("DNS: created A record fresh.example.com", output) def test_types_ttl_and_zone_are_passed_on(self): self.run_main( "fresh.example.co.uk", "-z", "example.co.uk", "-t", "a,aaaa", "--ttl", "60" ) calls = [c.args[1:] for c in self.ensure.call_args_list] self.assertEqual( calls, [ ("example.co.uk", "fresh.example.co.uk", "A", 60), ("example.co.uk", "fresh.example.co.uk", "AAAA", 60), ], ) def test_existing_record_is_reported_not_changed(self): self.ensure.return_value = (False, {"content": "1.2.3.4", "ttl": 3600}) output = self.run_main("fresh.example.com") self.assertIn("A record fresh.example.com exists (1.2.3.4, TTL 3600)", output) def test_zone_of_existing_host_comes_from_config(self): self.run_main("b.example.com", "--yes") self.assertEqual(self.ensure.call_args.args[1], "example.com") def test_no_dns_skips_inwx(self): self.run_main("fresh.example.com", "--no-dns") self.ensure.assert_not_called() def test_inwx_failure_changes_nothing(self): self.ensure.side_effect = sh.InwxError( "account.login: 2200 Authentication error" ) with self.assertRaises(SystemExit) as ctx: self.run_main("fresh.example.com") self.assertIn("Nothing was changed", str(ctx.exception)) with open(self.path) as f: self.assertEqual(f.read(), CONFIG) def test_invalid_record_type(self): with self.assertRaises(SystemExit): self.run_main("fresh.example.com", "-t", "MX") self.ensure.assert_not_called() 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()