okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
5.5 KiB114 linesraw
1"""#3722: HTTPS downloads check the server against the operating system's certificates (truststore), fall back to certifi, and a
2certificate that still fails gives a plain explanation, never the raw urlopen text and never a way to skip the check."""
3
4import ssl
5import sys
6import types
7import unittest
8import urllib.error
9from pathlib import Path
10from unittest import mock
11
12ROOT = Path(__file__).resolve().parents[2]
13sys.path.insert(0, str(ROOT))
14from strata_control import tls  # noqa: E402
15
16RAW = ("<urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate "
17       "(_ssl.c:1010)>")
18
19
20def cert_error():
21    inner = ssl.SSLCertVerificationError(1, "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate")
22    return urllib.error.URLError(inner)
23
24
25class Install(unittest.TestCase):
26    def setUp(self):
27        self.mode = tls.mode
28        self.context = ssl._create_default_https_context
29        tls.mode = None
30        self.addCleanup(self.restore)
31
32    def restore(self):
33        tls.mode = self.mode
34        ssl._create_default_https_context = self.context
35
36    def test_truststore_is_used_when_present(self):
37        fake = types.SimpleNamespace(calls=0)
38        fake.inject_into_ssl = lambda: setattr(fake, "calls", fake.calls + 1)
39        with mock.patch.dict(sys.modules, {"truststore": fake}):
40            self.assertEqual(tls.install(), "truststore")
41            self.assertEqual(tls.install(), "truststore")          # again: nothing more happens
42        self.assertEqual(fake.calls, 1)
43
44    def test_certifi_is_the_fallback_when_truststore_is_missing(self):
45        seen = {}
46        fake_certifi = types.SimpleNamespace(where=lambda: "bundle.pem")
47        with mock.patch.dict(sys.modules, {"truststore": None, "certifi": fake_certifi}), \
48                mock.patch.object(ssl, "create_default_context", lambda cafile=None, **k: seen.setdefault("cafile", cafile)):
49            self.assertEqual(tls.install(), "certifi")
50            ssl._create_default_https_context()
51        self.assertEqual(seen["cafile"], "bundle.pem")
52
53    def test_python_default_stays_when_neither_exists(self):
54        with mock.patch.dict(sys.modules, {"truststore": None, "certifi": None}):
55            self.assertEqual(tls.install(), "default")
56        self.assertIs(ssl._create_default_https_context, self.context)
57
58    def test_the_pins_name_truststore_in_requirements_and_every_lock(self):
59        self.assertIn("truststore==", (ROOT / "requirements.txt").read_text())
60        for lock in (ROOT / "packaging" / "locks").glob("runtime-*-cp312.txt"):
61            text = lock.read_text()
62            self.assertRegex(text, r"truststore==\S+ \\r?\n\s+--hash=sha256:[0-9a-f]{64}", lock.name)
63            self.assertIn("certifi==", text)                       # the fallback stays
64
65
66class Plain(unittest.TestCase):
67    def test_a_failed_certificate_is_recognised_however_it_is_wrapped(self):
68        self.assertTrue(tls.is_certificate_error(cert_error()))
69        self.assertTrue(tls.is_certificate_error(OSError(RAW)))
70        wrapped = RuntimeError("x")
71        wrapped.__cause__ = cert_error()
72        self.assertTrue(tls.is_certificate_error(wrapped))
73        self.assertFalse(tls.is_certificate_error(urllib.error.URLError(ConnectionRefusedError())))
74        self.assertFalse(tls.is_certificate_error(None))
75
76    def test_the_message_is_plain_and_never_offers_to_skip_the_check(self):
77        text = tls.explain("github.com")
78        for word in ("github.com", "antivirus", "proxy", "date and time", "Windows Update"):
79            self.assertIn(word, text)
80        for raw in ("urlopen", "CERTIFICATE_VERIFY_FAILED", "_ssl.c", "issuer"):
81            self.assertNotIn(raw, text)
82        self.assertRegex(text, r"will not skip the check")
83        self.assertNotRegex(text.lower(), r"verify\s*=\s*false|insecure|disable (the )?verification|turn off (the )?(certificate|verification)")
84
85    def test_setup_urlopen_raises_the_plain_problem(self):
86        import setup
87        request = types.SimpleNamespace(full_url="https://github.com/x/y")
88        with mock.patch.object(setup.acquisition, "require", lambda *a, **k: None), \
89                mock.patch.object(setup.netpolicy, "urlopen", side_effect=cert_error()):
90            with self.assertRaises(tls.CertificateProblem) as cm:
91                setup._urlopen(request)
92        self.assertIn("github.com", str(cm.exception))
93        self.assertNotIn("CERTIFICATE_VERIFY_FAILED", str(cm.exception))
94
95    def test_setup_urlopen_leaves_other_errors_alone(self):
96        import setup
97        refused = urllib.error.URLError(ConnectionRefusedError())
98        with mock.patch.object(setup.acquisition, "require", lambda *a, **k: None), \
99                mock.patch.object(setup.netpolicy, "urlopen", side_effect=refused):
100            with self.assertRaises(urllib.error.URLError):
101                setup._urlopen(types.SimpleNamespace(full_url="https://github.com/x"))
102
103    def test_the_update_reader_gives_the_plain_message(self):
104        from strata_control import transfer
105        with mock.patch.object(transfer, "check_url_policy", lambda url: None), \
106                mock.patch.object(transfer._opener, "open", side_effect=cert_error()):
107            with self.assertRaises(transfer.TransferError) as cm:
108                transfer.read_small("https://updates.example.org/feed.json")
109        self.assertIn("antivirus", str(cm.exception))
110        self.assertNotIn("urlopen", str(cm.exception))
111
112
113if __name__ == "__main__":
114    unittest.main()