ci: the network A/B oracle, the same journey on the lab with the published engine and with a candidate, every leaf of what the wire carried compared
tests/_wire_capture.py reads what a client puts on the wire, with the standard library, hyperframe/h2 and aioquic: the TLS ClientHello (MSG_PEEK until the whole record is buffered, then the same socket goes to ssl; GREASE is one word, the random, the session id, key share bytes and PSK identities are dropped), the HTTP/2 frames (SETTINGS in order, WINDOW_UPDATE, PRIORITY, PRIORITY_UPDATE, the pseudo-header order of each request), HTTP/1.1 request heads as written, and an HTTP/3 client (QUIC transport parameters in order, the SETTINGS frame, the header order). WireServer serves one HTTPS site on TCP (h1 or h2 by ALPN) and QUIC on one port. scripts/ci_ab_network.py runs the P4 journey, an HTTPS page on each protocol, an HTTP/3 page, a WebRTC page (STUN and TURN through the relay) and two idle launches through a coherent SOCKS5 gateway with the fake DoH, the witness and the watcher, writes a normalised transcript per engine, and compares two transcripts leaf by leaf (path and both values). A direct connection on either side is red by itself; the leaves that differ between two runs of one engine live in ci/ab-network-volatile.json (empty until the A/A measures them; an entry that matches no leaf is stale and red). --a-a runs the published engine twice: a difference there is a broken control (exit 2), and with a candidate the A/A runs first. tests/test_ab_network.py, tests/test_wire_capture.py and tests/test_wire_capture_quic.py hold the comparator, the normalisation, the lab and the parsers to known inputs, no browser. tests/test_ab_network_e2e.py runs the A/A on a pull request (evidence under RUNNER_TEMP/invpw-evidence/ab-network) and the A/A then the A/B with a candidate.
This commit is contained in:
1 parent
050dbb159f
commit
9cd828654f
7 files changed
+3100
No files matched your search
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"format": "ab-network-volatile/1",
|
||||
"about": "The leaves of the network transcript that differ between two runs of ONE engine (the A/A of scripts/ci_ab_network.py). Each entry: `pattern` (fnmatch over the leaf path seeds/<seed>/<category>/...), `reason` (why that leaf is noise), `aa_run` (the A/A run that proved it). Born from the evidence of the A/A, never written ahead of it. It may only shrink: an entry that matches no leaf of a run is red as stale.",
|
||||
"entries": []
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,798 @@
|
||||
"""What a client puts on the wire, read by a server of the lab: the TLS ClientHello, the HTTP/2 frames, the HTTP/1.1 request heads in wire order, and
|
||||
what an HTTP/3 client says (QUIC transport parameters, the SETTINGS frame, the header order). No browser in here: every parser takes bytes, and the
|
||||
unit tests (``test_wire_capture.py``, ``test_wire_capture_quic.py``) feed them a client of Python's ``ssl``, the ``h2`` library and ``aioquic``.
|
||||
|
||||
The use: the network A/B oracle (``scripts/ci_ab_network.py``) runs the same journey with two engines and compares what these servers saw, leaf by leaf.
|
||||
|
||||
* :func:`parse_client_hello` reads the record of a ClientHello with the standard library only: record and handshake version, the cipher suites in order,
|
||||
the compression methods, the extensions in the order they were sent, and what is inside each of the known ones (supported_groups, signature_algorithms,
|
||||
ALPN, key_share GROUPS, psk_key_exchange_modes, supported_versions, record_size_limit, ec_point_formats, ...). A GREASE value is written ``"GREASE"``.
|
||||
What is random or secret per connection is NOT kept: the random, the session id, the bytes of a key share, the PSK identities and their ages, the
|
||||
ECH config id, the encapsulated key. Only their lengths stay (a length is the shape of the hello, not a value of it).
|
||||
* :func:`peek_client_hello` reads that record off a socket with ``MSG_PEEK`` until the whole record is buffered, so the same socket can then be handed to
|
||||
``ssl`` as if nothing had been read (:func:`accept_with_hello`).
|
||||
* :class:`FrameTap` reads the HTTP/2 frames of a connection from the raw bytes (``hyperframe``, which ``h2`` is made of): SETTINGS ids and values in order,
|
||||
the WINDOW_UPDATEs, PRIORITY and PRIORITY_UPDATE, the priority fields of a HEADERS. :class:`H2Connection` is the server side (``h2``): it answers the
|
||||
requests and writes down, per request, the pseudo-header order and every header name and value in the order they arrived.
|
||||
* :class:`Http1Parser` keeps the request line and the header lines as they were written (the case, the order, the empty values); :func:`serve_http1` is
|
||||
the server side, and the parser alone is what a tee in front of another server uses.
|
||||
* :class:`WireServer` is one address and one port: TCP with TLS (HTTP/2 or HTTP/1.1 by the ALPN it offers) and, when asked, QUIC (HTTP/3 with
|
||||
``aioquic``) on the same number, each connection written down.
|
||||
|
||||
Nothing here waits on a clock: a peek that is short of bytes is a poll with a deadline (a safety net, not a verdict), and every other wait is a blocking read.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
import socketserver
|
||||
import ssl
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, List, Optional, Tuple
|
||||
|
||||
#: The longest ClientHello record a peek waits for. A hello with a post-quantum key share and an ECH payload is about 2 KB; 16 KB is the limit of a record.
|
||||
MAX_HELLO_RECORD = 16384 + 5
|
||||
#: The deadline of a peek, in seconds. A safety net: a client that sent half a hello and stopped, not a measure of anything.
|
||||
PEEK_DEADLINE_S = 30.0
|
||||
|
||||
GREASE = "GREASE"
|
||||
|
||||
EXTENSION_NAMES = {
|
||||
0: "server_name", 1: "max_fragment_length", 5: "status_request", 10: "supported_groups", 11: "ec_point_formats", 13: "signature_algorithms",
|
||||
14: "use_srtp", 15: "heartbeat", 16: "alpn", 18: "signed_certificate_timestamp", 21: "padding", 22: "encrypt_then_mac", 23: "extended_master_secret",
|
||||
27: "compress_certificate", 28: "record_size_limit", 34: "delegated_credentials", 35: "session_ticket", 41: "pre_shared_key", 42: "early_data",
|
||||
43: "supported_versions", 44: "cookie", 45: "psk_key_exchange_modes", 49: "post_handshake_auth", 50: "signature_algorithms_cert", 51: "key_share",
|
||||
17513: "application_settings", 17613: "application_settings_new", 65037: "encrypted_client_hello", 65281: "renegotiation_info",
|
||||
}
|
||||
|
||||
#: The QUIC transport parameters by id (RFC 9000 18.2 and the extensions seen in browsers).
|
||||
QUIC_PARAMETER_NAMES = {
|
||||
0x00: "original_destination_connection_id", 0x01: "max_idle_timeout", 0x02: "stateless_reset_token", 0x03: "max_udp_payload_size",
|
||||
0x04: "initial_max_data", 0x05: "initial_max_stream_data_bidi_local", 0x06: "initial_max_stream_data_bidi_remote",
|
||||
0x07: "initial_max_stream_data_uni", 0x08: "initial_max_streams_bidi", 0x09: "initial_max_streams_uni", 0x0A: "ack_delay_exponent",
|
||||
0x0B: "max_ack_delay", 0x0C: "disable_active_migration", 0x0D: "preferred_address", 0x0E: "active_connection_id_limit",
|
||||
0x0F: "initial_source_connection_id", 0x10: "retry_source_connection_id", 0x11: "version_information", 0x20: "max_datagram_frame_size",
|
||||
0x2AB2: "grease_quic_bit", 0x2AB1: "reset_stream_at", 0x3127: "initial_rtt", 0x1057: "google_connection_options", 0x4752: "google_version",
|
||||
}
|
||||
#: The parameters whose value is an identifier or a secret of the connection: only its length is kept.
|
||||
QUIC_OPAQUE = {0x00, 0x02, 0x0D, 0x0F, 0x10}
|
||||
|
||||
H2_FRAME_TYPES = {0: "DATA", 1: "HEADERS", 2: "PRIORITY", 3: "RST_STREAM", 4: "SETTINGS", 5: "PUSH_PROMISE", 6: "PING", 7: "GOAWAY",
|
||||
8: "WINDOW_UPDATE", 9: "CONTINUATION", 0x10: "PRIORITY_UPDATE"}
|
||||
H2_PREFACE = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
|
||||
|
||||
|
||||
class NotAClientHello(ValueError):
|
||||
"""The bytes are not one TLS record that holds a ClientHello."""
|
||||
|
||||
|
||||
def is_grease(value: int) -> bool:
|
||||
"""A GREASE value of RFC 8701: both bytes are the same and end in 0xa (0x0a0a, 0x1a1a ... 0xfafa)."""
|
||||
return (value & 0x0F0F) == 0x0A0A and (value >> 8) == (value & 0xFF)
|
||||
|
||||
|
||||
def _hex(value: int) -> str:
|
||||
return GREASE if is_grease(value) else "0x%04x" % value
|
||||
|
||||
|
||||
def _grease_quic(identifier: int) -> bool:
|
||||
"""A reserved QUIC transport parameter id (31 * N + 27)."""
|
||||
return identifier >= 27 and (identifier - 27) % 31 == 0
|
||||
|
||||
|
||||
class _Reader:
|
||||
"""A cursor over bytes that refuses to read past the end."""
|
||||
|
||||
def __init__(self, data: bytes) -> None:
|
||||
self.data = data
|
||||
self.at = 0
|
||||
|
||||
def left(self) -> int:
|
||||
return len(self.data) - self.at
|
||||
|
||||
def take(self, n: int) -> bytes:
|
||||
if n < 0 or self.at + n > len(self.data):
|
||||
raise NotAClientHello("a field of %d bytes runs past the end (%d left)" % (n, self.left()))
|
||||
out = self.data[self.at:self.at + n]
|
||||
self.at += n
|
||||
return out
|
||||
|
||||
def u8(self) -> int:
|
||||
return self.take(1)[0]
|
||||
|
||||
def u16(self) -> int:
|
||||
return struct.unpack("!H", self.take(2))[0]
|
||||
|
||||
def u24(self) -> int:
|
||||
return int.from_bytes(self.take(3), "big")
|
||||
|
||||
def u32(self) -> int:
|
||||
return struct.unpack("!I", self.take(4))[0]
|
||||
|
||||
def vec8(self) -> bytes:
|
||||
return self.take(self.u8())
|
||||
|
||||
def vec16(self) -> bytes:
|
||||
return self.take(self.u16())
|
||||
|
||||
|
||||
def _u16_list(data: bytes) -> List[str]:
|
||||
reader = _Reader(data)
|
||||
out = []
|
||||
while reader.left() >= 2:
|
||||
out.append(_hex(reader.u16()))
|
||||
return out
|
||||
|
||||
|
||||
def _parse_extension(ext_type: int, data: bytes) -> Any:
|
||||
"""What is inside one extension, without anything random: a value, a list, or a dict."""
|
||||
reader = _Reader(data)
|
||||
if ext_type == 0: # server_name
|
||||
names = []
|
||||
inner = _Reader(reader.vec16())
|
||||
while inner.left():
|
||||
kind = inner.u8()
|
||||
names.append(inner.vec16().decode("ascii", "replace") if kind == 0 else "type%d" % kind)
|
||||
return names[0] if len(names) == 1 else names
|
||||
if ext_type == 5: # status_request
|
||||
kind = reader.u8()
|
||||
return {"type": kind, "responder_ids_length": len(reader.vec16()), "extensions_length": len(reader.vec16())}
|
||||
if ext_type == 10: # supported_groups
|
||||
return _u16_list(reader.vec16())
|
||||
if ext_type == 11: # ec_point_formats
|
||||
return list(reader.vec8())
|
||||
if ext_type in (13, 34, 50): # signature_algorithms, delegated_credentials, signature_algorithms_cert
|
||||
return _u16_list(reader.vec16())
|
||||
if ext_type == 16: # alpn
|
||||
inner = _Reader(reader.vec16())
|
||||
out = []
|
||||
while inner.left():
|
||||
out.append(inner.vec8().decode("ascii", "replace"))
|
||||
return out
|
||||
if ext_type == 21: # padding
|
||||
return {"length": len(data)}
|
||||
if ext_type == 27: # compress_certificate
|
||||
return _u16_list(reader.vec8())
|
||||
if ext_type == 28: # record_size_limit
|
||||
return reader.u16()
|
||||
if ext_type == 35: # session_ticket
|
||||
return {"length": len(data)}
|
||||
if ext_type == 41: # pre_shared_key: how many, never what
|
||||
identities = _Reader(reader.vec16())
|
||||
count = 0
|
||||
while identities.left():
|
||||
identities.vec16()
|
||||
identities.u32()
|
||||
count += 1
|
||||
binders = _Reader(reader.vec16())
|
||||
lengths = []
|
||||
while binders.left():
|
||||
lengths.append(len(binders.vec8()))
|
||||
return {"identities": count, "binder_lengths": lengths}
|
||||
if ext_type == 42: # early_data
|
||||
return True
|
||||
if ext_type == 43: # supported_versions
|
||||
return _u16_list(reader.vec8())
|
||||
if ext_type == 45: # psk_key_exchange_modes
|
||||
return list(reader.vec8())
|
||||
if ext_type == 51: # key_share: the groups and the length of each key, never the key
|
||||
shares = _Reader(reader.vec16())
|
||||
out = []
|
||||
while shares.left():
|
||||
group = shares.u16()
|
||||
out.append({"group": _hex(group), "key_length": len(shares.vec16())})
|
||||
return out
|
||||
if ext_type in (17513, 17613): # application_settings
|
||||
inner = _Reader(reader.vec16())
|
||||
out = []
|
||||
while inner.left():
|
||||
out.append(inner.vec8().decode("ascii", "replace"))
|
||||
return out
|
||||
if ext_type == 65037: # encrypted_client_hello: the suite and the lengths, never the config or the key
|
||||
kind = reader.u8()
|
||||
if kind != 0:
|
||||
return {"type": kind, "length": len(data)}
|
||||
kdf, aead = reader.u16(), reader.u16()
|
||||
reader.u8()
|
||||
return {"type": 0, "kdf": kdf, "aead": aead, "enc_length": len(reader.vec16()), "payload_length": len(reader.vec16())}
|
||||
if ext_type == 65281: # renegotiation_info
|
||||
return {"length": len(reader.vec8())}
|
||||
return {"length": len(data)}
|
||||
|
||||
|
||||
def parse_client_hello(record: bytes) -> Dict[str, Any]:
|
||||
"""The ClientHello in ``record`` (a whole TLS record, header included), as the dict described at the top of this file. Raises NotAClientHello."""
|
||||
try:
|
||||
reader = _Reader(record)
|
||||
content_type, record_version, length = reader.u8(), reader.u16(), reader.u16()
|
||||
if content_type != 22:
|
||||
raise NotAClientHello("the record is of type %d, not a handshake" % content_type)
|
||||
if length > reader.left():
|
||||
raise NotAClientHello("the record says %d bytes and %d came" % (length, reader.left()))
|
||||
body = _Reader(reader.take(length))
|
||||
if body.u8() != 1:
|
||||
raise NotAClientHello("the handshake message is not a ClientHello")
|
||||
hello = _Reader(body.take(body.u24()))
|
||||
handshake_version = hello.u16()
|
||||
hello.take(32) # the random: dropped
|
||||
session_id = hello.vec8() # the session id: only its length
|
||||
suites_raw = hello.vec16()
|
||||
suites = [_hex(struct.unpack("!H", suites_raw[i:i + 2])[0]) for i in range(0, len(suites_raw) - 1, 2)]
|
||||
compression = list(hello.vec8())
|
||||
out: Dict[str, Any] = {
|
||||
"record_version": "0x%04x" % record_version, "record_length": length, "handshake_version": "0x%04x" % handshake_version,
|
||||
"session_id_length": len(session_id), "cipher_suites": suites, "compression_methods": compression,
|
||||
}
|
||||
order: List[str] = []
|
||||
data: Dict[str, Any] = {}
|
||||
lengths: Dict[str, int] = {}
|
||||
grease = 0
|
||||
extensions = _Reader(hello.vec16()) if hello.left() else _Reader(b"")
|
||||
while extensions.left():
|
||||
ext_type, ext_data = extensions.u16(), extensions.vec16()
|
||||
if is_grease(ext_type):
|
||||
order.append(GREASE)
|
||||
grease += 1
|
||||
continue
|
||||
name = EXTENSION_NAMES.get(ext_type, "ext_%d" % ext_type)
|
||||
order.append(name)
|
||||
lengths[name] = len(ext_data)
|
||||
try:
|
||||
data[name] = _parse_extension(ext_type, ext_data)
|
||||
except NotAClientHello:
|
||||
data[name] = {"unparsed_length": len(ext_data)}
|
||||
out["extension_order"] = order
|
||||
out["extensions"] = data
|
||||
out["extension_lengths"] = lengths
|
||||
out["grease_extensions"] = grease
|
||||
return out
|
||||
except struct.error as exc:
|
||||
raise NotAClientHello("a field is cut short: %s" % exc) from None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------- peeking at the socket
|
||||
def _peek(sock: socket.socket, n: int, deadline_s: float) -> bytes:
|
||||
"""Exactly ``n`` bytes from the front of the stream, left in it. Blocks until they are there (``MSG_WAITALL`` where the system takes it with
|
||||
``MSG_PEEK``; elsewhere a poll with a deadline: a peek that is short of bytes returns at once, and the only way to wait is to look again)."""
|
||||
flags = socket.MSG_PEEK | (0 if sys.platform == "win32" else getattr(socket, "MSG_WAITALL", 0))
|
||||
end = time.monotonic() + deadline_s
|
||||
sock.settimeout(deadline_s)
|
||||
while True:
|
||||
data = sock.recv(n, flags)
|
||||
if len(data) >= n:
|
||||
return data
|
||||
if not data:
|
||||
raise ConnectionError("the peer closed the connection before the ClientHello was complete")
|
||||
if time.monotonic() >= end:
|
||||
raise TimeoutError("the ClientHello did not arrive in %.0f s (%d of %d bytes)" % (deadline_s, len(data), n))
|
||||
time.sleep(0.002)
|
||||
|
||||
|
||||
def peek_client_hello(sock: socket.socket, deadline_s: float = PEEK_DEADLINE_S) -> bytes:
|
||||
"""The record of the ClientHello at the front of the stream of ``sock``, with every byte of it still in the socket's buffer."""
|
||||
head = _peek(sock, 5, deadline_s)
|
||||
if head[0] != 22:
|
||||
raise NotAClientHello("the first byte of the connection is %d, not a TLS handshake record" % head[0])
|
||||
total = 5 + struct.unpack("!H", head[3:5])[0]
|
||||
if total > MAX_HELLO_RECORD:
|
||||
raise NotAClientHello("a record of %d bytes" % total)
|
||||
return _peek(sock, total, deadline_s)[:total]
|
||||
|
||||
|
||||
def accept_with_hello(conn: socket.socket, context: ssl.SSLContext, deadline_s: float = PEEK_DEADLINE_S) -> Tuple[Dict[str, Any], ssl.SSLSocket]:
|
||||
"""Peek the ClientHello of ``conn``, parse it, then hand the same socket to ``ssl``: ``(hello, tls socket)``. The handshake sees every byte."""
|
||||
hello = parse_client_hello(peek_client_hello(conn, deadline_s))
|
||||
conn.settimeout(deadline_s)
|
||||
return hello, context.wrap_socket(conn, server_side=True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------- HTTP/1.1
|
||||
class Http1Parser:
|
||||
"""The requests of one HTTP/1.1 connection, read from the bytes in the order they come. ``feed`` returns the requests that are complete (head and body).
|
||||
|
||||
A request is ``{"request_line": "GET /x HTTP/1.1", "method", "target", "version", "headers": [[name, value], ...], "body_length": n}``: the names with
|
||||
the case they were sent with, in the order they were sent, an empty value kept. The body is skipped (``Content-Length`` and ``chunked``) and never kept."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._buf = bytearray()
|
||||
self._pending: Optional[Dict[str, Any]] = None
|
||||
self._body_left = 0
|
||||
self._chunked = False
|
||||
|
||||
def feed(self, data: bytes) -> List[Dict[str, Any]]:
|
||||
self._buf += data
|
||||
done: List[Dict[str, Any]] = []
|
||||
while True:
|
||||
if self._pending is None:
|
||||
end = self._buf.find(b"\r\n\r\n")
|
||||
if end < 0:
|
||||
return done
|
||||
head = bytes(self._buf[:end]).decode("latin-1")
|
||||
del self._buf[:end + 4]
|
||||
lines = head.split("\r\n")
|
||||
parts = lines[0].split(" ")
|
||||
headers = []
|
||||
for line in lines[1:]:
|
||||
name, _sep, value = line.partition(":")
|
||||
headers.append([name, value.strip(" \t")])
|
||||
self._pending = {"request_line": lines[0], "method": parts[0], "target": parts[1] if len(parts) > 1 else "",
|
||||
"version": parts[2] if len(parts) > 2 else "", "headers": headers, "body_length": 0}
|
||||
lowered = {n.lower(): v for n, v in headers}
|
||||
self._chunked = "chunked" in lowered.get("transfer-encoding", "").lower()
|
||||
try:
|
||||
self._body_left = int(lowered.get("content-length", "0") or 0)
|
||||
except ValueError:
|
||||
self._body_left = 0
|
||||
if self._chunked:
|
||||
if not self._skip_chunks():
|
||||
return done
|
||||
else:
|
||||
take = min(self._body_left, len(self._buf))
|
||||
del self._buf[:take]
|
||||
self._body_left -= take
|
||||
self._pending["body_length"] += take
|
||||
if self._body_left:
|
||||
return done
|
||||
done.append(self._pending)
|
||||
self._pending, self._chunked = None, False
|
||||
|
||||
def _skip_chunks(self) -> bool:
|
||||
"""Consume chunks while they are whole; True when the terminating chunk and its trailer have been read."""
|
||||
while True:
|
||||
line_end = self._buf.find(b"\r\n")
|
||||
if line_end < 0:
|
||||
return False
|
||||
try:
|
||||
size = int(bytes(self._buf[:line_end]).split(b";")[0], 16)
|
||||
except ValueError:
|
||||
size = 0
|
||||
if size == 0:
|
||||
if self._buf.find(b"\r\n\r\n", line_end - 1) < 0 and not self._buf.startswith(b"0\r\n\r\n"):
|
||||
return False
|
||||
end = self._buf.find(b"\r\n\r\n")
|
||||
del self._buf[:end + 4 if end >= 0 else len(self._buf)]
|
||||
return True
|
||||
if len(self._buf) < line_end + 2 + size + 2:
|
||||
return False
|
||||
self._pending["body_length"] += size
|
||||
del self._buf[:line_end + 2 + size + 2]
|
||||
|
||||
|
||||
def serve_http1(sock: Any, responder: Callable[[Dict[str, Any]], Tuple[int, List[Tuple[str, str]], bytes]],
|
||||
on_request: Callable[[Dict[str, Any]], None], alt_svc: Optional[str] = None) -> None:
|
||||
"""Serve the requests of a connection (a TLS socket, or a plain one) until the peer closes: each request is handed to ``on_request`` and answered by
|
||||
``responder(request) -> (status, headers, body)``."""
|
||||
parser = Http1Parser()
|
||||
while True:
|
||||
data = sock.recv(65536)
|
||||
if not data:
|
||||
return
|
||||
for request in parser.feed(data):
|
||||
on_request(request)
|
||||
status, headers, body = responder(dict(request, scheme="https", protocol="http/1.1"))
|
||||
if alt_svc:
|
||||
headers = list(headers) + [("alt-svc", alt_svc)]
|
||||
lines = ["HTTP/1.1 %d %s" % (status, "OK" if status == 200 else "Status")]
|
||||
lines += ["%s: %s" % (n, v) for n, v in headers if n.lower() != "content-length"]
|
||||
lines.append("Content-Length: %d" % len(body))
|
||||
sock.sendall(("\r\n".join(lines) + "\r\n\r\n").encode("latin-1") + body)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------- HTTP/2
|
||||
class FrameTap:
|
||||
"""The HTTP/2 frames of one direction of a connection, parsed from the raw bytes as they come (the client's preface first)."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._buf = bytearray()
|
||||
self._preface = False
|
||||
self.frames: List[Dict[str, Any]] = []
|
||||
|
||||
def feed(self, data: bytes) -> List[Dict[str, Any]]:
|
||||
from hyperframe.frame import Frame
|
||||
|
||||
self._buf += data
|
||||
if not self._preface:
|
||||
if len(self._buf) < len(H2_PREFACE):
|
||||
return []
|
||||
if bytes(self._buf[:len(H2_PREFACE)]) != H2_PREFACE:
|
||||
raise ValueError("the connection does not start with the HTTP/2 preface")
|
||||
del self._buf[:len(H2_PREFACE)]
|
||||
self._preface = True
|
||||
new = []
|
||||
while len(self._buf) >= 9:
|
||||
frame, length = Frame.parse_frame_header(memoryview(bytes(self._buf[:9])))
|
||||
if len(self._buf) < 9 + length:
|
||||
break
|
||||
frame.parse_body(memoryview(bytes(self._buf[9:9 + length])))
|
||||
del self._buf[:9 + length]
|
||||
record = _frame_record(frame)
|
||||
self.frames.append(record)
|
||||
new.append(record)
|
||||
return new
|
||||
|
||||
|
||||
def _priority_fields(frame: Any) -> Dict[str, Any]:
|
||||
return {"depends_on": frame.depends_on, "weight": frame.stream_weight + 1 if frame.stream_weight is not None else None,
|
||||
"exclusive": bool(frame.exclusive)}
|
||||
|
||||
|
||||
def _frame_record(frame: Any) -> Dict[str, Any]:
|
||||
kind = type(frame).__name__
|
||||
record: Dict[str, Any] = {"stream": frame.stream_id, "flags": sorted(frame.flags)}
|
||||
if kind == "SettingsFrame":
|
||||
record.update(type="SETTINGS", settings=[[int(k), v] for k, v in frame.settings.items()])
|
||||
elif kind == "WindowUpdateFrame":
|
||||
record.update(type="WINDOW_UPDATE", increment=frame.window_increment)
|
||||
elif kind == "PriorityFrame":
|
||||
record.update(type="PRIORITY", **_priority_fields(frame))
|
||||
elif kind in ("HeadersFrame", "PushPromiseFrame", "ContinuationFrame"):
|
||||
record["type"] = {"HeadersFrame": "HEADERS", "PushPromiseFrame": "PUSH_PROMISE", "ContinuationFrame": "CONTINUATION"}[kind]
|
||||
if kind == "HeadersFrame" and "PRIORITY" in frame.flags:
|
||||
record["priority"] = _priority_fields(frame)
|
||||
elif kind == "DataFrame":
|
||||
record.update(type="DATA", length=len(frame.data))
|
||||
elif kind == "ExtensionFrame":
|
||||
number = int(frame.type)
|
||||
record["type"] = H2_FRAME_TYPES.get(number, "TYPE_%d" % number)
|
||||
body = bytes(frame.body)
|
||||
if number == 0x10 and len(body) >= 4: # PRIORITY_UPDATE (RFC 9218): the element and the priority field
|
||||
record.update(element=struct.unpack("!I", body[:4])[0] & 0x7FFFFFFF, field=body[4:].decode("ascii", "replace"))
|
||||
else:
|
||||
record["length"] = len(body)
|
||||
else:
|
||||
record["type"] = {"PingFrame": "PING", "GoAwayFrame": "GOAWAY", "RstStreamFrame": "RST_STREAM"}.get(kind, kind)
|
||||
return record
|
||||
|
||||
|
||||
def summarize_frames(frames: List[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
"""What of a connection's frames is the shape of the CLIENT, not of the traffic: the first SETTINGS in order, the WINDOW_UPDATEs and the types of the
|
||||
frames before the first request, every PRIORITY and PRIORITY_UPDATE, the priority fields of the HEADERS. What follows the first request (DATA, PING,
|
||||
later window updates) depends on how much was sent and is only counted."""
|
||||
first_headers = next((i for i, f in enumerate(frames) if f["type"] == "HEADERS"), len(frames))
|
||||
before = frames[:first_headers]
|
||||
settings = next((f["settings"] for f in frames if f["type"] == "SETTINGS" and "ACK" not in f["flags"]), None)
|
||||
return {
|
||||
"settings": settings,
|
||||
"settings_ack_sent_by_client": any(f["type"] == "SETTINGS" and "ACK" in f["flags"] for f in frames),
|
||||
"frame_types_before_the_first_request": [f["type"] for f in before],
|
||||
"window_updates_before_the_first_request": [{"stream": f["stream"], "increment": f["increment"]} for f in before if f["type"] == "WINDOW_UPDATE"],
|
||||
"priority": [{"stream": f["stream"], **{k: f[k] for k in ("depends_on", "weight", "exclusive")}} for f in frames if f["type"] == "PRIORITY"],
|
||||
"priority_update": [{"stream": f["stream"], "element": f["element"], "field": f["field"]} for f in frames if f["type"] == "PRIORITY_UPDATE"],
|
||||
"headers_priority": [dict(f["priority"], stream=f["stream"]) for f in frames if f["type"] == "HEADERS" and "priority" in f],
|
||||
"frames_after_the_first_request": len(frames) - first_headers,
|
||||
}
|
||||
|
||||
|
||||
class H2Connection:
|
||||
"""The server side of one HTTP/2 connection, with a tap on the frames. ``serve(sock)`` blocks until the peer closes. Each request is recorded as
|
||||
``{"stream", "pseudo_order": [":method", ...], "header_names": [...], "headers": [[name, value], ...], "end_stream"}`` and answered by ``responder``."""
|
||||
|
||||
def __init__(self, responder: Callable[[Dict[str, Any]], Tuple[int, List[Tuple[str, str]], bytes]], alt_svc: Optional[str] = None) -> None:
|
||||
import h2.config
|
||||
import h2.connection
|
||||
|
||||
config = h2.config.H2Configuration(client_side=False, header_encoding=None, validate_inbound_headers=False, normalize_inbound_headers=False,
|
||||
validate_outbound_headers=False, normalize_outbound_headers=False)
|
||||
self.conn = h2.connection.H2Connection(config=config)
|
||||
self.responder = responder
|
||||
self.alt_svc = alt_svc
|
||||
self.tap = FrameTap()
|
||||
self.requests: List[Dict[str, Any]] = []
|
||||
self._bodies: Dict[int, int] = {}
|
||||
|
||||
def summary(self) -> Dict[str, Any]:
|
||||
return dict(summarize_frames(self.tap.frames), requests=list(self.requests))
|
||||
|
||||
def serve(self, sock: Any) -> None:
|
||||
import h2.events
|
||||
import h2.exceptions
|
||||
|
||||
self.conn.initiate_connection()
|
||||
sock.sendall(self.conn.data_to_send())
|
||||
while True:
|
||||
data = sock.recv(65536)
|
||||
if not data:
|
||||
return
|
||||
try:
|
||||
self.tap.feed(data)
|
||||
events = self.conn.receive_data(data)
|
||||
except (h2.exceptions.ProtocolError, ValueError):
|
||||
out = self.conn.data_to_send()
|
||||
if out:
|
||||
sock.sendall(out)
|
||||
return
|
||||
for event in events:
|
||||
if isinstance(event, h2.events.RequestReceived):
|
||||
self._request(event)
|
||||
if event.stream_ended is not None:
|
||||
self._answer(event.stream_id)
|
||||
elif isinstance(event, h2.events.DataReceived):
|
||||
self._bodies[event.stream_id] = self._bodies.get(event.stream_id, 0) + len(event.data)
|
||||
self.conn.acknowledge_received_data(event.flow_controlled_length, event.stream_id)
|
||||
elif isinstance(event, h2.events.StreamEnded):
|
||||
self._answer(event.stream_id)
|
||||
elif isinstance(event, h2.events.ConnectionTerminated):
|
||||
return
|
||||
out = self.conn.data_to_send()
|
||||
if out:
|
||||
sock.sendall(out)
|
||||
|
||||
def _request(self, event: Any) -> None:
|
||||
headers = [[_text(n), _text(v)] for n, v in event.headers]
|
||||
self.requests.append({"stream": event.stream_id, "pseudo_order": [n for n, _v in headers if n.startswith(":")],
|
||||
"header_names": [n for n, _v in headers if not n.startswith(":")], "headers": headers,
|
||||
"end_stream": event.stream_ended is not None})
|
||||
|
||||
def _answer(self, stream_id: int) -> None:
|
||||
request = next((r for r in self.requests if r["stream"] == stream_id and not r.get("answered")), None)
|
||||
if request is None:
|
||||
return
|
||||
request["answered"] = True
|
||||
fields = {n: v for n, v in request["headers"]}
|
||||
status, headers, body = self.responder({"method": fields.get(":method", ""), "target": fields.get(":path", ""), "headers": request["headers"],
|
||||
"scheme": "https", "protocol": "h2", "body_length": self._bodies.get(stream_id, 0)})
|
||||
extra = [("alt-svc", self.alt_svc)] if self.alt_svc else []
|
||||
out = [(":status", str(status))] + [(n.lower(), v) for n, v in list(headers) + extra if n.lower() != "content-length"]
|
||||
out.append(("content-length", str(len(body))))
|
||||
self.conn.send_headers(stream_id, out)
|
||||
self.conn.send_data(stream_id, body, end_stream=True)
|
||||
|
||||
|
||||
def _text(value: Any) -> str:
|
||||
return value.decode("latin-1") if isinstance(value, (bytes, bytearray)) else str(value)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------- QUIC / HTTP/3
|
||||
def read_varint(data: bytes, at: int) -> Tuple[int, int]:
|
||||
"""A QUIC variable-length integer at ``data[at:]``: ``(value, the index after it)``."""
|
||||
first = data[at]
|
||||
size = 1 << (first >> 6)
|
||||
if at + size > len(data):
|
||||
raise ValueError("a variable-length integer is cut short")
|
||||
return int.from_bytes(bytes([first & 0x3F]) + data[at + 1:at + size], "big"), at + size
|
||||
|
||||
|
||||
def parse_quic_transport_parameters(raw: bytes) -> List[Dict[str, Any]]:
|
||||
"""The transport parameters a QUIC client sent, in the order it sent them. A reserved id (31 * N + 27) is ``"GREASE"`` and loses its value; an
|
||||
identifier or a secret (connection ids, the reset token, the preferred address) keeps only its length; any other integer parameter its value."""
|
||||
out: List[Dict[str, Any]] = []
|
||||
at = 0
|
||||
while at < len(raw):
|
||||
identifier, at = read_varint(raw, at)
|
||||
length, at = read_varint(raw, at)
|
||||
value = raw[at:at + length]
|
||||
if len(value) < length:
|
||||
raise ValueError("a transport parameter is cut short")
|
||||
at += length
|
||||
if _grease_quic(identifier):
|
||||
out.append({"id": GREASE, "length": length})
|
||||
continue
|
||||
entry: Dict[str, Any] = {"id": identifier, "name": QUIC_PARAMETER_NAMES.get(identifier, "param_%d" % identifier), "length": length}
|
||||
if identifier not in QUIC_OPAQUE and 0 < length <= 8 and identifier not in (0x11,):
|
||||
try:
|
||||
entry["value"], end = read_varint(value, 0)
|
||||
if end != length:
|
||||
del entry["value"]
|
||||
except ValueError:
|
||||
pass
|
||||
out.append(entry)
|
||||
return out
|
||||
|
||||
|
||||
H3_SETTING_NAMES = {0x01: "QPACK_MAX_TABLE_CAPACITY", 0x06: "MAX_FIELD_SECTION_SIZE", 0x07: "QPACK_BLOCKED_STREAMS", 0x08: "ENABLE_CONNECT_PROTOCOL",
|
||||
0x33: "H3_DATAGRAM", 0x276: "H3_DATAGRAM_DRAFT04", 0x2B603742: "ENABLE_WEBTRANSPORT"}
|
||||
|
||||
|
||||
def h3_settings(settings: Optional[Dict[int, int]]) -> Optional[List[List[Any]]]:
|
||||
"""The SETTINGS frame of an HTTP/3 client as ``[[name, value], ...]``; a reserved identifier (0x1f * N + 0x21) is ``"GREASE"``."""
|
||||
if settings is None:
|
||||
return None
|
||||
return [["GREASE" if (k >= 0x21 and (k - 0x21) % 0x1F == 0) else H3_SETTING_NAMES.get(int(k), "0x%x" % int(k)), v] for k, v in settings.items()]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------------------------- the lab server
|
||||
PAGE = (b"<!doctype html><meta charset=utf-8><title>wire</title><link rel=stylesheet href=/wire.css><script src=/wire.js></script>"
|
||||
b"<p>wire</p><img src=/wire.svg alt=''>")
|
||||
|
||||
|
||||
def default_responder(request: Dict[str, Any]) -> Tuple[int, List[Tuple[str, str]], bytes]:
|
||||
"""A small site: a page that loads a style, a script and an image, sets a cookie, and answers a POST."""
|
||||
target = request["target"].split("?")[0]
|
||||
if target == "/":
|
||||
return 200, [("content-type", "text/html; charset=utf-8"), ("set-cookie", "wire=1; Path=/; SameSite=Lax"), ("cache-control", "no-store")], PAGE
|
||||
if target == "/wire.css":
|
||||
return 200, [("content-type", "text/css"), ("cache-control", "no-store")], b"p{color:#333}"
|
||||
if target == "/wire.js":
|
||||
return 200, [("content-type", "text/javascript"), ("cache-control", "no-store")], b"window.__wire = 1;"
|
||||
if target == "/wire.svg":
|
||||
return 200, [("content-type", "image/svg+xml"), ("cache-control", "no-store")], b"<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'/>"
|
||||
return 200, [("content-type", "text/plain"), ("access-control-allow-origin", "*"), ("cache-control", "no-store")], b"ok"
|
||||
|
||||
|
||||
class _Handler(socketserver.BaseRequestHandler):
|
||||
def handle(self) -> None:
|
||||
self.server.owner._connection(self.request) # type: ignore[attr-defined]
|
||||
|
||||
|
||||
class _Server(socketserver.ThreadingTCPServer):
|
||||
allow_reuse_address = sys.platform != "win32"
|
||||
daemon_threads = True
|
||||
|
||||
|
||||
class WireServer:
|
||||
"""One TLS server (TCP) and, with ``h3=True``, a QUIC server on the same port number, each connection written down.
|
||||
|
||||
``alpn`` is what the server OFFERS (``["h2", "http/1.1"]``, or ``["http/1.1"]`` for a server that only speaks HTTP/1.1): the client's offer is the same
|
||||
either way, and what it reads is the answer. ``phase()`` names the stage of the run a connection or a request belongs to, at the time it arrives.
|
||||
|
||||
``connections`` is the list of the TLS connections, each ``{"id", "phase", "tls": <ClientHello>, "alpn": <selected>, "http1": [requests]}`` or
|
||||
``{..., "h2": <H2Connection>}``; ``quic`` the QUIC connections ``{"phase", "transport_parameters", "h3_settings", "requests"}``. :meth:`snapshot` is the
|
||||
JSON of all of it."""
|
||||
|
||||
def __init__(self, address: str = "127.0.0.1", *, alpn: Tuple[str, ...] = ("h2", "http/1.1"), h3: bool = False,
|
||||
responder: Callable[[Dict[str, Any]], Tuple[int, List[Tuple[str, str]], bytes]] = default_responder,
|
||||
phase: Callable[[], str] = lambda: "-", dns_names: Tuple[str, ...] = ("wire.test",)) -> None:
|
||||
from _doh_servers import make_certificate
|
||||
from _ports import bind_tcp_and_hold_udp
|
||||
|
||||
self.address, self.alpn, self.responder, self.phase = address, tuple(alpn), responder, phase
|
||||
self.connections: List[Dict[str, Any]] = []
|
||||
self.quic: List[Dict[str, Any]] = []
|
||||
self.refused: List[str] = []
|
||||
self._lock = threading.Lock()
|
||||
self._dir = tempfile.TemporaryDirectory()
|
||||
certificate, key = make_certificate(Path(self._dir.name), dns_names=dns_names, ip_addresses=(address,))
|
||||
self._tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
self._tls.load_cert_chain(str(certificate), str(key))
|
||||
self._tls.set_alpn_protocols(list(self.alpn))
|
||||
self._udp: Optional[socket.socket] = None
|
||||
if h3:
|
||||
self._tcp, self.port, self._udp = bind_tcp_and_hold_udp(address, lambda host, number: _Server((host, number), _Handler), socket_module=socket)
|
||||
else:
|
||||
self._tcp = _Server((address, 0), _Handler)
|
||||
self.port = self._tcp.server_address[1]
|
||||
self.alt_svc = 'h3=":%d"; ma=3600' % self.port if h3 else None
|
||||
self._tcp.owner = self # type: ignore[attr-defined]
|
||||
threading.Thread(target=self._tcp.serve_forever, daemon=True).start()
|
||||
self._loop = None
|
||||
if h3:
|
||||
self._start_quic(certificate, key)
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
return "https://%s:%d/" % (self.address, self.port)
|
||||
|
||||
# --- TCP ------------------------------------------------------------------------------------------------------------------------------
|
||||
def _connection(self, sock: socket.socket) -> None:
|
||||
record: Dict[str, Any] = {"phase": self.phase(), "tls": None, "alpn": None}
|
||||
with self._lock:
|
||||
record["id"] = len(self.connections)
|
||||
self.connections.append(record)
|
||||
tls = None
|
||||
try:
|
||||
hello, tls = accept_with_hello(sock, self._tls)
|
||||
record["tls"] = hello
|
||||
record["alpn"] = tls.selected_alpn_protocol() or "http/1.1"
|
||||
tls.settimeout(60)
|
||||
if record["alpn"] == "h2":
|
||||
record["h2"] = connection = H2Connection(self.responder, self.alt_svc)
|
||||
connection.serve(tls)
|
||||
else:
|
||||
record["http1"] = []
|
||||
serve_http1(tls, self.responder, lambda r: record["http1"].append(dict(r, phase=self.phase())), self.alt_svc)
|
||||
except (ssl.SSLError, OSError, ConnectionError, NotAClientHello, TimeoutError) as exc:
|
||||
record["error"] = "%s: %s" % (type(exc).__name__, exc)
|
||||
finally:
|
||||
for s in (tls, sock):
|
||||
try:
|
||||
if s is not None:
|
||||
s.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# --- QUIC -----------------------------------------------------------------------------------------------------------------------------
|
||||
def _start_quic(self, certificate: Path, key: Path) -> None:
|
||||
import asyncio
|
||||
|
||||
from aioquic.asyncio.protocol import QuicConnectionProtocol
|
||||
from aioquic.asyncio.server import QuicServer
|
||||
from aioquic.h3.connection import H3_ALPN, H3Connection
|
||||
from aioquic.h3.events import HeadersReceived
|
||||
from aioquic.quic.configuration import QuicConfiguration
|
||||
from aioquic.quic.events import ProtocolNegotiated
|
||||
|
||||
server = self
|
||||
|
||||
class Protocol(QuicConnectionProtocol):
|
||||
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self._http: Optional[Any] = None
|
||||
self._record: Dict[str, Any] = {}
|
||||
|
||||
def quic_event_received(self, event: Any) -> None:
|
||||
if isinstance(event, ProtocolNegotiated):
|
||||
self._http = H3Connection(self._quic)
|
||||
raw = next((data for kind, data in (self._quic.tls.received_extensions or []) if kind in (0x39, 0xFFA5)), b"")
|
||||
peer = self._quic._network_paths[0].addr
|
||||
self._record = {"phase": server.phase(), "alpn": event.alpn_protocol, "peer": [peer[0], peer[1]],
|
||||
"transport_parameters": parse_quic_transport_parameters(raw), "h3_settings": None, "requests": []}
|
||||
with server._lock:
|
||||
server.quic.append(self._record)
|
||||
if self._http is None:
|
||||
return
|
||||
for http_event in self._http.handle_event(event):
|
||||
if isinstance(http_event, HeadersReceived):
|
||||
headers = [[_text(n), _text(v)] for n, v in http_event.headers]
|
||||
self._record["h3_settings"] = h3_settings(self._http.received_settings)
|
||||
self._record["requests"].append({
|
||||
"stream": http_event.stream_id, "pseudo_order": [n for n, _v in headers if n.startswith(":")],
|
||||
"header_names": [n for n, _v in headers if not n.startswith(":")], "headers": headers,
|
||||
"phase": server.phase()})
|
||||
fields = dict(headers)
|
||||
status, out, body = server.responder({"method": fields.get(":method", ""), "target": fields.get(":path", ""), "headers": headers,
|
||||
"scheme": "https", "protocol": "h3", "body_length": 0})
|
||||
self._http.send_headers(http_event.stream_id, [(b":status", str(status).encode())] +
|
||||
[(n.lower().encode(), v.encode()) for n, v in out if n.lower() != "content-length"] +
|
||||
[(b"content-length", str(len(body)).encode())])
|
||||
self._http.send_data(http_event.stream_id, body, end_stream=True)
|
||||
self.transmit()
|
||||
|
||||
configuration = QuicConfiguration(is_client=False, alpn_protocols=H3_ALPN)
|
||||
configuration.load_cert_chain(str(certificate), str(key))
|
||||
self._loop = asyncio.new_event_loop()
|
||||
started = threading.Event()
|
||||
|
||||
def run() -> None:
|
||||
asyncio.set_event_loop(self._loop)
|
||||
_transport, self._quic = self._loop.run_until_complete(self._loop.create_datagram_endpoint(
|
||||
lambda: QuicServer(configuration=configuration, create_protocol=Protocol), sock=self._udp))
|
||||
started.set()
|
||||
try:
|
||||
self._loop.run_forever()
|
||||
finally:
|
||||
# The loop is closed HERE, on its own thread, after the QUIC server (as tests/_h3_server.py does): a loop that is only stopped is closed
|
||||
# later by the garbage collector on whatever thread it runs in, and on Windows the proactor's close then waits for ever.
|
||||
self._quic.close()
|
||||
for _ in range(3): # a few turns of the loop let the closing transport flush
|
||||
self._loop.run_until_complete(asyncio.sleep(0))
|
||||
self._loop.close()
|
||||
|
||||
self._thread = threading.Thread(target=run, daemon=True)
|
||||
self._thread.start()
|
||||
if not started.wait(30):
|
||||
raise RuntimeError("the QUIC server did not start")
|
||||
|
||||
# --- what a test or the oracle reads --------------------------------------------------------------------------------------------------
|
||||
def snapshot(self) -> Dict[str, Any]:
|
||||
with self._lock:
|
||||
connections = list(self.connections)
|
||||
quic = list(self.quic)
|
||||
out: List[Dict[str, Any]] = []
|
||||
for c in connections:
|
||||
item = {"id": c["id"], "phase": c["phase"], "tls": c["tls"], "alpn": c["alpn"]}
|
||||
if "h2" in c:
|
||||
item["h2"] = c["h2"].summary()
|
||||
if "http1" in c:
|
||||
item["http1"] = list(c["http1"])
|
||||
if "error" in c:
|
||||
item["error"] = c["error"]
|
||||
out.append(item)
|
||||
return {"connections": out, "quic": quic}
|
||||
|
||||
def close(self) -> None:
|
||||
self._tcp.shutdown()
|
||||
self._tcp.server_close()
|
||||
if self._loop is not None and not self._loop.is_closed():
|
||||
self._loop.call_soon_threadsafe(self._loop.stop)
|
||||
self._thread.join(30)
|
||||
self._dir.cleanup()
|
||||
|
||||
def __enter__(self) -> "WireServer":
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc: Any) -> None:
|
||||
self.close()
|
||||
@@ -0,0 +1,638 @@
|
||||
"""The network A/B oracle's comparator, its normalisation and its lab (scripts/ci_ab_network.py), on synthetic transcripts and local sockets, no browser.
|
||||
|
||||
The oracle asks one question of two engines: same journey, same seeds, same lab, same wire. Each property is shown on the input it exists for: two transcripts that
|
||||
differ in one leaf are red (with the path and both values), equal ones are green, a transcript with fewer leaves than the floor is red (a run that saw less than it should
|
||||
passes anything), a volatile entry that matches no leaf is red as stale (the list may only shrink), a connection that reached the lab around the proxy on EITHER side is red
|
||||
by itself, and the A/A (one engine twice) is a control: its red is a broken control, exit 2, never a finding about a candidate.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
|
||||
import ci_ab_network as ab # noqa: E402
|
||||
import _wire_capture as wc # noqa: E402
|
||||
from test_wire_capture import build_hello # noqa: E402
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def transcript(label="a", seeds=(11, 12)):
|
||||
"""A small transcript with the categories a real one has: a journey step, a TLS hello, an HTTP/2 connection, a WebRTC gather, an idle window and the lab's direct lists."""
|
||||
def seed_body():
|
||||
return {
|
||||
"journey": {"order": ["127.0.0.1:A", "127.0.0.1:O"],
|
||||
"steps": {"01": {"name": "open home", "ok": True, "idle": True, "url": "A/",
|
||||
"connects": {"order": ["127.0.0.1:A"], "counts": {"127.0.0.1:A": 2}},
|
||||
"requests": {"GET A/": {"count": 1, "headers": [["Host", "journey-a.test:A"], ["Accept", "*/*"]], "name_orders": ["Host,Accept"],
|
||||
"body_length": 0}}}}},
|
||||
"https": {"h2": {"v1": {"connections": [{"alpn": "h2", "tls": wc.parse_client_hello(build_hello())}]}}},
|
||||
"webrtc": {"candidates": ["udp comp1 prio100 srflx <exit>"], "gathering": "complete"},
|
||||
"idle": {"c1": {"destinations": {"connects": [], "dns": []}}},
|
||||
"lab": {"direct": {"witness_tcp": [], "witness_udp": [], "watcher": [], "doh_direct": [], "resolver_trap": [], "blind": []}},
|
||||
}
|
||||
return {"format": ab.FORMAT, "label": label, "seeds": {str(s): seed_body() for s in seeds}}
|
||||
|
||||
|
||||
def compare(a, b, volatile=(), floor=0):
|
||||
return ab.compare_transcripts(a, b, list(volatile), floor, a.get("label", "A"), b.get("label", "B"))
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------- the comparison
|
||||
def test_equal_transcripts_are_green_and_the_leaves_are_counted_by_category():
|
||||
report = compare(transcript(), transcript())
|
||||
assert report["verdict"] == "green" and report["problems"] == [] and report["differences"] == []
|
||||
assert report["leaves"] > 100
|
||||
assert set(report["by_category"]) == {"journey", "https", "webrtc", "idle", "lab"}
|
||||
assert sum(report["by_category"].values()) == report["leaves"]
|
||||
|
||||
|
||||
def test_a_difference_in_one_leaf_is_red_and_names_the_path_and_both_values():
|
||||
b = transcript("b")
|
||||
b["seeds"]["12"]["journey"]["steps"]["01"]["requests"]["GET A/"]["headers"][1][1] = "text/html"
|
||||
report = compare(transcript(), b)
|
||||
assert report["verdict"] == "red"
|
||||
(difference,) = report["differences"]
|
||||
assert difference["path"] == "seeds/12/journey/steps/01/requests/GET A//headers/1/1"
|
||||
assert difference["a"] == "*/*" and difference["b"] == "text/html"
|
||||
assert any(difference["path"] in p and "*/*" in p and "text/html" in p for p in report["problems"])
|
||||
|
||||
|
||||
def test_a_leaf_that_one_side_does_not_have_is_a_difference():
|
||||
b = transcript("b")
|
||||
del b["seeds"]["11"]["https"]["h2"]["v1"]["connections"][0]["tls"]["extensions"]["record_size_limit"]
|
||||
(difference,) = compare(transcript(), b)["differences"]
|
||||
assert difference["a"] == 16385 and difference["b"] == ab.MISSING and difference["path"].endswith("/record_size_limit")
|
||||
|
||||
|
||||
def test_an_order_that_changed_is_a_difference_at_the_index_where_it_changed():
|
||||
b = transcript("b")
|
||||
tls = b["seeds"]["11"]["https"]["h2"]["v1"]["connections"][0]["tls"]
|
||||
tls["cipher_suites"][1], tls["cipher_suites"][2] = tls["cipher_suites"][2], tls["cipher_suites"][1]
|
||||
paths = [d["path"] for d in compare(transcript(), b)["differences"]]
|
||||
assert paths == ["seeds/11/https/h2/v1/connections/0/tls/cipher_suites/1", "seeds/11/https/h2/v1/connections/0/tls/cipher_suites/2"]
|
||||
|
||||
|
||||
def test_fewer_leaves_than_the_floor_is_red_even_when_every_leaf_is_equal():
|
||||
report = compare(transcript(), transcript(), floor=10 ** 6)
|
||||
leaves = report["leaves"]
|
||||
assert report["verdict"] == "red" and report["differences"] == []
|
||||
assert any(("only %d leaves" % leaves) in p for p in report["problems"])
|
||||
assert compare(transcript(), transcript(), floor=leaves)["verdict"] == "green"
|
||||
|
||||
|
||||
def test_sides_that_ran_different_seeds_are_red():
|
||||
report = compare(transcript(seeds=(11, 12)), transcript(seeds=(11, 13)))
|
||||
assert report["verdict"] == "red" and any("different seeds" in p for p in report["problems"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("side", ["a", "b"])
|
||||
@pytest.mark.parametrize("name", ["witness_tcp", "witness_udp", "watcher", "doh_direct", "resolver_trap", "blind"])
|
||||
def test_a_direct_connection_on_either_side_is_red_by_itself(side, name):
|
||||
"""Known-bad: the witness heard the browser, or the watcher saw a connection past the proxy, or the sink was blind: red even when the other side did the same."""
|
||||
a, b = transcript("a"), transcript("b")
|
||||
for t in ((a,) if side == "a" else (b,)):
|
||||
t["seeds"]["11"]["lab"]["direct"][name] = ["tcp from 192.0.2.1"]
|
||||
report = compare(a, b)
|
||||
assert report["verdict"] == "red" and report["direct"]
|
||||
assert any(("a, seed 11" if side == "a" else "b, seed 11") in p for p in report["problems"] if p.startswith("a direct connection"))
|
||||
both = copy.deepcopy(a)
|
||||
both["seeds"]["11"]["lab"]["direct"][name] = ["tcp from 192.0.2.1"]
|
||||
c = copy.deepcopy(both)
|
||||
assert compare(both, c)["verdict"] == "red", "a leak that both engines make is still a leak"
|
||||
|
||||
|
||||
def test_a_volatile_entry_excuses_the_leaves_it_names_and_only_those():
|
||||
b = transcript("b")
|
||||
b["seeds"]["11"]["journey"]["steps"]["01"]["connects"]["counts"]["127.0.0.1:A"] = 3
|
||||
b["seeds"]["12"]["webrtc"]["gathering"] = "new"
|
||||
entry = {"pattern": "seeds/*/journey/steps/*/connects/counts/*", "reason": "speculative connections", "aa_run": "run 1"}
|
||||
report = compare(transcript(), b, [entry])
|
||||
assert [d["path"] for d in report["differences"]] == ["seeds/12/webrtc/gathering"]
|
||||
assert report["excused"] == 2 and report["volatile"] == [{"pattern": entry["pattern"], "leaves": 2, "differing": 1}]
|
||||
assert report["leaves"] == compare(transcript(), b)["leaves"] - 2
|
||||
|
||||
|
||||
def test_a_volatile_entry_that_matches_no_leaf_is_stale_and_red():
|
||||
"""The list may only shrink: an entry whose leaf is gone says nothing any more and hides what a new leaf of that shape would say."""
|
||||
entry = {"pattern": "seeds/*/journey/steps/*/ads/*", "reason": "a leaf that was removed", "aa_run": "run 1"}
|
||||
report = compare(transcript(), transcript(), [entry])
|
||||
assert report["verdict"] == "red" and report["stale"] == [entry["pattern"]]
|
||||
assert any("stale" in p for p in report["problems"])
|
||||
|
||||
|
||||
def test_a_long_value_is_clipped_in_the_diff_with_its_hash():
|
||||
b = transcript("b")
|
||||
b["seeds"]["11"]["webrtc"]["gathering"] = "x" * 2000
|
||||
(difference,) = compare(transcript(), b)["differences"]
|
||||
assert difference["b"]["len"] > 2000 and len(difference["b"]["sha256"]) == 64 and difference["a"] == "complete"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------- the exit codes and the files
|
||||
def write(path, document):
|
||||
ab.write_json(path, document)
|
||||
return path
|
||||
|
||||
|
||||
def test_the_exit_codes_green_red_and_broken_control(tmp_path, capsys):
|
||||
a = write(tmp_path / "a.json", transcript("a"))
|
||||
same = write(tmp_path / "same.json", transcript("b"))
|
||||
other = transcript("c")
|
||||
other["seeds"]["11"]["webrtc"]["gathering"] = "new"
|
||||
different = write(tmp_path / "different.json", other)
|
||||
empty = tmp_path / "volatile.json"
|
||||
empty.write_text(json.dumps({"format": ab.VOLATILE_FORMAT, "entries": []}), encoding="utf-8")
|
||||
base = ["compare", str(a), "--volatile", str(empty)]
|
||||
assert ab.main(base[:2] + [str(same)] + base[2:]) == 0
|
||||
assert ab.main(base[:2] + [str(different)] + base[2:] + ["--out", str(tmp_path / "diff.json")]) == 1
|
||||
assert ab.main(base[:2] + [str(different)] + base[2:] + ["--a-a"]) == 2, "the A/A that differs is a broken control, not a finding"
|
||||
assert ab.main(base[:2] + [str(same)] + base[2:] + ["--a-a"]) == 0
|
||||
printed = capsys.readouterr().out
|
||||
assert 'DIFF seeds/11/webrtc/gathering: a "complete" | c "new"' in printed and "AB NETWORK A/A FAILED" in printed and "AB NETWORK A/B FAILED" in printed
|
||||
diff = json.loads((tmp_path / "diff.json").read_text(encoding="utf-8"))
|
||||
assert diff["verdict"] == "red" and diff["differences"][0]["path"] == "seeds/11/webrtc/gathering"
|
||||
assert ab.main(["judge", str(tmp_path / "diff.json")]) == 1 and ab.main(["judge", str(tmp_path / "diff.json"), "--a-a"]) == 2
|
||||
|
||||
|
||||
def test_a_file_that_is_not_a_transcript_is_refused(tmp_path):
|
||||
(tmp_path / "x.json").write_text(json.dumps({"format": "other"}), encoding="utf-8")
|
||||
with pytest.raises(SystemExit):
|
||||
ab.read_transcript(tmp_path / "x.json")
|
||||
|
||||
|
||||
def test_an_a_a_that_differs_proposes_the_volatile_patterns_without_the_seed_and_the_step():
|
||||
b = transcript("b")
|
||||
b["seeds"]["11"]["journey"]["steps"]["01"]["connects"]["counts"]["127.0.0.1:A"] = 3
|
||||
b["seeds"]["12"]["journey"]["steps"]["01"]["connects"]["counts"]["127.0.0.1:A"] = 4
|
||||
assert ab.propose_volatile(compare(transcript(), b)) == ["seeds/*/journey/steps/*/connects/counts/127.0.0.1:A"]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------------------ the volatile list
|
||||
def test_the_volatile_list_of_the_repository_is_well_formed_and_every_entry_names_its_evidence():
|
||||
entries = ab.load_volatile()
|
||||
assert all(e["aa_run"].strip() and e["reason"].strip() for e in entries)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("document,why", [
|
||||
({"format": "x", "entries": []}, "format"),
|
||||
({"format": ab.VOLATILE_FORMAT, "entries": "no"}, "list"),
|
||||
({"format": ab.VOLATILE_FORMAT, "entries": [{"pattern": "a/*", "reason": "r"}]}, "aa_run"),
|
||||
({"format": ab.VOLATILE_FORMAT, "entries": [{"pattern": "a/*", "reason": " ", "aa_run": "run"}]}, "reason"),
|
||||
({"format": ab.VOLATILE_FORMAT, "entries": [{"pattern": "a/*", "reason": "r", "aa_run": "x"}, {"pattern": "a/*", "reason": "r", "aa_run": "y"}]}, "twice"),
|
||||
])
|
||||
def test_a_malformed_volatile_list_is_an_error_not_an_empty_list(tmp_path, document, why):
|
||||
path = tmp_path / "v.json"
|
||||
path.write_text(json.dumps(document), encoding="utf-8")
|
||||
with pytest.raises(SystemExit) as raised:
|
||||
ab.load_volatile(path)
|
||||
assert why in str(raised.value)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------- the seeds
|
||||
def test_the_seeds_come_from_the_persona_file_when_it_has_the_candidate_key_and_from_the_oracle_of_the_page_otherwise(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(ab, "SEEDS_FILE", tmp_path / "absent.json")
|
||||
assert ab.default_seeds() == ab.FALLBACK_SEEDS == (11, 12, 13)
|
||||
present = tmp_path / "persona-seeds.json"
|
||||
present.write_text(json.dumps({"candidate": [101, 102], "other": [1]}), encoding="utf-8")
|
||||
monkeypatch.setattr(ab, "SEEDS_FILE", present)
|
||||
assert ab.default_seeds() == (101, 102)
|
||||
present.write_text(json.dumps({"other": [1]}), encoding="utf-8")
|
||||
assert ab.default_seeds() == (11, 12, 13)
|
||||
assert ab.parse_seeds("5, 6,7") == (5, 6, 7)
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------------------------------------------------- the normalisation
|
||||
def test_a_port_of_the_lab_becomes_its_role_everywhere_a_string_holds_it():
|
||||
norm = ab.Normalizer({40001: "A", 40002: "h3", 40003: "witness"})
|
||||
assert norm.text("127.0.0.1:40001") == "127.0.0.1:A"
|
||||
assert norm.text("http://journey-a.test:40001/article/2?x=1:40002") == "http://journey-a.test:A/article/2?x=1:h3"
|
||||
assert norm.text('h3=":40002"; ma=3600') == 'h3=":h3"; ma=3600'
|
||||
assert norm.text("12:30:45 and :40009 stay") == "12:30:45 and :40009 stay"
|
||||
assert norm.walk({"127.0.0.1:40003": ["a:40001", {"k": "b:40002"}], "n": 40001}) == {"127.0.0.1:witness": ["a:A", {"k": "b:h3"}], "n": 40001}
|
||||
|
||||
|
||||
def test_the_random_token_of_a_page_and_the_value_of_a_cookie_are_dropped_and_their_names_stay():
|
||||
norm = ab.Normalizer({1111: "A"})
|
||||
assert norm.text("/hold?id=lp3f9k2a") == "/hold?id=lp<TOK>"
|
||||
assert norm.text("/hold?id=kapark3f9k2a&until=9") == "/hold?id=kapark<TOK>&until=9"
|
||||
assert norm.text("/jf/slow?tok=ab12cd") == "/jf/slow?tok=<TOK>"
|
||||
assert norm.text("/r?kind=json&id=late3") == "/r?kind=json&id=late3"
|
||||
assert norm.header("Cookie", "session=9f8e7d; theme=dark") == "session=<v>; theme=<v>"
|
||||
assert norm.header("Referer", "http://journey-a.test:1111/") == "http://journey-a.test:A/"
|
||||
assert norm.headers([["Host", "x:1111"], ["cookie", "a=1"]]) == [["Host", "x:A"], ["cookie", "a=<v>"]]
|
||||
|
||||
|
||||
def test_the_requests_of_a_stage_keep_the_header_order_of_the_first_and_every_distinct_order():
|
||||
norm = ab.Normalizer({7000: "A"})
|
||||
first = {"role": "A", "method": "GET", "target": "/a?tok=zz11", "headers": [["Host", "h:7000"], ["Accept", "*/*"]], "body_length": 0}
|
||||
second = {"role": "A", "method": "GET", "target": "/a?tok=yy22", "headers": [["Host", "h:7000"], ["Cookie", "s=1"], ["Accept", "*/*"]], "body_length": 0}
|
||||
other = {"role": "O", "method": "POST", "target": "/beacon", "headers": [["Host", "o"]], "body_length": 3}
|
||||
summary = ab.request_summary([first, second, other], norm)
|
||||
assert list(summary) == ["GET A/a?tok=<TOK>", "POST O/beacon"]
|
||||
entry = summary["GET A/a?tok=<TOK>"]
|
||||
assert entry["count"] == 2 and entry["headers"] == [["Host", "h:A"], ["Accept", "*/*"]]
|
||||
assert entry["name_orders"] == ["Host,Accept", "Host,Cookie,Accept"]
|
||||
assert summary["POST O/beacon"]["body_length"] == 3
|
||||
|
||||
|
||||
def test_connects_dns_and_datagrams_keep_the_first_seen_order_and_count_the_rest():
|
||||
norm = ab.Normalizer({7000: "A"})
|
||||
assert ab.connect_summary(["127.0.0.1:7000", "192.0.2.53:443", "127.0.0.1:7000"], norm) == {
|
||||
"order": ["127.0.0.1:A", "192.0.2.53:443"], "counts": {"127.0.0.1:A": 2, "192.0.2.53:443": 1}}
|
||||
assert ab.dns_summary([("b.test", 28, "lab"), ("a.test", 1, "lab"), ("b.test", 1, "lab"), ("b.test", 65, "lab")]) == {
|
||||
"order": ["b.test", "a.test"], "types": {"a.test": [1], "b.test": [1, 28, 65]}}
|
||||
stun = b"\x00\x01\x00\x00\x21\x12\xa4\x42" + b"\x00" * 12
|
||||
udp = ab.udp_summary([{"target": "198.51.100.5:19302", "message": ab.message_kind(stun)}, {"target": "198.51.100.5:19302", "message": ab.message_kind(stun)}], norm)
|
||||
assert udp == {"order": ["198.51.100.5:19302"], "messages": {"198.51.100.5:19302": ["stun-0x0001"]}, "counts": {"198.51.100.5:19302": 2}}
|
||||
assert ab.message_kind(b"\xc3" + b"\x00" * 30) == "quic-long" and ab.message_kind(b"\x43abc") == "quic-short" and ab.message_kind(b"\x01") == "other"
|
||||
|
||||
|
||||
def test_an_ice_candidate_loses_what_it_draws_at_random_and_keeps_what_the_client_decides():
|
||||
exit_ip = "198.51.100.9"
|
||||
mdns = "candidate:0 1 UDP 2122252543 6f1c1e2a-9b8d-4c33-a1e0-5d7f7a9c0b11.local 51234 typ host"
|
||||
srflx = "candidate:1 1 UDP 1686052607 198.51.100.9 51234 typ srflx raddr 0.0.0.0 rport 0"
|
||||
relay = "candidate:2 1 UDP 92216831 203.0.113.5 61000 typ relay raddr 198.51.100.9 rport 40000"
|
||||
assert ab.candidate_summary(mdns, exit_ip) == "udp comp1 prio2122252543 host <mdns>"
|
||||
assert ab.candidate_summary(srflx, exit_ip) == "udp comp1 prio1686052607 srflx <exit> raddr 0.0.0.0 rport 0"
|
||||
assert ab.candidate_summary(relay, exit_ip) == "udp comp1 prio92216831 relay <other> raddr <exit> rport <port>"
|
||||
assert ab.candidate_summary("candidate:3 garbled", exit_ip).startswith("unparsed:")
|
||||
again = mdns.replace("6f1c1e2a-9b8d-4c33-a1e0-5d7f7a9c0b11", "11111111-2222-3333-4444-555555555555").replace("51234", "1")
|
||||
assert ab.candidate_summary(again, exit_ip) == ab.candidate_summary(mdns, exit_ip)
|
||||
|
||||
|
||||
def test_an_sdp_keeps_its_shape_and_loses_its_random_values():
|
||||
sdp = "\r\n".join(["v=0", "o=mozilla...THIS_IS_SDPARTA-99.0 7134562788921547 0 IN IP4 0.0.0.0", "s=-", "t=0 0", "a=fingerprint:sha-256 AA:BB", "a=group:BUNDLE 0",
|
||||
"m=application 54321 UDP/DTLS/SCTP webrtc-datachannel", "c=IN IP4 198.51.100.9", "a=candidate:0 1 UDP 1 198.51.100.9 1 typ srflx",
|
||||
"a=ice-ufrag:abcd", "a=ice-pwd:0123456789", "a=mid:0", ""])
|
||||
lines = ab.sdp_summary(sdp, "198.51.100.9")
|
||||
assert "a=fingerprint:<v>" in lines and "a=ice-ufrag:<v>" in lines and "c=IN IP4 <exit>" in lines and "m=application <port> UDP/DTLS/SCTP webrtc-datachannel" in lines
|
||||
assert not any(line.startswith("a=candidate") for line in lines) and "o=mozilla...THIS_IS_SDPARTA-99.0 <id> <ver> IN IP4 0.0.0.0" in lines
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------------------------- the recorder
|
||||
def test_the_recorder_gives_each_item_to_the_stage_that_was_current_when_it_arrived():
|
||||
rec = ab.Recorder()
|
||||
questions: list = []
|
||||
rec.attach("doh", questions)
|
||||
questions.append("q0")
|
||||
rec.set_phase("journey.01")
|
||||
rec.event("connect", target="t1")
|
||||
questions += ["q1", "q2"]
|
||||
rec.set_phase("journey.02")
|
||||
rec.event("connect", target="t2")
|
||||
rec.event("http", role="A")
|
||||
questions.append("q3")
|
||||
rec.set_phase("webrtc")
|
||||
questions.append("q4")
|
||||
assert rec.slice("doh", "launch") == ["q0"]
|
||||
assert rec.slice("doh", "journey.01") == ["q1", "q2"]
|
||||
assert rec.slice("doh", "journey") == ["q1", "q2", "q3"], "a prefix holds the stages under it"
|
||||
assert rec.slice("doh", "webrtc") == ["q4"]
|
||||
assert [e["target"] for e in rec.of("journey", "connect")] == ["t1", "t2"] and [e["target"] for e in rec.of("journey.02", "connect")] == ["t2"]
|
||||
assert rec.of("journey.01", "http") == [] and len(rec.of("journey", "http")) == 1
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------------------------------------------------------- the lab itself
|
||||
def _http_server():
|
||||
"""A plain HTTP/1.1 server on loopback that answers every request with its own path; ``port`` and ``close``."""
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def do_GET(self): # noqa: N802
|
||||
body = self.path.encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
do_POST = do_GET # noqa: N815
|
||||
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
server.daemon_threads = True
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server
|
||||
|
||||
|
||||
def _read_response(sock, until: bytes) -> bytes:
|
||||
sock.settimeout(60)
|
||||
data = b""
|
||||
while until not in data:
|
||||
chunk = sock.recv(4096)
|
||||
assert chunk, "closed before %r: %r" % (until, data)
|
||||
data += chunk
|
||||
return data
|
||||
|
||||
|
||||
def test_the_tee_writes_down_each_request_head_as_it_was_written_and_changes_no_byte():
|
||||
rec = ab.Recorder()
|
||||
server = _http_server()
|
||||
tee = ab.RawTee(rec, server.server_address[1], "A")
|
||||
try:
|
||||
with socket.create_connection(("127.0.0.1", tee.port), timeout=60) as client:
|
||||
client.sendall(b"GET /one?x=1 HTTP/1.1\r\nHost: h\r\nX-Mixed-Case: A\r\nx-empty:\r\n\r\n")
|
||||
assert _read_response(client, b"/one?x=1").startswith(b"HTTP/1.1 200")
|
||||
client.sendall(b"POST /two HTTP/1.1\r\nHost: h\r\nContent-Length: 3\r\nAccept: */*\r\n\r\nabc")
|
||||
assert _read_response(client, b"/two").endswith(b"/two")
|
||||
finally:
|
||||
tee.close()
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
events = rec.of("launch", "http")
|
||||
assert [(e["role"], e["method"], e["target"], e["body_length"]) for e in events] == [("A", "GET", "/one?x=1", 0), ("A", "POST", "/two", 3)]
|
||||
assert events[0]["headers"] == [["Host", "h"], ["X-Mixed-Case", "A"], ["x-empty", ""]]
|
||||
assert events[1]["headers"] == [["Host", "h"], ["Content-Length", "3"], ["Accept", "*/*"]]
|
||||
|
||||
|
||||
def _socks_connect(proxy_port: int, host: str, port: int):
|
||||
"""A SOCKS5 CONNECT by address, no authentication: ``(socket, reply code)``."""
|
||||
sock = socket.create_connection(("127.0.0.1", proxy_port), timeout=60)
|
||||
sock.settimeout(60)
|
||||
sock.sendall(b"\x05\x01\x00")
|
||||
assert sock.recv(2) == b"\x05\x00"
|
||||
sock.sendall(b"\x05\x01\x00\x01" + socket.inet_aton(host) + struct.pack("!H", port))
|
||||
reply = b""
|
||||
while len(reply) < 10:
|
||||
reply += sock.recv(10 - len(reply))
|
||||
return sock, reply[1]
|
||||
|
||||
|
||||
def test_the_gateway_writes_down_every_connect_sends_a_teed_port_to_its_tee_and_carries_nothing_past_loopback_that_the_lab_did_not_name():
|
||||
from _doh_servers import FakeDoh
|
||||
|
||||
gateway_class, turn_class, _page = ab.make_lab_classes()
|
||||
rec = ab.Recorder()
|
||||
doh = FakeDoh({})
|
||||
turn = turn_class("127.0.0.1")
|
||||
gateway = gateway_class(rec, doh, turn, "127.0.0.1", "198.51.100.9")
|
||||
server = _http_server()
|
||||
tee = ab.RawTee(rec, server.server_address[1], "A")
|
||||
gateway.reroute[server.server_address[1]] = tee.port
|
||||
try:
|
||||
sock, code = _socks_connect(gateway.port, "127.0.0.1", server.server_address[1])
|
||||
assert code == 0
|
||||
sock.sendall(b"GET /through HTTP/1.1\r\nHost: h\r\n\r\n")
|
||||
assert _read_response(sock, b"/through").endswith(b"/through")
|
||||
sock.close()
|
||||
refused, refusal = _socks_connect(gateway.port, "192.0.2.77", 8080)
|
||||
refused.close()
|
||||
assert refusal != 0, "an address past loopback that the lab did not name must be refused"
|
||||
finally:
|
||||
tee.close()
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
gateway.close()
|
||||
turn.close()
|
||||
doh.close()
|
||||
assert [e["target"] for e in rec.of("launch", "connect")] == ["127.0.0.1:%d" % server.server_address[1], "192.0.2.77:8080"]
|
||||
assert [e["target"] for e in rec.of("launch", "http")] == ["/through"], "the request went through the tee: its head was written down"
|
||||
|
||||
|
||||
def test_the_gateway_carries_a_datagram_to_the_turn_and_to_the_stun_of_the_lab_and_drops_every_other_one():
|
||||
from _doh_servers import FakeDoh
|
||||
from _turn_chain import TURN_IP, TURN_PORT
|
||||
|
||||
gateway_class, turn_class, _page = ab.make_lab_classes()
|
||||
rec = ab.Recorder()
|
||||
doh = FakeDoh({})
|
||||
turn = turn_class("127.0.0.1")
|
||||
gateway = gateway_class(rec, doh, turn, "127.0.0.1", "198.51.100.9")
|
||||
gateway.udp_allowed.add(("127.0.0.1", 4444))
|
||||
stun = b"\x00\x01\x00\x00\x21\x12\xa4\x42" + b"\x07" * 12
|
||||
try:
|
||||
to_turn = gateway._route(TURN_IP, TURN_PORT, 1, stun, 1, None)
|
||||
assert to_turn == (turn.address, (TURN_IP, TURN_PORT))
|
||||
to_stun = gateway._route("198.51.100.5", 19302, 1, stun, 1, None)
|
||||
assert to_stun is not None and to_stun[0] == gateway.stun.address
|
||||
assert gateway._route("127.0.0.1", 4444, 1, b"\xc3", 1, None) == (("127.0.0.1", 4444), None)
|
||||
assert gateway._route("127.0.0.1", 5555, 1, b"", 1, None) is None, "a datagram to a witness or to anything else is dropped"
|
||||
assert gateway._route("name.test", 4444, 3, b"", 1, None) is None
|
||||
finally:
|
||||
gateway.close()
|
||||
turn.close()
|
||||
doh.close()
|
||||
assert [(e["target"], e["message"]) for e in rec.of("launch", "udp")] == [
|
||||
("198.51.100.7:3478", "stun-0x0001"), ("198.51.100.5:19302", "stun-0x0001"), ("127.0.0.1:4444", "quic-long"), ("127.0.0.1:5555", "other"), ("name.test:4444", "other")]
|
||||
|
||||
|
||||
def test_the_page_site_serves_the_probe_page_with_its_canary_and_counts_the_sentinels():
|
||||
import urllib.request
|
||||
|
||||
_gateway, _turn, page_class = ab.make_lab_classes()
|
||||
site = page_class("http://192.0.2.1:9/c.png")
|
||||
try:
|
||||
base = "http://127.0.0.1:%d" % site.port
|
||||
assert b"http://192.0.2.1:9/c.png" in urllib.request.urlopen(base + "/rtc", timeout=60).read()
|
||||
assert urllib.request.urlopen(base + "/s/3", timeout=60).read() == b"ok"
|
||||
assert urllib.request.urlopen(base + "/", timeout=60).read().startswith(b"<!doctype html>")
|
||||
assert site.sentinels == ["/s/3"]
|
||||
finally:
|
||||
site.close()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------------------- what a transcript holds
|
||||
def minimal_run():
|
||||
"""The leaves per category of a minimal but complete run of ONE seed, from the real parsers and summaries: a floor under this number says the run saw less than
|
||||
one request on each road. (A real run holds many times more: the first A/A measures it.)"""
|
||||
norm = ab.Normalizer({7000: "A", 7001: "O", 7002: "h1", 7003: "h2", 7004: "h3"})
|
||||
headers = [["Host", "journey-a.test:7000"], ["User-Agent", "Mozilla/5.0"], ["Accept", "text/html"], ["Accept-Language", "en-US,en;q=0.5"], ["Accept-Encoding", "gzip, deflate"],
|
||||
["Connection", "keep-alive"], ["Upgrade-Insecure-Requests", "1"], ["Cookie", "theme=dark"]]
|
||||
request = {"role": "A", "method": "GET", "target": "/", "headers": headers, "body_length": 0}
|
||||
step = {"connects": ab.connect_summary(["127.0.0.1:7000"], norm), "dns": ab.dns_summary([("journey-a.test", 1, "lab")]), "udp": ab.udp_summary([], norm),
|
||||
"requests": ab.request_summary([request] * 3, norm), "name": "n", "ok": True, "idle": True, "url": "A/", "title": "t", "marker": "m", "cookies": [], "history_length": 2,
|
||||
"pages": 1, "extra": {}}
|
||||
tls = wc.parse_client_hello(build_hello())
|
||||
h2 = {"settings": [[1, 65536], [2, 0], [4, 131072], [5, 16384]], "frame_types_before_the_first_request": ["SETTINGS", "WINDOW_UPDATE"],
|
||||
"window_updates_before_the_first_request": [{"stream": 0, "increment": 12517377}], "priority": [], "priority_update": [], "headers_priority": [],
|
||||
"frames_after_the_first_request": 3, "settings_ack_sent_by_client": True,
|
||||
"requests": [{"stream": 1, "pseudo_order": [":method", ":path", ":authority", ":scheme"], "header_names": ["user-agent", "accept"], "headers": [[":method", "GET"], ["user-agent", "x"]],
|
||||
"end_stream": True}]}
|
||||
body = {"journey": {"steps": {"%02d" % i: step for i in range(17)}, "order": ["127.0.0.1:A"]}, "https": {"h2": {"v1": {"connections": [{"alpn": "h2", "tls": tls, "h2": h2}]}}},
|
||||
"webrtc": {"candidates": ["udp comp1 prio1 srflx <exit>"], "gathering": "complete"}, "idle": {"c1": {"destinations": {"connects": [], "dns": []}}},
|
||||
"lab": {"direct": {"witness_tcp": [], "witness_udp": [], "watcher": [], "doh_direct": [], "resolver_trap": [], "blind": []}}}
|
||||
leaves = ab.flatten({"11": body})
|
||||
by_category = {}
|
||||
for path in leaves:
|
||||
by_category[ab.category_of(path)] = by_category.get(ab.category_of(path), 0) + 1
|
||||
return by_category, len(leaves)
|
||||
|
||||
|
||||
def test_a_whole_synthetic_transcript_of_a_plausible_run_holds_the_leaves_the_floor_is_chosen_from():
|
||||
by_category, total = minimal_run()
|
||||
assert set(by_category) == {"journey", "https", "webrtc", "idle", "lab"}
|
||||
assert by_category["https"] > 100, "the ClientHello alone is a hundred leaves or more"
|
||||
assert by_category["journey"] > 17 * 30
|
||||
assert total > 700
|
||||
|
||||
|
||||
def test_the_script_names_the_categories_the_run_writes_and_the_e2e_floor_is_below_a_minimal_run():
|
||||
assert ab.CATEGORIES == ("journey", "https", "h3", "webrtc", "idle", "lab")
|
||||
import test_ab_network_e2e as e2e
|
||||
|
||||
_by_category, minimal = minimal_run()
|
||||
assert set(e2e.FLOOR) == {"linux", "win32"}
|
||||
assert all(0 < floor < minimal for floor in e2e.FLOOR.values()), "the floor is above what a minimal complete run of one seed holds (%d): a healthy run would be red" % minimal
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ the lab as a whole, with no browser
|
||||
def test_the_whole_lab_carries_a_client_through_its_gateway_and_writes_down_each_road_by_stage():
|
||||
"""The lab as a run assembles it (the journey site behind its tees, the HTTPS servers, the DoH, the gateway), driven by a plain client that speaks SOCKS5: the road of
|
||||
a page of the journey (through its tee), the road of an HTTPS page (through the gateway to a capture server), the stage each belongs to, the role that replaces each port."""
|
||||
import ssl
|
||||
|
||||
from fakeweb import journey_site
|
||||
|
||||
with ab.Lab(journey=True, wire=True, host="127.0.0.1") as lab:
|
||||
journey_site.STATE.set_step(3)
|
||||
assert lab.rec.phase == "journey.03", "the walk reaching a step moves the stage"
|
||||
port_a = int(lab.origin_a.rsplit(":", 1)[1])
|
||||
sock, code = _socks_connect(lab.gateway.port, "127.0.0.1", port_a)
|
||||
assert code == 0
|
||||
sock.sendall(b"GET /?noise=0 HTTP/1.1\r\nHost: journey-a.test:%d\r\nUser-Agent: smoke\r\nCookie: a=1\r\n\r\n" % port_a)
|
||||
assert _read_response(sock, b"</html>").startswith(b"HTTP/1.1 200")
|
||||
sock.close()
|
||||
lab.rec.set_phase("https.h1.v1")
|
||||
raw, code = _socks_connect(lab.gateway.port, "127.0.0.1", lab.h1.port)
|
||||
assert code == 0
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
context.check_hostname, context.verify_mode = False, ssl.CERT_NONE
|
||||
context.set_alpn_protocols(["h2", "http/1.1"])
|
||||
tls = context.wrap_socket(raw, server_hostname=ab.H1_NAME)
|
||||
tls.sendall(b"GET /wire.css HTTP/1.1\r\nHost: h1.lab.test:%d\r\nAccept: text/css\r\n\r\n" % lab.h1.port)
|
||||
assert b"p{color" in _read_response(tls, b"p{color")
|
||||
tls.close()
|
||||
journey = ab.phase_data(lab, "journey.03")
|
||||
assert journey["connects"] == {"order": ["127.0.0.1:A"], "counts": {"127.0.0.1:A": 1}}
|
||||
(signature,) = journey["requests"]
|
||||
assert signature == "GET A/?noise=0" and journey["requests"][signature]["headers"] == [["Host", "journey-a.test:A"], ["User-Agent", "smoke"], ["Cookie", "a=<v>"]]
|
||||
https = ab.phase_data(lab, "https.h1.v1")
|
||||
assert https["connects"]["order"] == ["127.0.0.1:h1"] and lab.roles[lab.h1.port] == "h1" and lab.roles[port_a] == "A"
|
||||
wire = ab.wire_summary(lab.h1, "https.h1.v1", lab.norm)
|
||||
(connection,) = wire["connections"]
|
||||
assert connection["alpn"] == "http/1.1" and connection["tls"]["extensions"]["server_name"] == ab.H1_NAME
|
||||
assert connection["http1"] == [{"request_line": "GET /wire.css HTTP/1.1", "headers": [["Host", "h1.lab.test:h1"], ["Accept", "text/css"]], "body_length": 0}]
|
||||
assert wire["quic"] == []
|
||||
assert ab.wire_summary(lab.h1, "journey.03", lab.norm) == {"connections": [], "quic": []}, "a connection belongs to the stage it arrived in"
|
||||
|
||||
|
||||
def test_the_direct_report_counts_what_reached_the_witness_or_the_watcher_and_forgives_only_the_road_to_the_relay():
|
||||
import collections
|
||||
|
||||
Direct = collections.namedtuple("Direct", "pid process protocol local remote status")
|
||||
|
||||
class Watcher:
|
||||
def __init__(self, direct, pids=(1,)):
|
||||
self.direct, self.watched_pids, self.process_names = direct, set(pids), ["firefox.exe"]
|
||||
|
||||
with ab.Lab(wire=True, host="127.0.0.1") as lab:
|
||||
clean = ab.direct_report(lab, Watcher([Direct(1, "firefox.exe", "udp", "x:1", "127.0.0.1:40999", "")]), None)
|
||||
assert clean == {"witness_tcp": [], "witness_udp": [], "watcher": [], "doh_direct": [], "resolver_trap": [],
|
||||
"blind": []}, "a datagram to the address of the relay (a port that is not the HTTP/3 server's) is the road"
|
||||
leaks = ab.direct_report(lab, Watcher([Direct(1, "firefox.exe", "udp", "x:1", "127.0.0.1:%d" % lab.h3.port, ""),
|
||||
Direct(1, "firefox.exe", "tcp", "x:2", "203.0.113.9:443", "ESTABLISHED")]), None)
|
||||
assert leaks["watcher"] == ["tcp firefox -> 203.0.113.9:443", "udp firefox -> 127.0.0.1:h3"]
|
||||
blind = ab.direct_report(lab, Watcher([], pids=()), None)
|
||||
assert blind["blind"] and "never saw a browser" in blind["blind"][0]
|
||||
with socket.create_connection(("127.0.0.1", lab.witness.port), timeout=60):
|
||||
pass
|
||||
from _waits import wait_until
|
||||
|
||||
assert wait_until(lambda: lab.witness.heard()["tcp"], 60, lambda: time.sleep(0.01)), "the witness never wrote the arrival down"
|
||||
assert ab.direct_report(lab, Watcher([]), None)["witness_tcp"] == ["tcp from 127.0.0.1"]
|
||||
trap = type("Trap", (), {"names": lambda self: ["leak-name.test"]})()
|
||||
assert ab.direct_report(lab, Watcher([]), trap)["resolver_trap"] == ["leak-name.test"]
|
||||
|
||||
|
||||
def test_the_sentinel_signature_leaves_out_the_sentinel_and_the_idle_window_ends_when_two_rounds_agree():
|
||||
with ab.Lab(host="127.0.0.1") as lab:
|
||||
lab.rec.event("connect", target="127.0.0.1:%d" % lab.site.port) # the sentinel's own road
|
||||
lab.rec.event("connect", target="192.0.2.53:443")
|
||||
lab.rec.event("udp", target="198.51.100.5:19302", message="stun-0x0001")
|
||||
lab.doh.queries.append(type("Q", (), {"name": ab.PAGE_NAME, "qtype": 1, "via": "lab"})())
|
||||
lab.doh.queries.append(type("Q", (), {"name": "background.test", "qtype": 1, "via": "lab"})())
|
||||
assert ab.sentinel_signature(lab) == {"connects": ["192.0.2.53:443"], "dns": ["background.test"], "udp": ["198.51.100.5:19302"]}
|
||||
lab.rec.event("connect", target="192.0.2.99:443")
|
||||
assert ab.sentinel_signature(lab)["connects"] == ["192.0.2.53:443", "192.0.2.99:443"]
|
||||
|
||||
|
||||
def _fake_run_engine(monkeypatch, make):
|
||||
"""Replace the process that runs one engine by a function that writes the transcript ``make(label)`` makes."""
|
||||
calls = []
|
||||
|
||||
def run_engine(binary, seal, label, seeds, out):
|
||||
calls.append((binary, seal, label, seeds))
|
||||
ab.write_json(out, make(label))
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(ab, "run_engine", run_engine)
|
||||
return calls
|
||||
|
||||
|
||||
def _ab_args(tmp_path, *extra):
|
||||
empty = tmp_path / "volatile.json"
|
||||
empty.write_text(json.dumps({"format": ab.VOLATILE_FORMAT, "entries": []}), encoding="utf-8")
|
||||
return ["ab", "--out", str(tmp_path / "out"), "--published-binary", "published-ff", "--published-seal", "pub.seal.json", "--volatile", str(empty), "--seeds", "11,12", *extra]
|
||||
|
||||
|
||||
def test_the_a_a_first_then_the_candidate_and_a_broken_control_stops_the_a_b(tmp_path, monkeypatch, capsys):
|
||||
calls = _fake_run_engine(monkeypatch, lambda label: transcript(label))
|
||||
assert ab.main(_ab_args(tmp_path, "--candidate", "cand-ff", "--candidate-seal", "cand.seal.json")) == 0
|
||||
assert [c[2] for c in calls] == ["firefox-68", "firefox-68-again", "candidate"], "the A/A runs first, the candidate last"
|
||||
assert calls[2][:2] == ("cand-ff", "cand.seal.json") and calls[0][:2] == ("published-ff", "pub.seal.json") and all(c[3] == (11, 12) for c in calls)
|
||||
names = sorted(p.name for p in (tmp_path / "out").iterdir())
|
||||
assert names == ["diff-a-a.json", "diff.json", "transcript-68-again.json", "transcript-68.json", "transcript-candidate.json"]
|
||||
capsys.readouterr()
|
||||
|
||||
def make(label):
|
||||
t = transcript(label)
|
||||
if label.endswith("-again"):
|
||||
t["seeds"]["11"]["webrtc"]["gathering"] = "noise"
|
||||
return t
|
||||
|
||||
calls = _fake_run_engine(monkeypatch, make)
|
||||
out = tmp_path / "broken"
|
||||
args = _ab_args(tmp_path, "--candidate", "cand-ff", "--candidate-seal", "cand.seal.json")
|
||||
args[2] = str(out)
|
||||
assert ab.main(args) == 2, "an A/A that differs is a broken control"
|
||||
assert [c[2] for c in calls] == ["firefox-68", "firefox-68-again"], "the A/B is not run on a broken control"
|
||||
proposal = json.loads((out / "volatile-proposal.json").read_text(encoding="utf-8"))
|
||||
assert proposal["patterns"] == ["seeds/*/webrtc/gathering"]
|
||||
assert "AB NETWORK A/A FAILED" in capsys.readouterr().out
|
||||
|
||||
calls = _fake_run_engine(monkeypatch, make)
|
||||
args = _ab_args(tmp_path, "--candidate", "cand-ff", "--candidate-seal", "cand.seal.json", "--measure")
|
||||
args[2] = str(tmp_path / "measure")
|
||||
assert ab.main(args) == 2 and [c[2] for c in calls] == ["firefox-68", "firefox-68-again", "candidate"]
|
||||
|
||||
|
||||
def test_a_candidate_that_differs_from_a_sound_control_is_red_and_the_a_a_alone_needs_no_candidate(tmp_path, monkeypatch):
|
||||
def make(label):
|
||||
t = transcript(label)
|
||||
if label == "candidate":
|
||||
t["seeds"]["12"]["https"]["h2"]["v1"]["connections"][0]["tls"]["cipher_suites"].pop()
|
||||
return t
|
||||
|
||||
_fake_run_engine(monkeypatch, make)
|
||||
assert ab.main(_ab_args(tmp_path, "--candidate", "cand-ff", "--candidate-seal", "cand.seal.json")) == 1
|
||||
diff = json.loads((tmp_path / "out" / "diff.json").read_text(encoding="utf-8"))
|
||||
assert diff["verdict"] == "red" and diff["differences"][0]["path"].endswith("/tls/cipher_suites/3")
|
||||
calls = _fake_run_engine(monkeypatch, lambda label: transcript(label))
|
||||
args = _ab_args(tmp_path, "--a-a")
|
||||
args[2] = str(tmp_path / "aa")
|
||||
assert ab.main(args) == 0 and [c[2] for c in calls] == ["firefox-68", "firefox-68-again"]
|
||||
assert ab.main(_ab_args(tmp_path)) == 2, "neither a candidate nor --a-a: nothing to run"
|
||||
@@ -0,0 +1,80 @@
|
||||
"""The network A/B oracle on a runner: the same journey on the local lab with the published firefox-68 engine twice (the A/A, the control), and, with a candidate, against the candidate.
|
||||
|
||||
scripts/ci_ab_network.py walks the P4 journey (17 steps), one HTTPS site (HTTP/1.1 and HTTP/2), one HTTP/3 site, one WebRTC page and two idle launches through a SOCKS5 gateway in coherent mode, with the fake DoH,
|
||||
a witness and the watcher of direct connections, and writes what the lab saw as a transcript: the hosts contacted in order, the DNS questions, the TLS ClientHello, the HTTP/2 frames, every request head in
|
||||
wire order, the QUIC parameters, the WebRTC candidates and the UDP path. Two transcripts are compared leaf by leaf; a leaf that differs is red with its path and both values. The leaves that differ between two
|
||||
runs of ONE engine are the noise (ci/ab-network-volatile.json), and they are born from the A/A: this test is where it runs.
|
||||
|
||||
* On a pull request (no candidate: ``INVPW_BINARY_PATH`` is the published engine and no ``INVISIBLE_SEAL_FILE``): the A/A, on the first seed. It saves both transcripts, the diff and a proposal of the volatile
|
||||
entries under ``$AB_ORACLE_OUT/network`` or, on a runner, ``$RUNNER_TEMP/invpw-evidence/ab-network`` (which the e2e jobs upload), on Linux and on Windows. A difference is a BROKEN CONTROL and red,
|
||||
until the list holds it. ``AB_NETWORK_MEASURE=1`` makes the run the MEASUREMENT of the noise: it fails only on what no list can excuse (a connection around the proxy, a run that saw fewer leaves than the
|
||||
floor, a run that did not finish) and says in its message how many leaves differed.
|
||||
* With a candidate (``INVPW_BINARY_PATH`` and ``INVISIBLE_SEAL_FILE`` as the gate's ab_oracle leg sets them): the A/A first, then the published engine against the candidate on every seed of
|
||||
ci/persona-seeds.json (key ``candidate``) or, without the file, the seeds of the A/B oracle of the page. The A/A is the control: if it is broken the A/B is not run.
|
||||
|
||||
Not skipped on a machine without the engine's own network: a skipped test is a red one in the judge, and an oracle that did not run says nothing. Nothing here reads a wall clock: the lab drives the journey by
|
||||
events, and the idle windows end at an event (see IDLE in scripts/ci_ab_network.py).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SCRIPT = ROOT / "scripts" / "ci_ab_network.py"
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
import ci_ab_network as oracle # noqa: E402
|
||||
|
||||
#: The fewest leaves a comparison holds, per system. A minimal but complete run of ONE seed (one request on each road, tests/test_ab_network.py) holds about 740; a real one holds several times that. A floor of
|
||||
#: 500 says "the run saw something on every road" and nothing more: it is raised to a fraction of the measured count once the A/A has measured it.
|
||||
FLOOR = {"linux": 500, "win32": 500}
|
||||
TIMEOUT_S = 40 * 60
|
||||
|
||||
|
||||
def _out(tmp_path: Path) -> Path:
|
||||
explicit = os.environ.get("AB_ORACLE_OUT")
|
||||
if explicit:
|
||||
return Path(explicit) / "network"
|
||||
runner = os.environ.get("RUNNER_TEMP")
|
||||
if runner:
|
||||
return Path(runner) / "invpw-evidence" / "ab-network"
|
||||
return tmp_path / "ab-network"
|
||||
|
||||
|
||||
def test_the_network_a_a_is_the_control_and_the_candidate_puts_on_the_wire_what_the_published_engine_puts(firefox_binary, tmp_path):
|
||||
seal = os.environ.get("INVISIBLE_SEAL_FILE")
|
||||
candidate = bool(seal and Path(seal).is_file())
|
||||
out = _out(tmp_path)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
floor = FLOOR["win32" if sys.platform == "win32" else "linux"]
|
||||
command = [sys.executable, "-u", str(SCRIPT), "ab", "--out", str(out), "--floor", str(floor)]
|
||||
if candidate:
|
||||
command += ["--candidate", firefox_binary, "--candidate-seal", seal]
|
||||
else:
|
||||
command += ["--a-a", "--published-binary", firefox_binary, "--seeds", str(oracle.default_seeds()[0])]
|
||||
done = subprocess.run(command, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=TIMEOUT_S)
|
||||
(out / "oracle.log").write_text(done.stdout + "\n--- stderr\n" + done.stderr, encoding="utf-8")
|
||||
verdict = [line for line in done.stdout.splitlines() if line.startswith(("DIFF ", "FAIL ", "AB NETWORK", "ERROR "))]
|
||||
control = out / "diff-a-a.json"
|
||||
assert control.is_file(), "the A/A did not run to its end (exit %s):\n%s\n%s" % (done.returncode, "\n".join(verdict[:40]), done.stderr[-1500:])
|
||||
aa = json.loads(control.read_text(encoding="utf-8"))
|
||||
measure = os.environ.get("AB_NETWORK_MEASURE") == "1" and not candidate
|
||||
if measure:
|
||||
assert not aa["direct"], "the lab was reached around the proxy:\n" + "\n".join(aa["direct"])
|
||||
assert aa["leaves"] >= floor, "the run compared %d leaves, fewer than the floor of %d" % (aa["leaves"], floor)
|
||||
print("A/A measurement: %d leaves compared (%s), %d differ, %d excused" % (aa["leaves"], aa["by_category"], len(aa["differences"]), aa["excused"]))
|
||||
return
|
||||
assert done.returncode != 2 or aa["verdict"] == "green", "BROKEN CONTROL: the published engine differs from itself on %d leaves (the list is ci/ab-network-volatile.json):\n%s" % (
|
||||
len(aa["differences"]), "\n".join(verdict[:60]))
|
||||
assert done.returncode == 0, "the network oracle is red:\n" + "\n".join(verdict[:60]) + "\n" + done.stderr[-1500:]
|
||||
assert aa["verdict"] == "green" and aa["differences"] == [] and aa["leaves"] >= floor
|
||||
if candidate:
|
||||
diff = json.loads((out / "diff.json").read_text(encoding="utf-8"))
|
||||
assert diff["verdict"] == "green" and diff["differences"] == [] and diff["direct"] == [] and diff["leaves"] >= floor
|
||||
@@ -0,0 +1,345 @@
|
||||
"""The wire parsers of the network A/B oracle (``tests/_wire_capture.py``), held to known inputs with no browser: a ClientHello made by hand and one made by Python's
|
||||
``ssl``, the frames of the ``h2`` library and of hand-made bytes, HTTP/1.1 heads as they are written.
|
||||
|
||||
What each test refuses: a hello parser that keeps the random, the session id, a key share or a PSK identity (the values of a connection, not of a client); a GREASE value
|
||||
that is not normalised; a peek that eats the bytes ssl then needs; an HTTP/1.1 reader that lowers the case of a header or forgets an empty one; an HTTP/2 tap that loses the
|
||||
order of the SETTINGS, the WINDOW_UPDATE of the connection, the PRIORITY frames or the order of the pseudo-headers.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import socket
|
||||
import ssl
|
||||
import struct
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
import _wire_capture as wc
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
RANDOM = b"\x11" * 32
|
||||
SESSION_ID = b"\x22" * 32
|
||||
KEY_BYTES = b"\x33" * 32
|
||||
IDENTITY = b"\x44" * 24
|
||||
BINDER = b"\x55" * 32
|
||||
|
||||
|
||||
def _u16(n: int) -> bytes:
|
||||
return struct.pack("!H", n)
|
||||
|
||||
|
||||
def _vec16(b: bytes) -> bytes:
|
||||
return _u16(len(b)) + b
|
||||
|
||||
|
||||
def _vec8(b: bytes) -> bytes:
|
||||
return bytes([len(b)]) + b
|
||||
|
||||
|
||||
def _ext(kind: int, body: bytes) -> bytes:
|
||||
return _u16(kind) + _vec16(body)
|
||||
|
||||
|
||||
def build_hello(suites=(0x2A2A, 0x1301, 0x1303, 0xC02B), extensions=None) -> bytes:
|
||||
"""A ClientHello record as a Firefox-like client writes it, with a GREASE suite, group, version and extension, and values that must NOT come out."""
|
||||
if extensions is None:
|
||||
extensions = [
|
||||
_ext(0x3A3A, b"\x00"), # a GREASE extension
|
||||
_ext(0, _vec16(b"\x00" + _vec16(b"wire.test"))), # server_name
|
||||
_ext(23, b""), # extended_master_secret
|
||||
_ext(65281, _vec8(b"")), # renegotiation_info
|
||||
_ext(10, _vec16(_u16(0x6A6A) + _u16(0x001D) + _u16(0x0017) + _u16(0x0018) + _u16(0x0100))), # supported_groups
|
||||
_ext(11, _vec8(b"\x00")), # ec_point_formats
|
||||
_ext(35, b""), # session_ticket
|
||||
_ext(16, _vec16(_vec8(b"h2") + _vec8(b"http/1.1"))), # alpn
|
||||
_ext(5, b"\x01" + _vec16(b"") + _vec16(b"")), # status_request
|
||||
_ext(34, _vec16(_u16(0x0403) + _u16(0x0503))), # delegated_credentials
|
||||
_ext(51, _vec16(_u16(0x0A0A) + _vec16(b"\x00") + _u16(0x001D) + _vec16(KEY_BYTES))), # key_share
|
||||
_ext(43, _vec8(_u16(0x7A7A) + _u16(0x0304) + _u16(0x0303))), # supported_versions
|
||||
_ext(13, _vec16(_u16(0x0403) + _u16(0x0804) + _u16(0x0401))), # signature_algorithms
|
||||
_ext(45, _vec8(b"\x01")), # psk_key_exchange_modes
|
||||
_ext(28, _u16(16385)), # record_size_limit
|
||||
_ext(27, _vec8(_u16(2))), # compress_certificate
|
||||
_ext(65037, b"\x00" + _u16(1) + _u16(1) + b"\x66" + _vec16(b"\x77" * 32) + _vec16(b"\x88" * 144)), # encrypted_client_hello
|
||||
_ext(21, b"\x00" * 40), # padding
|
||||
_ext(41, _vec16(_vec16(IDENTITY) + struct.pack("!I", 12345)) + _vec16(_vec8(BINDER))), # pre_shared_key
|
||||
]
|
||||
body = (_u16(0x0303) + RANDOM + _vec8(SESSION_ID) + _vec16(b"".join(_u16(s) for s in suites)) + _vec8(b"\x00") + _vec16(b"".join(extensions)))
|
||||
handshake = b"\x01" + len(body).to_bytes(3, "big") + body
|
||||
return b"\x16" + _u16(0x0301) + _vec16(handshake)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------------------ the ClientHello
|
||||
def test_a_client_hello_is_read_field_by_field_and_grease_is_one_word():
|
||||
hello = wc.parse_client_hello(build_hello())
|
||||
assert hello["record_version"] == "0x0301" and hello["handshake_version"] == "0x0303"
|
||||
assert hello["session_id_length"] == 32 and hello["compression_methods"] == [0]
|
||||
assert hello["cipher_suites"] == ["GREASE", "0x1301", "0x1303", "0xc02b"]
|
||||
assert hello["extension_order"][:4] == ["GREASE", "server_name", "extended_master_secret", "renegotiation_info"]
|
||||
assert hello["extension_order"][-1] == "pre_shared_key"
|
||||
assert hello["grease_extensions"] == 1
|
||||
x = hello["extensions"]
|
||||
assert x["server_name"] == "wire.test"
|
||||
assert x["supported_groups"] == ["GREASE", "0x001d", "0x0017", "0x0018", "0x0100"]
|
||||
assert x["ec_point_formats"] == [0]
|
||||
assert x["alpn"] == ["h2", "http/1.1"]
|
||||
assert x["signature_algorithms"] == ["0x0403", "0x0804", "0x0401"]
|
||||
assert x["delegated_credentials"] == ["0x0403", "0x0503"]
|
||||
assert x["supported_versions"] == ["GREASE", "0x0304", "0x0303"]
|
||||
assert x["psk_key_exchange_modes"] == [1]
|
||||
assert x["record_size_limit"] == 16385
|
||||
assert x["compress_certificate"] == ["0x0002"]
|
||||
assert x["key_share"] == [{"group": "GREASE", "key_length": 1}, {"group": "0x001d", "key_length": 32}]
|
||||
assert x["status_request"] == {"type": 1, "responder_ids_length": 0, "extensions_length": 0}
|
||||
assert x["padding"] == {"length": 40}
|
||||
assert x["encrypted_client_hello"] == {"type": 0, "kdf": 1, "aead": 1, "enc_length": 32, "payload_length": 144}
|
||||
assert x["pre_shared_key"] == {"identities": 1, "binder_lengths": [32]}
|
||||
assert x["renegotiation_info"] == {"length": 0}
|
||||
|
||||
|
||||
def test_nothing_that_is_random_or_secret_per_connection_is_kept():
|
||||
"""Known-bad: a parser that keeps the random, the session id, the bytes of a key share or a PSK identity makes two launches of one engine differ in every leaf."""
|
||||
text = json.dumps(wc.parse_client_hello(build_hello()), sort_keys=True)
|
||||
for name, value in (("the random", RANDOM), ("the session id", SESSION_ID), ("a key share", KEY_BYTES), ("a PSK identity", IDENTITY), ("a binder", BINDER)):
|
||||
assert value.hex() not in text, "%s is in the parsed hello" % name
|
||||
assert list(value) not in json.loads(text).values(), name
|
||||
assert "random" not in text.lower() or "random" not in json.loads(text)
|
||||
assert "12345" not in text, "the obfuscated ticket age is in the parsed hello"
|
||||
|
||||
|
||||
def test_a_hello_with_no_extensions_and_a_cut_hello():
|
||||
bare = wc.parse_client_hello(build_hello(extensions=[]))
|
||||
assert bare["extension_order"] == [] and bare["extensions"] == {}
|
||||
record = build_hello()
|
||||
with pytest.raises(wc.NotAClientHello):
|
||||
wc.parse_client_hello(record[:-10])
|
||||
with pytest.raises(wc.NotAClientHello):
|
||||
wc.parse_client_hello(b"\x17" + record[1:])
|
||||
with pytest.raises(wc.NotAClientHello):
|
||||
wc.parse_client_hello(b"\x16\x03\x01\x00\x04" + b"\x02\x00\x00\x00")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value,grease", [(0x0A0A, True), (0x1A1A, True), (0xFAFA, True), (0x0A1A, False), (0x1301, False), (0x0000, False), (0xAAAA, True)])
|
||||
def test_grease_is_recognised_by_its_two_equal_bytes(value, grease):
|
||||
assert wc.is_grease(value) is grease
|
||||
|
||||
|
||||
def test_the_peek_leaves_every_byte_in_the_socket_and_waits_for_a_hello_that_comes_in_pieces():
|
||||
record = build_hello()
|
||||
a, b = socket.socketpair()
|
||||
go = threading.Event()
|
||||
|
||||
def send() -> None:
|
||||
a.sendall(record[:3])
|
||||
go.wait(30)
|
||||
a.sendall(record[3:20])
|
||||
a.sendall(record[20:])
|
||||
|
||||
sender = threading.Thread(target=send, daemon=True)
|
||||
sender.start()
|
||||
found: list = []
|
||||
reader = threading.Thread(target=lambda: found.append(wc.peek_client_hello(b)), daemon=True)
|
||||
reader.start()
|
||||
go.set()
|
||||
reader.join(60)
|
||||
sender.join(60)
|
||||
assert found == [record]
|
||||
again = b""
|
||||
b.settimeout(30)
|
||||
while len(again) < len(record):
|
||||
again += b.recv(len(record) - len(again))
|
||||
assert again == record, "the peek consumed bytes"
|
||||
a.close()
|
||||
b.close()
|
||||
|
||||
|
||||
def test_a_peek_that_meets_a_closed_connection_or_a_stream_that_is_not_tls_says_so():
|
||||
a, b = socket.socketpair()
|
||||
a.sendall(b"GET / HTTP/1.1\r\n\r\n")
|
||||
with pytest.raises(wc.NotAClientHello):
|
||||
wc.peek_client_hello(b)
|
||||
a.close()
|
||||
b.close()
|
||||
c, d = socket.socketpair()
|
||||
c.close()
|
||||
with pytest.raises(ConnectionError):
|
||||
wc.peek_client_hello(d)
|
||||
d.close()
|
||||
# A peek cannot see the end of a stream that stops in the middle of a record (the bytes are still there to be looked at): the deadline is what ends it.
|
||||
e, f = socket.socketpair()
|
||||
e.sendall(b"\x16\x03\x01\x00")
|
||||
e.close()
|
||||
with pytest.raises(TimeoutError):
|
||||
wc.peek_client_hello(f, deadline_s=0.3)
|
||||
f.close()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------- a real client of Python's ssl
|
||||
def _client_context(alpn):
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(list(alpn))
|
||||
return context
|
||||
|
||||
|
||||
def test_the_hello_of_a_real_ssl_client_is_read_and_the_handshake_still_completes_and_http1_is_kept_as_written():
|
||||
with wc.WireServer(alpn=("http/1.1",), dns_names=("wire.test",)) as server:
|
||||
with socket.create_connection((server.address, server.port), timeout=60) as raw:
|
||||
with _client_context(["h2", "http/1.1"]).wrap_socket(raw, server_hostname="wire.test") as tls:
|
||||
tls.sendall(b"GET /wire.css?x=1 HTTP/1.1\r\nHost: wire.test\r\nX-Mixed-Case: A\r\nx-empty:\r\nAccept: */*\r\n\r\n")
|
||||
tls.settimeout(60)
|
||||
reply = b""
|
||||
while b"p{color" not in reply:
|
||||
chunk = tls.recv(4096)
|
||||
assert chunk, "the connection closed before the answer: %r" % reply
|
||||
reply += chunk
|
||||
version = tls.version()
|
||||
assert reply.startswith(b"HTTP/1.1 200")
|
||||
snapshot = server.snapshot()
|
||||
(connection,) = snapshot["connections"]
|
||||
hello = connection["tls"]
|
||||
assert hello["extensions"]["server_name"] == "wire.test"
|
||||
assert hello["extensions"]["alpn"] == ["h2", "http/1.1"]
|
||||
assert "0x0304" in hello["extensions"]["supported_versions"] and version == "TLSv1.3"
|
||||
assert hello["cipher_suites"] and all(s == "GREASE" or s.startswith("0x") for s in hello["cipher_suites"])
|
||||
assert hello["extension_order"].count("server_name") == 1
|
||||
assert connection["alpn"] == "http/1.1"
|
||||
(request,) = connection["http1"]
|
||||
assert request["request_line"] == "GET /wire.css?x=1 HTTP/1.1"
|
||||
assert request["headers"] == [["Host", "wire.test"], ["X-Mixed-Case", "A"], ["x-empty", ""], ["Accept", "*/*"]]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------------- HTTP/1.1
|
||||
def test_http1_heads_keep_their_case_order_empty_values_and_pipelining_across_any_split():
|
||||
wire = (b"POST /a HTTP/1.1\r\nHost: h\r\nContent-Length: 5\r\nX-Empty:\r\ncookie: a=1; b=2\r\n\r\nhello"
|
||||
b"GET /b HTTP/1.1\r\nHOST: h\r\nAccept: */* \r\n\r\n"
|
||||
b"POST /c HTTP/1.1\r\nHost: h\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nwxyz\r\n3\r\nabc\r\n0\r\n\r\n"
|
||||
b"GET /d HTTP/1.1\r\nHost: h\r\n\r\n")
|
||||
for step in (len(wire), 7, 1):
|
||||
parser = wc.Http1Parser()
|
||||
out = []
|
||||
for i in range(0, len(wire), step):
|
||||
out += parser.feed(wire[i:i + step])
|
||||
assert [r["request_line"] for r in out] == ["POST /a HTTP/1.1", "GET /b HTTP/1.1", "POST /c HTTP/1.1", "GET /d HTTP/1.1"], step
|
||||
assert out[0]["headers"] == [["Host", "h"], ["Content-Length", "5"], ["X-Empty", ""], ["cookie", "a=1; b=2"]]
|
||||
assert out[0]["body_length"] == 5 and out[2]["body_length"] == 7 and out[3]["body_length"] == 0
|
||||
assert out[1]["headers"] == [["HOST", "h"], ["Accept", "*/*"]]
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------------- HTTP/2
|
||||
def _h2_client_exchange(server, extra_wire: bytes = b"", settings=None, window_update: int = 0):
|
||||
"""One TLS connection to ``server`` that speaks HTTP/2 with the ``h2`` library: the given SETTINGS, a connection WINDOW_UPDATE, ``extra_wire`` (raw frames),
|
||||
then one GET whose headers are in a known order. Returns the status line header of the answer."""
|
||||
import h2.config
|
||||
import h2.connection
|
||||
import h2.events
|
||||
import h2.settings
|
||||
|
||||
conn = h2.connection.H2Connection(config=h2.config.H2Configuration(client_side=True))
|
||||
if settings:
|
||||
conn.local_settings = h2.settings.Settings(client=True, initial_values=settings)
|
||||
conn.initiate_connection()
|
||||
if window_update:
|
||||
conn.increment_flow_control_window(window_update)
|
||||
with socket.create_connection((server.address, server.port), timeout=60) as raw:
|
||||
with _client_context(["h2", "http/1.1"]).wrap_socket(raw, server_hostname="wire.test") as tls:
|
||||
assert tls.selected_alpn_protocol() == "h2"
|
||||
tls.settimeout(60)
|
||||
tls.sendall(conn.data_to_send() + extra_wire)
|
||||
conn.send_headers(1, [(":method", "GET"), (":path", "/wire.css"), (":authority", "wire.test"), (":scheme", "https"),
|
||||
("user-agent", "a-test"), ("accept", "text/css,*/*;q=0.1"), ("cookie", "a=1; b=2"), ("x-last", "z")], end_stream=True)
|
||||
tls.sendall(conn.data_to_send())
|
||||
status, ended = None, False
|
||||
while not ended:
|
||||
data = tls.recv(65536)
|
||||
assert data, "the server closed before the answer"
|
||||
for event in conn.receive_data(data):
|
||||
if isinstance(event, h2.events.ResponseReceived):
|
||||
status = dict(event.headers).get(b":status")
|
||||
elif isinstance(event, h2.events.StreamEnded):
|
||||
ended = True
|
||||
tls.sendall(conn.data_to_send())
|
||||
return status
|
||||
|
||||
|
||||
def _frame(kind: int, stream: int, body: bytes, flags: int = 0) -> bytes:
|
||||
return len(body).to_bytes(3, "big") + bytes([kind, flags]) + struct.pack("!I", stream) + body
|
||||
|
||||
|
||||
def test_an_h2_client_is_recorded_settings_window_updates_priorities_and_the_order_of_a_request():
|
||||
import h2.settings
|
||||
|
||||
priority = _frame(2, 3, struct.pack("!IB", 0, 200)) + _frame(2, 5, struct.pack("!IB", 0x80000000 | 3, 100))
|
||||
update = _frame(0x10, 0, struct.pack("!I", 3) + b"u=0, i")
|
||||
initial = {h2.settings.SettingCodes.ENABLE_PUSH: 0, h2.settings.SettingCodes.INITIAL_WINDOW_SIZE: 131072,
|
||||
h2.settings.SettingCodes.MAX_FRAME_SIZE: 16384}
|
||||
with wc.WireServer(alpn=("h2", "http/1.1"), h3=False) as server:
|
||||
assert _h2_client_exchange(server, priority + update, initial, window_update=12517377) == b"200"
|
||||
snapshot = server.snapshot()
|
||||
(connection,) = snapshot["connections"]
|
||||
assert connection["alpn"] == "h2" and connection["tls"]["extensions"]["alpn"] == ["h2", "http/1.1"]
|
||||
h2c = connection["h2"]
|
||||
got = {k: v for k, v in h2c["settings"]}
|
||||
assert got[2] == 0 and got[4] == 131072 and got[5] == 16384
|
||||
assert [k for k, _v in h2c["settings"]][:3] == [2, 4, 5] or {2, 4, 5} <= set(got), h2c["settings"]
|
||||
assert h2c["frame_types_before_the_first_request"][:2] == ["SETTINGS", "WINDOW_UPDATE"]
|
||||
assert "PRIORITY" in h2c["frame_types_before_the_first_request"] and "PRIORITY_UPDATE" in h2c["frame_types_before_the_first_request"]
|
||||
assert h2c["window_updates_before_the_first_request"] == [{"stream": 0, "increment": 12517377}]
|
||||
assert h2c["priority"] == [{"stream": 3, "depends_on": 0, "weight": 201, "exclusive": False},
|
||||
{"stream": 5, "depends_on": 3, "weight": 101, "exclusive": True}]
|
||||
assert h2c["priority_update"] == [{"stream": 0, "element": 3, "field": "u=0, i"}]
|
||||
(request,) = h2c["requests"]
|
||||
assert request["pseudo_order"] == [":method", ":path", ":authority", ":scheme"]
|
||||
assert request["header_names"] == ["user-agent", "accept", "cookie", "x-last"]
|
||||
assert request["headers"][4:6] == [["user-agent", "a-test"], ["accept", "text/css,*/*;q=0.1"]]
|
||||
|
||||
|
||||
def test_the_frame_tap_refuses_a_stream_that_does_not_start_with_the_preface_and_reads_a_split_one():
|
||||
tap = wc.FrameTap()
|
||||
with pytest.raises(ValueError):
|
||||
tap.feed(b"GET / HTTP/1.1\r\nHost: x\r\n\r\n")
|
||||
tap = wc.FrameTap()
|
||||
wire = wc.H2_PREFACE + _frame(4, 0, struct.pack("!HI", 4, 131072) + struct.pack("!HI", 1, 65536)) + _frame(8, 0, struct.pack("!I", 99))
|
||||
seen = []
|
||||
for i in range(0, len(wire), 5):
|
||||
seen += tap.feed(wire[i:i + 5])
|
||||
assert [f["type"] for f in seen] == ["SETTINGS", "WINDOW_UPDATE"]
|
||||
assert seen[0]["settings"] == [[4, 131072], [1, 65536]] and seen[1]["increment"] == 99
|
||||
summary = wc.summarize_frames(tap.frames)
|
||||
assert summary["settings"] == [[4, 131072], [1, 65536]] and summary["frames_after_the_first_request"] == 0
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------------- QUIC values
|
||||
def _varint(n: int) -> bytes:
|
||||
if n < 64:
|
||||
return bytes([n])
|
||||
if n < 16384:
|
||||
return struct.pack("!H", 0x4000 | n)
|
||||
return struct.pack("!I", 0x80000000 | n)
|
||||
|
||||
|
||||
def test_quic_transport_parameters_keep_their_order_and_drop_identifiers_and_grease():
|
||||
def param(i: int, value: bytes) -> bytes:
|
||||
return _varint(i) + _varint(len(value)) + value
|
||||
|
||||
raw = (param(0x04, _varint(15728640)) + param(0x05, _varint(12582912)) + param(0x0F, b"\x99" * 8) + param(27 + 31 * 5, b"\xaa\xbb")
|
||||
+ param(0x0B, _varint(20)) + param(0x0C, b"") + param(0x20, _varint(65535)) + param(0x2AB2, b""))
|
||||
out = wc.parse_quic_transport_parameters(raw)
|
||||
assert [p["id"] for p in out] == [4, 5, 15, "GREASE", 11, 12, 32, 0x2AB2]
|
||||
assert out[0] == {"id": 4, "name": "initial_max_data", "length": 4, "value": 15728640}
|
||||
assert out[2] == {"id": 15, "name": "initial_source_connection_id", "length": 8}
|
||||
assert out[3] == {"id": "GREASE", "length": 2}
|
||||
assert out[5] == {"id": 12, "name": "disable_active_migration", "length": 0}
|
||||
assert out[6]["value"] == 65535
|
||||
assert ("99" * 8) not in json.dumps(out)
|
||||
with pytest.raises(ValueError):
|
||||
wc.parse_quic_transport_parameters(param(4, _varint(1))[:-1])
|
||||
|
||||
|
||||
def test_h3_settings_are_named_and_a_reserved_identifier_is_grease():
|
||||
assert wc.h3_settings(None) is None
|
||||
assert wc.h3_settings({1: 65536, 7: 20, 0x21 + 0x1F * 3: 0, 0x33: 1}) == [["QPACK_MAX_TABLE_CAPACITY", 65536], ["QPACK_BLOCKED_STREAMS", 20], ["GREASE", 0],
|
||||
["H3_DATAGRAM", 1]]
|
||||
@@ -0,0 +1,66 @@
|
||||
"""What an HTTP/3 client says, read by the lab server (``tests/_wire_capture.py``, the QUIC side of ``WireServer``), held to a real ``aioquic`` client with no browser.
|
||||
|
||||
The oracle compares what two engines send over QUIC: the transport parameters in the order they come, the SETTINGS frame of HTTP/3 and the order of the headers of a request.
|
||||
This test makes the server read a client whose values it knows: the transport parameters aioquic sends, its SETTINGS, and a request with its pseudo-headers in the order it was
|
||||
given. A server that reads none of them (an empty list, no SETTINGS, the headers sorted) is red here.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import ssl
|
||||
|
||||
import pytest
|
||||
|
||||
import _wire_capture as wc
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
async def _get(port: int) -> int:
|
||||
from aioquic.asyncio import connect
|
||||
from aioquic.asyncio.protocol import QuicConnectionProtocol
|
||||
from aioquic.h3.connection import H3_ALPN, H3Connection
|
||||
from aioquic.h3.events import DataReceived, HeadersReceived
|
||||
from aioquic.quic.configuration import QuicConfiguration
|
||||
|
||||
class Client(QuicConnectionProtocol):
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self.http = H3Connection(self._quic)
|
||||
self.status = asyncio.get_event_loop().create_future()
|
||||
|
||||
def quic_event_received(self, event) -> None:
|
||||
for http_event in self.http.handle_event(event):
|
||||
if isinstance(http_event, HeadersReceived):
|
||||
self.headers = dict(http_event.headers)
|
||||
elif isinstance(http_event, DataReceived) and http_event.stream_ended and not self.status.done():
|
||||
self.status.set_result(int(self.headers[b":status"]))
|
||||
|
||||
configuration = QuicConfiguration(is_client=True, alpn_protocols=H3_ALPN, verify_mode=ssl.CERT_NONE, server_name="wire.test")
|
||||
async with connect("127.0.0.1", port, configuration=configuration, create_protocol=Client) as client:
|
||||
stream = client._quic.get_next_available_stream_id()
|
||||
client.http.send_headers(stream, [(b":method", b"GET"), (b":scheme", b"https"), (b":authority", b"wire.test"), (b":path", b"/wire.css"),
|
||||
(b"user-agent", b"a-test"), (b"accept", b"text/css"), (b"x-last", b"z")], end_stream=True)
|
||||
client.transmit()
|
||||
return await asyncio.wait_for(client.status, 60)
|
||||
|
||||
|
||||
def test_a_quic_client_is_recorded_transport_parameters_settings_and_the_order_of_a_request():
|
||||
with wc.WireServer(h3=True) as server:
|
||||
assert asyncio.run(_get(server.port)) == 200
|
||||
snapshot = server.snapshot()
|
||||
(connection,) = snapshot["quic"]
|
||||
assert connection["alpn"] == "h3"
|
||||
parameters = connection["transport_parameters"]
|
||||
names = [p.get("name") or p["id"] for p in parameters]
|
||||
assert names, "no transport parameter was read"
|
||||
assert "initial_max_data" in names and "initial_max_streams_bidi" in names and "max_idle_timeout" in names
|
||||
assert ("initial_source_connection_id" in names) and all("value" not in p for p in parameters if p.get("name") == "initial_source_connection_id")
|
||||
by_name = {p["name"]: p for p in parameters if "name" in p}
|
||||
assert by_name["initial_max_data"]["value"] > 0
|
||||
settings = dict(connection["h3_settings"])
|
||||
assert "QPACK_MAX_TABLE_CAPACITY" in settings and "QPACK_BLOCKED_STREAMS" in settings
|
||||
(request,) = connection["requests"]
|
||||
assert request["pseudo_order"] == [":method", ":scheme", ":authority", ":path"]
|
||||
assert request["header_names"] == ["user-agent", "accept", "x-last"]
|
||||
assert [n for n, _v in request["headers"]][:4] == [":method", ":scheme", ":authority", ":path"]
|
||||
Reference in new issue
Block a user