# Copyright (C) 2026 Danilo M. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """Tests for the first-run config builder in abusectl.init.""" import ipaddress import pathlib import tempfile import tomllib import unittest from abusectl import config, init class TestBuildConfig(unittest.TestCase): def test_the_answers_become_readable_toml(self): text = init.build({"trusted_relays": ["192.0.2.0/24"], "cases": "~/c"}) parsed = tomllib.loads(text) self.assertEqual(parsed["general"]["trusted_relays"], ["192.0.2.0/24"]) self.assertEqual(parsed["general"]["cases"], "~/c") def test_a_skipped_answer_is_absent_not_empty(self): # An empty string reads as configured-and-broken later on. text = init.build({"trusted_relays": ["192.0.2.0/24"], "cases": ""}) self.assertNotIn("cases", tomllib.loads(text)["general"]) def test_a_malformed_relay_is_rejected(self): with self.assertRaises(ValueError): init.build({"trusted_relays": ["nonsense"]}) def test_no_relays_at_all_is_rejected(self): with self.assertRaises(ValueError): init.build({"trusted_relays": []}) def test_the_result_loads_back_through_config(self): with tempfile.TemporaryDirectory() as tmp: path = pathlib.Path(tmp) / "config.toml" path.write_text( init.build({"trusted_relays": ["192.0.2.0/24"]}), encoding="utf-8" ) self.assertEqual(config.load(path).trusted_relays, ["192.0.2.0/24"]) def test_a_quote_in_an_answer_cannot_break_out_of_the_toml(self): # The cases path reaches the file as a quoted string, so a value # containing a quote must not be able to close it early. with self.assertRaises(ValueError): init.build({"trusted_relays": ["192.0.2.0/24"], "cases": 'x" \ntrusted_relays = ["0.0.0.0/0"]\n#'}) class TestReporterSection(unittest.TestCase): def test_the_identity_becomes_a_reporter_table(self): text = init.build({ "trusted_relays": ["192.0.2.0/24"], "reporter_name": "A Reporter", "reporter_org": "Example Ltd", "reporter_email": "abuse@example.org", }) parsed = tomllib.loads(text) self.assertEqual(parsed["reporter"], { "name": "A Reporter", "org": "Example Ltd", "email": "abuse@example.org", }) def test_a_fully_skipped_identity_emits_no_table_at_all(self): # Not an empty [reporter]: an empty table reads as configured, and # the reader would then report an identity of nothing rather than # saying plainly that none is set. text = init.build({ "trusted_relays": ["192.0.2.0/24"], "reporter_name": "", "reporter_org": "", "reporter_email": "", }) self.assertNotIn("[reporter]", text) self.assertNotIn("reporter", tomllib.loads(text)) def test_a_skipped_answer_is_absent_not_empty(self): # Same rule as the cases path: "" reads as configured-and-broken. text = init.build({ "trusted_relays": ["192.0.2.0/24"], "reporter_name": "A Reporter", "reporter_org": "", "reporter_email": " ", }) reporter = tomllib.loads(text)["reporter"] self.assertEqual(reporter, {"name": "A Reporter"}) def test_values_are_written_stripped(self): # config.load() strips on read, so writing unstripped would make the # file disagree with what every consumer sees. text = init.build({ "trusted_relays": ["192.0.2.0/24"], "reporter_name": " A Reporter ", }) self.assertEqual(tomllib.loads(text)["reporter"]["name"], "A Reporter") def test_a_quote_in_an_identity_cannot_break_out_of_the_toml(self): with self.assertRaises(ValueError): init.build({ "trusted_relays": ["192.0.2.0/24"], "reporter_name": 'x"\nemail = "attacker@example.invalid"', }) def test_the_identity_loads_back_through_config(self): # The seam report.build() consumes: what init writes must arrive as # the dict shape the reader hands over, keys and all. with tempfile.TemporaryDirectory() as tmp: path = pathlib.Path(tmp) / "config.toml" path.write_text(init.build({ "trusted_relays": ["192.0.2.0/24"], "reporter_name": "A Reporter", "reporter_org": "Example Ltd", "reporter_email": "abuse@example.org", }), encoding="utf-8") self.assertEqual(config.load(path).reporter, { "name": "A Reporter", "org": "Example Ltd", "email": "abuse@example.org", }) def test_a_partial_identity_loads_back_with_only_what_was_given(self): with tempfile.TemporaryDirectory() as tmp: path = pathlib.Path(tmp) / "config.toml" path.write_text(init.build({ "trusted_relays": ["192.0.2.0/24"], "reporter_email": "abuse@example.org", }), encoding="utf-8") self.assertEqual(config.load(path).reporter, {"email": "abuse@example.org"}) class TestReporterCarryAcross(unittest.TestCase): def test_an_identity_set_by_hand_survives_a_relays_only_rewrite(self): # AGENTS.md: sections build() does not produce are carried across # verbatim. Skipping all three answers must not delete an identity # the user set earlier; there would be no warning that it went. with tempfile.TemporaryDirectory() as tmp: path = pathlib.Path(tmp) / "config.toml" path.write_text( '[general]\ntrusted_relays = ["10.0.0.0/8"]\n\n' '[reporter]\nname = "A Reporter"\nemail = "abuse@example.org"\n', encoding="utf-8", ) init.write(path, {"trusted_relays": ["192.0.2.0/24"]}, force=True) self.assertEqual(config.load(path).reporter, {"name": "A Reporter", "email": "abuse@example.org"}) def test_a_new_identity_replaces_the_old_one_without_duplicating_it(self): # A section the builder DOES produce must not also be carried across: # two [reporter] tables in one file is not merely untidy, tomllib # refuses the whole file and the config becomes unreadable. with tempfile.TemporaryDirectory() as tmp: path = pathlib.Path(tmp) / "config.toml" path.write_text( '[general]\ntrusted_relays = ["10.0.0.0/8"]\n\n' '[reporter]\nname = "Old Name"\n', encoding="utf-8", ) init.write(path, { "trusted_relays": ["192.0.2.0/24"], "reporter_name": "New Name", }, force=True) self.assertEqual(path.read_text().count("[reporter]"), 1) self.assertEqual(config.load(path).reporter, {"name": "New Name"}) def test_an_unrelated_section_still_survives_alongside_an_identity(self): with tempfile.TemporaryDirectory() as tmp: path = pathlib.Path(tmp) / "config.toml" path.write_text( '[general]\ntrusted_relays = ["10.0.0.0/8"]\n\n' '[reporter]\nname = "Old Name"\n\n' '[misp]\napi_key = "kept"\n', encoding="utf-8", ) init.write(path, { "trusted_relays": ["192.0.2.0/24"], "reporter_name": "New Name", }, force=True) rewritten = path.read_text() self.assertIn("kept", rewritten) self.assertNotIn("Old Name", rewritten) self.assertEqual(config.load(path).reporter, {"name": "New Name"}) class TestProviderTable(unittest.TestCase): def test_a_known_provider_resolves_to_ranges(self): self.assertTrue(init.provider_relays("gmail")) def test_lookup_is_case_insensitive(self): self.assertEqual(init.provider_relays("Gmail"), init.provider_relays("gmail")) def test_an_unknown_provider_returns_nothing(self): self.assertEqual(init.provider_relays("nosuchprovider"), []) def test_every_shipped_range_is_a_valid_network(self): for name, ranges in init.PROVIDERS.items(): self.assertTrue(ranges, f"{name} has no ranges") for entry in ranges: ipaddress.ip_network(entry, strict=False) def test_a_provider_result_survives_the_builder(self): # The table feeds the builder directly, so its entries must satisfy # the same validation a typed answer does. text = init.build({"trusted_relays": init.provider_relays("gmail")}) self.assertIn("74.125.0.0/16", text) class TestSampleChain(unittest.TestCase): def test_hops_are_offered_for_picking(self): raw = ( pathlib.Path(__file__).parent / "fixtures" / "simple.eml" ).read_bytes() hops = init.hops_from_sample(raw) self.assertEqual(hops, ["192.0.2.11", "203.0.113.42"]) class TestWriteGuard(unittest.TestCase): def test_writing_over_an_existing_config_refuses_without_force(self): with tempfile.TemporaryDirectory() as tmp: path = pathlib.Path(tmp) / "config.toml" path.write_text("[general]\n", encoding="utf-8") with self.assertRaises(FileExistsError): init.write(path, {"trusted_relays": ["192.0.2.0/24"]}) def test_force_overwrites_and_leaves_a_backup(self): with tempfile.TemporaryDirectory() as tmp: path = pathlib.Path(tmp) / "config.toml" path.write_text('[general]\ntrusted_relays = ["10.0.0.0/8"]\n', encoding="utf-8") init.write(path, {"trusted_relays": ["192.0.2.0/24"]}, force=True) self.assertIn("192.0.2.0/24", path.read_text()) backups = list(pathlib.Path(tmp).glob("config.toml.bak-*")) self.assertEqual(len(backups), 1) self.assertIn("10.0.0.0/8", backups[0].read_text()) def test_a_backup_is_not_world_readable_either(self): # It holds the same secrets the config does. with tempfile.TemporaryDirectory() as tmp: path = pathlib.Path(tmp) / "config.toml" path.write_text("[general]\n", encoding="utf-8") init.write(path, {"trusted_relays": ["192.0.2.0/24"]}, force=True) backup = next(pathlib.Path(tmp).glob("config.toml.bak-*")) self.assertEqual(backup.stat().st_mode & 0o077, 0) def test_an_unsupplied_section_survives_a_rewrite(self): # Once the config holds a MISP key, an init that only sets the relays # must not silently discard it. The backup makes that recoverable; # not losing it is better. with tempfile.TemporaryDirectory() as tmp: path = pathlib.Path(tmp) / "config.toml" path.write_text( '[general]\ntrusted_relays = ["10.0.0.0/8"]\n\n' '[misp]\nurl = "https://misp.example.invalid"\n' 'api_key = "kept"\n', encoding="utf-8", ) init.write(path, {"trusted_relays": ["192.0.2.0/24"]}, force=True) rewritten = path.read_text() self.assertIn("192.0.2.0/24", rewritten) self.assertIn("[misp]", rewritten) self.assertIn("kept", rewritten) def test_a_rewrite_still_loads(self): # Preserving sections verbatim must not produce a file the reader # then chokes on. with tempfile.TemporaryDirectory() as tmp: path = pathlib.Path(tmp) / "config.toml" path.write_text( '[general]\ntrusted_relays = ["10.0.0.0/8"]\n\n' '[misp]\napi_key = "kept"\n', encoding="utf-8", ) init.write(path, {"trusted_relays": ["192.0.2.0/24"]}, force=True) self.assertEqual(config.load(path).trusted_relays, ["192.0.2.0/24"]) def test_a_written_config_is_not_world_readable(self): # It will hold API keys as later parts land. with tempfile.TemporaryDirectory() as tmp: path = pathlib.Path(tmp) / "config.toml" init.write(path, {"trusted_relays": ["192.0.2.0/24"]}) self.assertEqual(path.stat().st_mode & 0o077, 0) def test_a_first_write_creates_no_backup(self): with tempfile.TemporaryDirectory() as tmp: path = pathlib.Path(tmp) / "config.toml" init.write(path, {"trusted_relays": ["192.0.2.0/24"]}) self.assertEqual(list(pathlib.Path(tmp).glob("*.bak-*")), []) def test_existing_summary_names_sections_without_showing_values(self): # The file holds API keys. Echoing a secret to the terminal to ask # about overwriting it is a poor trade. with tempfile.TemporaryDirectory() as tmp: path = pathlib.Path(tmp) / "config.toml" path.write_text( '[general]\ntrusted_relays = ["10.0.0.0/8"]\n\n' '[misp]\napi_key = "topsecret"\n', encoding="utf-8", ) summary = init.existing_summary(path) self.assertIn("misp", summary) self.assertIn("api_key", summary) self.assertNotIn("topsecret", summary) if __name__ == "__main__": unittest.main() class TestRepeatedInit(unittest.TestCase): """build()'s own preamble and footer must not accrete across rewrites. Found by hand test, not by the suite: a single rewrite looks fine, and the file still parses, so only the third run makes it obvious. The carried text is build()'s, not the user's, so preserving it duplicated the header once per run. """ def test_the_preamble_and_footer_survive_four_rewrites_exactly_once(self): answers = {"trusted_relays": ["192.0.2.0/24"], "cases": ""} with tempfile.TemporaryDirectory() as tmp: path = pathlib.Path(tmp) / "config.toml" init.write(path, answers) path.write_text( path.read_text() + '\n[misp]\napi_key = "SECRET"\n' ) for _ in range(3): init.write(path, answers, force=True) text = path.read_text() self.assertEqual(text.count("# abusectl configuration."), 1) self.assertEqual(text.count("# Later parts of abusectl"), 1) # The unknown section still rides across untouched. self.assertEqual(tomllib.loads(text)["misp"]["api_key"], "SECRET") def test_the_footer_survives_an_identity_answered_then_skipped(self): # The sequence a hand test actually hit, and the one the first fix # missed: answering the identity, then re-running and skipping it, # leaves [reporter] PRESERVED rather than rendered, so the footer # trailing it rides across while this run emits its own. relays = {"trusted_relays": ["192.0.2.0/24"], "cases": ""} answered = dict(relays, reporter_name="A Reporter", reporter_org="example.org", reporter_email="r@example.org") with tempfile.TemporaryDirectory() as tmp: path = pathlib.Path(tmp) / "config.toml" init.write(path, answered) init.write(path, relays, force=True) text = path.read_text() self.assertEqual(text.count("# Later parts of abusectl"), 1) self.assertEqual(text.count("# abusectl configuration."), 1) self.assertEqual( tomllib.loads(text)["reporter"]["name"], "A Reporter" ) def test_the_footer_stays_at_the_end_after_a_preserved_section(self): # It says further sections are added below it, so a preserved table # appended underneath made it a comment about nothing. relays = {"trusted_relays": ["192.0.2.0/24"], "cases": ""} answered = dict(relays, reporter_name="A Reporter", reporter_email="r@example.org") with tempfile.TemporaryDirectory() as tmp: path = pathlib.Path(tmp) / "config.toml" init.write(path, answered) init.write(path, relays, force=True) text = path.read_text().rstrip("\n") self.assertTrue( text.endswith("# [reporting] - abuse-desk reporting defaults"), f"footer is not last:\n{text}", )