tests: a lab guard reads the host interfaces once, not at each refusal
A gateway of the lab refused the browser's CONNECTs to the DoH the core declares (162.159.61.4:443) 117 and 254 times in two single tests, 2296 in one leg, and every refusal read the host interfaces again with psutil in the pytest process that runs the core's UDP measurement. LabGuard now reads the interfaces once, when it is made, and judges every destination against that reading: a refusal is a synchronous list append. The decision-time reading (and its read_errors path) is gone; the reason of a refusal says the reading was made when the gateway was made. test_a_guard_reads_the_interfaces_once_however_many_destinations_it_refuses counts the readings of a fake psutil: 1 for 40 refusals and 3 decisions (44 on the old code).
This commit is contained in:
1 parent
3b094de0a7
commit
b1673988b4
2 files changed
+58
-46
No files matched your search
+19
-30
@@ -40,8 +40,9 @@ browser behind a gateway makes background requests of its own (a name of the ven
|
||||
destination is REFUSED, never forwarded (a CONNECT is answered with reply 2, "not allowed"; a datagram is dropped), and RECORDED
|
||||
(:class:`LabGuard`: the time since the gateway started, the SOCKS5 address type, the destination as it was received - the NAME for type 3 -, the
|
||||
port, the protocol, ``tcp`` or ``udp``, and the REASON: which rule refused it, the lab's or the narrower one of a subclass). The interfaces of this
|
||||
host are read when the guard is made (``psutil.net_if_addrs``, written once in the record with how they were read) and again at each decision that
|
||||
needs them; a reading that fails RAISES (``_witness.HostInterfacesUnreadable``), it is never an empty list. The record is always written, when the gateway is closed, under
|
||||
host are read ONCE, when the guard is made (``psutil.net_if_addrs``, written once in the record with how they were read), and every decision of that
|
||||
guard is taken against that reading: a browser that retries a refused destination hundreds of times costs a list append each, not a reading of the
|
||||
host; a reading that fails RAISES (``_witness.HostInterfacesUnreadable``), it is never an empty list. The record is always written, when the gateway is closed, under
|
||||
``$RUNNER_TEMP/invpw-evidence/<gateway>/<pid>-<ms>/refused-destinations.json`` (the folder the e2e jobs upload; off a runner nothing is
|
||||
written), so that a reader sees what the browser asked for besides what the test drives. There is no option that reopens it. A subclass can only
|
||||
narrow it (:meth:`Gateway._admits`); the destinations it serves itself (the fake STUN server, the page of ``WEB_NAME``, the exit questions) are
|
||||
@@ -192,11 +193,11 @@ def _how_own_interfaces_are_read() -> str:
|
||||
return how_host_interfaces_are_read()
|
||||
|
||||
|
||||
def lab_refusal(host: str) -> Optional[str]:
|
||||
def lab_refusal(host: str, own: Optional[Set[str]] = None) -> Optional[str]:
|
||||
"""None when ``host`` (an address, or a name as a SOCKS5 client sent it) is the lab's: loopback, a documentation range, an address of one of this host's
|
||||
own interfaces, or ``localhost``; otherwise WHY it is not, one sentence. Any other NAME is not the lab's: nothing here resolves a name for the internet's
|
||||
sake, and the question would leave the machine. The interfaces are read (:func:`_own_addresses`) only for an address outside loopback and the
|
||||
documentation ranges, and a reading that fails raises."""
|
||||
sake, and the question would leave the machine. ``own`` is the addresses of this host's interfaces as a guard read them when it was made; None: they
|
||||
are read now (:func:`_own_addresses`), only for an address outside loopback and the documentation ranges, and a reading that fails raises."""
|
||||
text = host.strip().strip("[]").split("%", 1)[0].rstrip(".").lower()
|
||||
try:
|
||||
address = ipaddress.ip_address(text)
|
||||
@@ -209,11 +210,12 @@ def lab_refusal(host: str) -> Optional[str]:
|
||||
address = mapped
|
||||
if any(address in network for network in LAB_NETWORKS):
|
||||
return None
|
||||
own = _own_addresses()
|
||||
read_at = "read at the decision" if own is None else "read when the gateway was made"
|
||||
own = _own_addresses() if own is None else own
|
||||
if address.compressed in own:
|
||||
return None
|
||||
return ("%s is not loopback, not in a documentation range and not one of the %d addresses of this host's interfaces read at the decision"
|
||||
% (address.compressed, len(own)))
|
||||
return ("%s is not loopback, not in a documentation range and not one of the %d addresses of this host's interfaces %s"
|
||||
% (address.compressed, len(own), read_at))
|
||||
|
||||
|
||||
def is_lab_destination(host: str) -> bool:
|
||||
@@ -230,8 +232,8 @@ class LabGuard:
|
||||
``destination`` (as received), ``port``, ``protocol`` and ``reason`` (the rule that refused it). :meth:`write_evidence` leaves them, always, under
|
||||
``$RUNNER_TEMP/invpw-evidence/<name>/``, with the interfaces of this host as the guard read them when it was made (:attr:`host_interfaces`) and how.
|
||||
|
||||
The interfaces are read when the guard is made: a reading that fails raises there (the gateway is not made). A reading at a decision that fails refuses
|
||||
the destination with that failure as its reason, is listed in :attr:`read_errors`, and :meth:`write_evidence` (the close of the gateway) raises it."""
|
||||
The interfaces are read ONCE, when the guard is made (a reading that fails raises there: the gateway is not made), and every decision is taken against
|
||||
that reading: a refusal is a list append, synchronous, with no reading of the host."""
|
||||
|
||||
def __init__(self, name: str, t0: Optional[float] = None):
|
||||
self.name = name
|
||||
@@ -241,20 +243,13 @@ class LabGuard:
|
||||
#: The addresses of each interface of this host, read when the guard was made (raises if they cannot be read), and how they were read.
|
||||
self.host_interfaces: Dict[str, List[str]] = _own_interfaces()
|
||||
self.host_interfaces_read_by = _how_own_interfaces_are_read()
|
||||
#: Every reading of the interfaces at a decision that failed (the destination was refused with it as the reason).
|
||||
self.read_errors: List[str] = []
|
||||
#: The same addresses as one set: what every decision of this guard is judged against.
|
||||
self._own = {address for addresses in self.host_interfaces.values() for address in addresses}
|
||||
self._lock = threading.Lock()
|
||||
self._written = False
|
||||
|
||||
def admits(self, host: str, port: int, atyp: int, protocol: str, target: Optional[Tuple[str, int]] = None) -> bool:
|
||||
try:
|
||||
reason = lab_refusal(host if target is None else target[0])
|
||||
except Exception as exc: # the interfaces could not be read at the decision: refused, said, and raised at the close
|
||||
error = "the interfaces of this host could not be read at the decision: %s: %s" % (type(exc).__name__, exc)
|
||||
with self._lock:
|
||||
self.read_errors.append(error)
|
||||
self.refuse(host, port, atyp, protocol, reason=error)
|
||||
return False
|
||||
reason = lab_refusal(host if target is None else target[0], self._own)
|
||||
if reason is None:
|
||||
return True
|
||||
if target is not None and (target[0], target[1]) != (host, port):
|
||||
@@ -275,17 +270,15 @@ class LabGuard:
|
||||
return [(r["destination"], r["port"]) for r in self.records if protocol is None or r["protocol"] == protocol]
|
||||
|
||||
def evidence(self, extra: Optional[dict] = None) -> dict:
|
||||
"""The record as it is written: the refusals, the interfaces of this host as read when the guard was made and how, the failed readings."""
|
||||
"""The record as it is written: the refusals, the interfaces of this host as read when the guard was made and how."""
|
||||
with self._lock:
|
||||
records, errors = list(self.records), list(self.read_errors)
|
||||
records = list(self.records)
|
||||
return dict({"gateway": self.name, "refused": records,
|
||||
"host_interfaces": {"read_by": self.host_interfaces_read_by, "read_at": "when the gateway was made",
|
||||
"interfaces": self.host_interfaces},
|
||||
"host_interfaces_read_errors": errors}, **(extra or {}))
|
||||
"interfaces": self.host_interfaces}}, **(extra or {}))
|
||||
|
||||
def write_evidence(self, extra: Optional[dict] = None) -> Optional[pathlib.Path]:
|
||||
"""Write the record, once (a gateway may be closed twice): the file written, or None off a runner (no ``$RUNNER_TEMP``) or when already written.
|
||||
Then, the first time, it RAISES if a reading of the interfaces failed at a decision (:attr:`read_errors`), on a runner or not."""
|
||||
"""Write the record, once (a gateway may be closed twice): the file written, or None off a runner (no ``$RUNNER_TEMP``) or when already written."""
|
||||
runner_temp = os.environ.get("RUNNER_TEMP")
|
||||
with self._lock:
|
||||
if self._written:
|
||||
@@ -297,10 +290,6 @@ class LabGuard:
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
path = folder / "refused-destinations.json"
|
||||
path.write_text(json.dumps(self.evidence(extra), indent=2), encoding="utf-8")
|
||||
if self.read_errors:
|
||||
from _witness import HostInterfacesUnreadable
|
||||
|
||||
raise HostInterfacesUnreadable("gateway %s: %s" % (self.name, "; ".join(self.read_errors)))
|
||||
return path
|
||||
|
||||
|
||||
|
||||
@@ -18,6 +18,8 @@ a verdict would then depend on whether the runner reaches them. What this holds,
|
||||
* the interfaces of this host: read by ``psutil.net_if_addrs`` in every form it gives (a zone id, upper case, an IPv4-mapped address, an interface with
|
||||
no IPv4); a reading that fails (``psutil`` raises or does not import, ``_witness`` does not import, an entry is not an address, no address at all)
|
||||
RAISES, in the gateway and in the witness, and is never an empty list (an empty list made every address of this host "not the lab's", silently);
|
||||
a guard reads them ONCE, when it is made, and judges every destination against that reading (a browser behind a gateway retried a refused DoH
|
||||
hundreds of times per test, and each refusal read the interfaces of the host again in the process of the measurement);
|
||||
* every refusal says its reason (the lab's rule, or the narrower one of the gateway: the DoH gateway refuses an address of this host by its own rule),
|
||||
and the record says once, per gateway, the interfaces it read and how.
|
||||
|
||||
@@ -512,7 +514,7 @@ def test_the_forms_psutil_gives_on_windows_are_read_as_the_addresses_they_are_an
|
||||
assert written["host_interfaces"]["interfaces"] == {
|
||||
"Ethernet": ["10.1.0.52", "fe80::1c2d:3a5b"], "Loopback Pseudo-Interface 1": ["::1", "127.0.0.1"],
|
||||
"vEthernet (nat)": ["10.1.0.53"], "Teredo Tunneling Pseudo-Interface": ["2001:0:2851:782c::1"]}
|
||||
assert "psutil.net_if_addrs()" in written["host_interfaces"]["read_by"] and written["host_interfaces_read_errors"] == []
|
||||
assert "psutil.net_if_addrs()" in written["host_interfaces"]["read_by"]
|
||||
|
||||
|
||||
def test_every_refusal_says_its_reason_and_the_doh_gateway_refuses_an_address_of_this_host_by_its_own_rule(monkeypatch):
|
||||
@@ -536,7 +538,7 @@ def test_every_refusal_says_its_reason_and_the_doh_gateway_refuses_an_address_of
|
||||
s.close()
|
||||
assert code == 2
|
||||
assert [(r["destination"], r["reason"]) for r in gateway.guard.records] == [
|
||||
(PUBLIC_V4, "8.8.8.8 is not loopback, not in a documentation range and not one of the 2 addresses of this host's interfaces read at the decision"),
|
||||
(PUBLIC_V4, "8.8.8.8 is not loopback, not in a documentation range and not one of the 2 addresses of this host's interfaces read when the gateway was made"),
|
||||
(NAME, "a name that is not localhost: a gateway of the tests resolves no name, the question would leave the machine")]
|
||||
assert is_lab_destination("10.1.0.52")
|
||||
written = gateway.guard.evidence()
|
||||
@@ -544,23 +546,44 @@ def test_every_refusal_says_its_reason_and_the_doh_gateway_refuses_an_address_of
|
||||
r["reason"] for r in gateway.guard.records]
|
||||
|
||||
|
||||
def test_a_reading_that_fails_at_a_decision_refuses_says_so_and_the_close_raises(monkeypatch):
|
||||
from _witness import HostInterfacesUnreadable
|
||||
class _CountingPsutil(_FakePsutil):
|
||||
"""A ``psutil`` that counts how many times the interfaces were listed."""
|
||||
|
||||
monkeypatch.setattr(servers, "_own_interfaces", lambda: {"lo": ["127.0.0.1"]})
|
||||
gateway = coherent()
|
||||
def __init__(self, table):
|
||||
super().__init__(table)
|
||||
self.readings = 0
|
||||
|
||||
def broken():
|
||||
raise HostInterfacesUnreadable("psutil.net_if_addrs() failed")
|
||||
def net_if_addrs(self):
|
||||
self.readings += 1
|
||||
return super().net_if_addrs()
|
||||
|
||||
monkeypatch.setattr(servers, "_own_interfaces", broken)
|
||||
s, code = _connect(gateway.port, "10.1.0.52", 443, V4)
|
||||
s.close()
|
||||
assert code == 2
|
||||
assert "could not be read at the decision" in gateway.guard.records[0]["reason"] and gateway.guard.read_errors
|
||||
with pytest.raises(HostInterfacesUnreadable):
|
||||
gateway.close()
|
||||
gateway.close() # once: the second close neither writes nor raises
|
||||
|
||||
#: The address of the DoH the core declares (``network.trr.bootstrapAddr``): a gateway of the lab refuses it, and the browser behind it retries.
|
||||
DECLARED_DOH = "162.159.61.4"
|
||||
|
||||
|
||||
def test_a_guard_reads_the_interfaces_once_however_many_destinations_it_refuses(monkeypatch):
|
||||
"""A gateway of the gate refused 117 and 254 CONNECTs to the declared DoH in two single tests (2296 in one leg): each refusal read the interfaces of
|
||||
the host again (``psutil.net_if_addrs``) in the process that runs the core's UDP measurement. The guard reads them once, when it is made, and judges
|
||||
every destination against that reading, so N refusals are N records and one reading, and the reason says when the reading was made."""
|
||||
psutil = _CountingPsutil(WINDOWS_LIKE)
|
||||
_real_interfaces(monkeypatch, psutil)
|
||||
refusals = 40
|
||||
with coherent() as gateway:
|
||||
assert psutil.readings == 1, "the guard reads the interfaces when it is made: %d readings" % psutil.readings
|
||||
gateway._open_upstream = lambda target: pytest.fail("the gateway opened a connection to %s" % (target,))
|
||||
for _ in range(refusals):
|
||||
s, code = _connect(gateway.port, DECLARED_DOH, 443, V4)
|
||||
s.close()
|
||||
assert code == 2
|
||||
assert gateway.guard.refused("tcp") == [(DECLARED_DOH, 443)] * refusals
|
||||
# an address of an interface is still the lab's, judged against the same reading; a datagram is judged the same way
|
||||
assert gateway.guard.admits("10.1.0.52", 443, V4, "tcp") and gateway.guard.admits("fe80::1c2d:3a5b", 443, V6, "udp")
|
||||
assert not gateway.guard.admits(PUBLIC_V4, 443, V4, "udp")
|
||||
assert psutil.readings == 1, "the interfaces of the host were read %d times for %d refusals and 3 decisions; once, when the guard was " "made, is the rule" % (psutil.readings, refusals)
|
||||
assert {r["reason"] for r in gateway.guard.records if r["destination"] == DECLARED_DOH} == {
|
||||
"162.159.61.4 is not loopback, not in a documentation range and not one of the 6 addresses of this host's interfaces read when the gateway"
|
||||
" was made"}
|
||||
|
||||
|
||||
def test_a_witness_that_cannot_read_the_interfaces_again_keeps_the_arrival_and_raises_when_read(monkeypatch):
|
||||
|
||||
Reference in new issue
Block a user