okami.mom/strata

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

Niko1221Merge f-ok-refused 5fdb9aa4a into f-own-intc7ec1e8fe

main
9.3 KiB191 linesraw
1"""netpolicy rule 4b (owner 11-11, "Remembering refused update feeds on Windows": Ok): a feed host that REFUSED the connection is remembered
2on disk for 6 hours, in Strata's own state folder, host:port and the time only.  Only automatic reads (`automatic=True`) read the note; a read
3the person asked for by name ignores it; the first answer from the host removes it; a damaged or unreadable note is no note, without a message.
4
5Windows needs about 2.0 s to report a refused connection (measured 2.03-2.04 s on the owner PC, owner-20261110-2003-a8da); a launch of a model
6with its own engine shape read the feed on every start, so a PC behind a dead proxy paid that on every start.  Every test here works in a test
7HOME (conftest.py and launch_support.Home redirect the state folder) or on a note file of its own."""
8
9from __future__ import annotations
10
11import contextlib
12import io
13import json
14import os
15import tempfile
16import time
17import unittest
18import urllib.request
19from pathlib import Path
20from unittest import mock
21
22from strata_control import netpolicy, paths, transfer
23from tests.terminal.launch_support import Home
24from tests.terminal.test_netpolicy import refused_port
25
26
27class Clock:
28    def __init__(self, t: float = 1_000_000.0):
29        self.t = t
30
31    def __call__(self) -> float:
32        return self.t
33
34
35def note_in(folder: Path, clock=None) -> netpolicy.RefusalNote:
36    return netpolicy.RefusalNote(path=folder / "net" / netpolicy.REFUSED_NOTE_NAME, clock=clock or Clock())
37
38
39class Base(unittest.TestCase):
40    def setUp(self):
41        t = tempfile.TemporaryDirectory(prefix="strata-refused-")
42        self.addCleanup(t.cleanup)
43        self.dir = Path(t.name)
44        self.clock = Clock()
45        self.note = note_in(self.dir, self.clock)
46        netpolicy.HOSTS.forget()
47        self.addCleanup(netpolicy.HOSTS.forget)
48
49
50def refuse(request, timeout):
51    raise ConnectionRefusedError(10061 if os.name == "nt" else 111, "refused")
52
53
54class TheNote(Base):
55    def test_the_values_of_the_rule(self):
56        self.assertEqual(netpolicy.REFUSED_NOTE_S, 6 * 3600)
57        with Home():                                         # the default note lives in Strata's own state folder (read when used)
58            self.assertEqual(netpolicy.REFUSALS.path(), paths.state_base() / "net" / "refused-hosts.json")
59            base = Path(os.environ["LOCALAPPDATA" if os.name == "nt" else "XDG_STATE_HOME"])
60            self.assertEqual(netpolicy.REFUSALS.path().parent.parent.parent, base, "inside the test HOME's state folder")
61
62    def test_host_port_and_time_only_and_six_hours(self):
63        self.note.remember("github.com:443")
64        self.assertEqual(json.loads(self.note.path().read_text(encoding="utf-8")), {"github.com:443": self.clock.t})
65        self.assertTrue(self.note.refused_recently("github.com:443"))
66        self.assertFalse(self.note.refused_recently("github.com:8443"), "per host AND port")
67        self.clock.t += 6 * 3600 - 1
68        self.assertTrue(self.note.refused_recently("github.com:443"))
69        self.clock.t += 1
70        self.assertFalse(self.note.refused_recently("github.com:443"), "after 6 hours the host is asked again")
71        self.note.remember("example.org:443")                # writing drops the expired entries
72        self.assertEqual(sorted(json.loads(self.note.path().read_text(encoding="utf-8"))), ["example.org:443"])
73
74    def test_a_clock_that_went_back_does_not_keep_a_host_forever(self):
75        self.note.remember("github.com:443")
76        self.clock.t -= 3600
77        self.assertFalse(self.note.refused_recently("github.com:443"))
78
79    def test_forget_removes_the_host_and_the_empty_note(self):
80        self.note.remember("a:1")
81        self.note.remember("b:2")
82        self.note.forget("a:1")
83        self.assertEqual(sorted(json.loads(self.note.path().read_text(encoding="utf-8"))), ["b:2"])
84        self.note.forget("b:2")
85        self.assertFalse(self.note.path().exists())
86
87    def test_forget_without_a_note_writes_nothing(self):
88        self.note.forget("a:1")
89        self.assertFalse(self.note.path().parent.exists())
90
91    def test_a_damaged_or_unreadable_note_is_no_note_and_says_nothing(self):
92        p = self.note.path()
93        p.parent.mkdir(parents=True)
94        for text in ("{not json", "[1, 2]", '{"a:1": "yesterday"}', '{"a:1": true}', "\xff\xfe".encode("latin-1").decode("latin-1")):
95            p.write_text(text, encoding="latin-1")
96            out, err = io.StringIO(), io.StringIO()
97            with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
98                self.assertFalse(self.note.refused_recently("a:1"), text)
99                self.note.remember("c:3")                    # a damaged note is replaced by a good one
100                self.assertTrue(self.note.refused_recently("c:3"))
101            self.assertEqual((out.getvalue(), err.getvalue()), ("", ""))
102        p.unlink()
103        p.mkdir()                                            # a folder where the note should be: cannot be read or written
104        self.assertFalse(self.note.refused_recently("a:1"))
105        self.note.remember("a:1")                            # silently not kept
106        self.note.forget("a:1")
107        self.assertFalse(self.note.refused_recently("a:1"))
108
109
110class OpenUrl(Base):
111    def test_a_refusal_is_noted_and_the_next_automatic_read_does_not_connect(self):
112        with self.assertRaises(netpolicy.NetFailure) as cm:
113            netpolicy.open_url(refuse, "https://feed.example:443/strata-feed.json", refusals=self.note, automatic=True)
114        self.assertEqual(cm.exception.kind, "offline")
115        self.assertTrue(self.note.refused_recently("feed.example:443"))
116        calls = []
117
118        def counting(request, timeout):
119            calls.append(1)
120            return b"answer"
121        with self.assertRaises(netpolicy.NetFailure) as cm:
122            netpolicy.open_url(counting, "https://feed.example:443/strata-feed.json", refusals=self.note, automatic=True)
123        self.assertEqual((cm.exception.kind, calls), ("offline", []), "the automatic read failed at once, without a connection")
124        self.assertIn("could not connect", str(cm.exception), "the same offline words as a refusal")
125
126    def test_a_read_asked_for_by_name_ignores_the_note_and_its_answer_removes_the_host(self):
127        self.note.remember("feed.example:443")
128        calls = []
129
130        def answer(request, timeout):
131            calls.append(1)
132            return b"answer"
133        self.assertEqual(netpolicy.open_url(answer, "https://feed.example:443/strata-feed.json", refusals=self.note), b"answer")
134        self.assertEqual(calls, [1])
135        self.assertFalse(self.note.refused_recently("feed.example:443"), "the first success removes the host")
136        self.assertEqual(netpolicy.open_url(answer, "https://feed.example:443/strata-feed.json", refusals=self.note, automatic=True), b"answer")
137
138    def test_an_http_answer_also_removes_the_host(self):
139        import urllib.error
140        self.note.remember("feed.example:443")
141
142        def missing(request, timeout):
143            raise urllib.error.HTTPError(str(request), 404, "Not Found", {}, None)
144        with self.assertRaises(urllib.error.HTTPError):
145            netpolicy.open_url(missing, "https://feed.example:443/x", refusals=self.note)
146        self.assertFalse(self.note.refused_recently("feed.example:443"))
147
148    def test_only_a_refusal_is_noted(self):
149        import socket
150
151        def no_name(request, timeout):
152            raise socket.gaierror(-2, "Name or service not known")
153
154        def timeout(request, timeout):
155            raise TimeoutError("timed out")
156        for fn in (no_name, timeout):
157            with self.assertRaises(netpolicy.NetFailure):
158                netpolicy.open_url(fn, "https://feed.example:443/x", refusals=self.note, limits=(0.01,), gap=0, sleep=lambda s: None)
159        self.assertFalse(self.note.path().exists(), "no DNS answer and a timeout are not refusals (the first fails at once anyway)")
160
161    def test_a_refusal_through_urllib_is_seen(self):
162        import urllib.error
163        self.assertTrue(netpolicy.refused(urllib.error.URLError(ConnectionRefusedError(111, "refused"))))
164        self.assertFalse(netpolicy.refused(urllib.error.URLError("timed out")))
165
166
167class RealSocket(Base):
168    def test_a_refused_loopback_port_costs_its_wait_once_then_nothing(self):
169        url = f"http://127.0.0.1:{refused_port()}/strata-feed.json"
170        with mock.patch.object(netpolicy, "REFUSALS", self.note):
171            t0 = time.monotonic()
172            with self.assertRaises(transfer.Unreachable):
173                transfer.read_small(url, timeout=5, automatic=True)
174            first = time.monotonic() - t0
175            t0 = time.monotonic()
176            with self.assertRaises(transfer.Unreachable):
177                transfer.read_small(url, timeout=5, automatic=True)
178            second = time.monotonic() - t0
179            t0 = time.monotonic()
180            with self.assertRaises(transfer.Unreachable):
181                transfer.read_small(url, timeout=5)              # asked for by name: it tries again
182            explicit = time.monotonic() - t0
183        print(f"refused loopback: first {first:.3f} s, second (noted) {second:.3f} s, explicit {explicit:.3f} s")
184        self.assertLess(second, 0.2)
185        if os.name == "nt":                                      # Windows reports a refusal after about 2 s: the note saves exactly that
186            self.assertGreater(first, 1.0)
187            self.assertGreater(explicit, 1.0)
188
189
190if __name__ == "__main__":
191    unittest.main()