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
6.0 KiB135 linesraw
1"""The network guard of conftest.py (lane NET): it refuses what is not this computer, passes three named things (a UDP connect, this computer's own host
2name, the RFC 5737 documentation addresses), counts every use of them per test, and nothing else gets through. These tests call the guard's own
3functions with the real connect replaced, so no packet is ever sent; each one that makes the guard refuse clears the guard's list before it ends
4(the autouse fixture would otherwise fail the test for the reach it was checking)."""
5
6from __future__ import annotations
7
8import os
9import socket
10import unittest
11from unittest import mock
12
13
14class _Live:
15    """The root conftest.py's own namespace, the live one (several conftest.py files share the module name "conftest", so it is found through the
16    function the guard put on socket.socket.connect, not by an import)."""
17
18    def __init__(self, names: dict):
19        object.__setattr__(self, "_names", names)
20
21    def __getattr__(self, name):
22        try:
23            return self._names[name]
24        except KeyError:
25            raise AttributeError(name) from None
26
27    def __setattr__(self, name, value):
28        self._names[name] = value
29
30    def __delattr__(self, name):
31        del self._names[name]
32
33
34assert socket.socket.connect.__name__ == "_guarded_connect", "the network guard of conftest.py is not installed"
35guard = _Live(socket.socket.connect.__globals__)
36
37
38def tcp() -> socket.socket:
39    return socket.socket(socket.AF_INET, socket.SOCK_STREAM)
40
41
42def udp() -> socket.socket:
43    return socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
44
45
46class Guarded(unittest.TestCase):
47    """The guard is on for these tests whatever the run says: a run with STRATA_TEST_ALLOW_NETWORK=1 (a live run, or a check that sets it) switches it
48    off for the others, and these tests are about the guard itself."""
49
50    def setUp(self):
51        p = mock.patch.dict(os.environ)
52        p.start()
53        self.addCleanup(p.stop)
54        os.environ.pop("STRATA_TEST_ALLOW_NETWORK", None)
55
56
57class Refused(Guarded):
58    def tearDown(self):
59        del guard._reached[:]                                  # (the refusals checked here are not this test's failure)
60
61    def test_a_tcp_connect_to_an_address_outside_the_allowances_is_refused(self):
62        for host in ("203.0.114.1", "192.0.3.1", "198.51.101.1", "10.255.255.254", "8.8.8.8", "93.184.216.34"):
63            with tcp() as s, mock.patch.object(guard, "_real_connect", side_effect=AssertionError("sent")):
64                with self.assertRaises(ConnectionRefusedError, msg=host):
65                    s.connect((host, 80))
66        self.assertEqual(len(guard._reached), 6)
67
68    def test_a_real_host_name_is_refused(self):
69        for host in ("github.com", "huggingface.co", "example.com", "strata-feed.invalid"):
70            with self.assertRaises(socket.gaierror, msg=host):
71                socket.getaddrinfo(host, 443)
72        self.assertEqual(len(guard._reached), 4)
73
74    def test_a_name_that_only_looks_like_this_computers_is_refused(self):
75        with self.assertRaises(socket.gaierror):
76            socket.getaddrinfo(guard._OWN_NAME + ".example.com", 80)
77
78    def test_the_failure_says_where_it_came_from(self):
79        with self.assertRaises(socket.gaierror):
80            socket.getaddrinfo("github.com", 443)
81        self.assertRegex(guard._reached[-1], r"^github\.com \[test_net_guard\.py:\d+\]$")
82
83    def test_a_tcp_connect_with_the_ipv6_documentation_range_is_not_covered(self):
84        with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s, mock.patch.object(guard, "_real_connect", side_effect=AssertionError("sent")):
85            with self.assertRaises(ConnectionRefusedError):
86                s.connect(("2001:db8::1", 80, 0, 0))             # (only the three IPv4 ranges are allowed)
87
88
89class Allowed(Guarded):
90    def setUp(self):
91        super().setUp()
92        self.before = len(guard._allowed)
93
94    def used(self):
95        return guard._allowed[self.before:]
96
97    def test_loopback_is_not_counted_at_all(self):
98        with tcp() as s, mock.patch.object(guard, "_real_connect", return_value=None):
99            s.connect(("127.0.0.1", 9))
100        socket.getaddrinfo("localhost", 80)
101        self.assertEqual(self.used(), [])
102
103    def test_a_udp_connect_passes_and_is_counted(self):
104        with udp() as s, mock.patch.object(guard, "_real_connect", return_value=None):
105            s.connect(("10.255.255.255", 1))
106        self.assertEqual([(w, a) for _t, w, a in self.used()], [("(a) UDP connect", "10.255.255.255:1")])
107        self.assertTrue(self.used()[0][0].endswith("::Allowed::test_a_udp_connect_passes_and_is_counted"), self.used())
108
109    def test_this_computers_own_name_passes_and_is_counted(self):
110        with mock.patch.object(guard, "_real_getaddrinfo", return_value=[]):
111            socket.getaddrinfo(socket.gethostname(), 0)
112        self.assertEqual([(w, a.lower()) for _t, w, a in self.used()], [("(b) own host name", guard._OWN_NAME)])
113
114    def test_the_three_documentation_ranges_pass_and_are_counted(self):
115        for host in ("192.0.2.1", "198.51.100.7", "203.0.113.1"):
116            with tcp() as s, mock.patch.object(guard, "_real_connect", return_value=None):
117                s.connect((host, 8080))
118        self.assertEqual([(w, a) for _t, w, a in self.used()],
119                         [("(c) documentation address", "192.0.2.1:8080"), ("(c) documentation address", "198.51.100.7:8080"),
120                          ("(c) documentation address", "203.0.113.1:8080")])
121
122
123class OptOut(Guarded):
124    def test_a_live_test_that_sets_the_variable_is_let_through_and_nothing_is_counted(self):
125        os.environ["STRATA_TEST_ALLOW_NETWORK"] = "1"
126        before = (len(guard._reached), len(guard._allowed))
127        with tcp() as s, mock.patch.object(guard, "_real_connect", return_value=None):
128            s.connect(("93.184.216.34", 80))
129        with mock.patch.object(guard, "_real_getaddrinfo", return_value=[]):
130            socket.getaddrinfo("github.com", 443)
131        self.assertEqual((len(guard._reached), len(guard._allowed)), before)
132
133
134if __name__ == "__main__":
135    unittest.main()