aboutsummaryrefslogtreecommitdiffstats
path: root/tests/test_init.py
blob: f1b20f86b45031f718156b9ff3989fade238ccdc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# 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}",
            )