AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
test: enforce offline transport isolation by default (#1228)
Ilia Alshanetskyda39f88de426
diff --git a/tests/conftest.py b/tests/conftest.pyindex 6a973faf..2f93396a 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -5,15 +5,16 @@ from unittest import mockimport pytest+pytest_plugins = ["tests.network_guard"]+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "skills" / "last30days" / "scripts"))@pytest.fixture(autouse=True)def _no_arctic_network():- """Default the arctic-shift score lookup to a no-op so the suite never makes- a real network call. test_reddit_arctic overrides this fixture (same name) to- exercise the real lookup with http.get mocked."""- with mock.patch("lib.reddit_arctic.fetch_scores", return_value={}):+ """Default Arctic transport collaborators to no-ops outside adapter tests."""+ with mock.patch("lib.reddit_arctic.fetch_scores", return_value={}), \+ mock.patch("lib.reddit_arctic.fetch_listings", return_value=[]):yielddiff --git a/tests/network_guard.py b/tests/network_guard.pynew file mode 100644index 00000000..95ff54c4--- /dev/null+++ b/tests/network_guard.py@@ -0,0 +1,198 @@+"""Fail offline tests for attempted network access, including caught errors."""++import errno+import importlib+import ipaddress+import socket+import threading+import weakref+from urllib.parse import urlsplit++import pytest+++def _loopback(host):+ if host == "localhost":+ return True+ try:+ return ipaddress.ip_address(host).is_loopback+ except ValueError:+ return False++[email protected](autouse=True)+def network_guard():+ attempts = []+ owned_sockets = weakref.WeakKeyDictionary()+ ownership_lock = threading.RLock()+ original_bind = socket.socket.bind+ original_close = socket.socket.close+ original_detach = socket.socket.detach+ original_connect = socket.socket.connect+ original_connect_ex = socket.socket.connect_ex+ original_sendto = socket.socket.sendto+ original_sendmsg = getattr(socket.socket, "sendmsg", None)+ original_create_connection = socket.create_connection+ original_getaddrinfo = socket.getaddrinfo+ original_getnameinfo = socket.getnameinfo++ def deny(operation, address):+ attempts.append(f"{operation}: {address!r}")+ raise OSError(errno.ENETUNREACH, "offline test attempted an unowned network destination")++ def endpoint(family, kind, protocol, address):+ kind = int(kind) & ~(getattr(socket, "SOCK_NONBLOCK", 0) | getattr(socket, "SOCK_CLOEXEC", 0))+ if not protocol:+ protocol = {socket.SOCK_STREAM: socket.IPPROTO_TCP, socket.SOCK_DGRAM: socket.IPPROTO_UDP}.get(kind, 0)+ scope = address[3] if family == socket.AF_INET6 and len(address) > 3 else 0+ return family, str(ipaddress.ip_address(address[0])), address[1], scope, kind, protocol++ def live_endpoints():+ with ownership_lock:+ return {value for sock, value in owned_sockets.items() if sock.fileno() >= 0}++ def destinations(operation, host, port, family=0, kind=0, protocol=0, flags=0):+ if not _loopback(host):+ deny(operation, (host, port))+ owned = live_endpoints()+ hosts = {entry[1] for entry in owned} if host == "localhost" else {host}+ answers = []+ for address in sorted(hosts):+ try:+ candidates = original_getaddrinfo(+ address, port, family, kind, protocol,+ flags | socket.AI_NUMERICHOST | socket.AI_NUMERICSERV,+ )+ except socket.gaierror:+ continue+ for item in candidates:+ if endpoint(item[0], item[1], item[2], item[4]) in owned and item not in answers:+ answers.append(item)+ if not answers:+ deny(operation, (host, port))+ return answers++ def checked_address(operation, sock, address):+ if sock.family not in (socket.AF_INET, socket.AF_INET6):+ return address+ return destinations(operation, address[0], address[1], sock.family, sock.type, sock.proto)[0][4]++ def bind(sock, address):+ if sock.family in (socket.AF_INET, socket.AF_INET6):+ host = address[0]+ if isinstance(host, bytes):+ try:+ host = host.decode("ascii")+ except UnicodeDecodeError:+ deny("bind", address)+ if not isinstance(host, str):+ raise TypeError("socket host must be str or bytes")+ if host == "localhost":+ host = "127.0.0.1" if sock.family == socket.AF_INET else "::1"+ elif host == "":+ host = "0.0.0.0" if sock.family == socket.AF_INET else "::"+ try:+ numeric = ipaddress.ip_address(host)+ except ValueError:+ deny("bind", address)+ if numeric.version != (4 if sock.family == socket.AF_INET else 6):+ raise socket.gaierror(socket.EAI_FAMILY, "IP address does not match the socket family")+ address = (str(numeric), *address[1:])+ result = original_bind(sock, address)+ if sock.family in (socket.AF_INET, socket.AF_INET6) and _loopback(address[0]):+ with ownership_lock:+ owned_sockets[sock] = endpoint(sock.family, sock.type, sock.proto, sock.getsockname())+ return result++ def close(sock):+ with ownership_lock:+ owned_sockets.pop(sock, None)+ return original_close(sock)++ def detach(sock):+ with ownership_lock:+ owned_sockets.pop(sock, None)+ return original_detach(sock)++ def connect(sock, address):+ return original_connect(sock, checked_address("connect", sock, address))++ def connect_ex(sock, address):+ return original_connect_ex(sock, checked_address("connect_ex", sock, address))++ def sendto(sock, data, *args):+ address = checked_address("sendto", sock, args[-1])+ return original_sendto(sock, data, *args[:-1], address)++ def sendmsg(sock, buffers, ancdata=(), flags=0, address=None):+ if address is None:+ return original_sendmsg(sock, buffers, ancdata, flags)+ return original_sendmsg(sock, buffers, ancdata, flags, checked_address("sendmsg", sock, address))++ def create_connection(address, *args, **kwargs):+ destinations("create_connection", address[0], address[1], kind=socket.SOCK_STREAM)+ return original_create_connection(address, *args, **kwargs)++ def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):+ return destinations("getaddrinfo", host, port, family, type, proto, flags)++ def local_address(operation, host, ipv4_only=False):+ if not _loopback(host):+ deny(operation, host)+ address = ipaddress.ip_address("127.0.0.1" if host == "localhost" else host)+ if ipv4_only and address.version != 4:+ raise socket.gaierror(socket.EAI_FAMILY, "IPv4 lookup requires an IPv4 address")+ return str(address)++ def gethostbyname(host):+ return local_address("gethostbyname", host, ipv4_only=True)++ def gethostbyname_ex(host):+ address = local_address("gethostbyname_ex", host, ipv4_only=True)+ return "localhost" if host == "localhost" else address, [], [address]++ def gethostbyaddr(host):+ return "localhost", [], [local_address("gethostbyaddr", host)]++ def getnameinfo(address, flags):+ required = socket.NI_NUMERICHOST | socket.NI_NUMERICSERV+ if not _loopback(address[0]) or address[0] == "localhost" or flags & required != required:+ deny("getnameinfo", address)+ return original_getnameinfo(address, flags)++ with pytest.MonkeyPatch.context() as patch:+ patch.setattr(socket.socket, "bind", bind)+ patch.setattr(socket.socket, "close", close)+ patch.setattr(socket.socket, "detach", detach)+ patch.setattr(socket.socket, "connect", connect)+ patch.setattr(socket.socket, "connect_ex", connect_ex)+ patch.setattr(socket.socket, "sendto", sendto)+ if original_sendmsg is not None:+ patch.setattr(socket.socket, "sendmsg", sendmsg)+ patch.setattr(socket, "create_connection", create_connection)+ patch.setattr(socket, "getaddrinfo", getaddrinfo)+ patch.setattr(socket, "gethostbyname", gethostbyname)+ patch.setattr(socket, "gethostbyname_ex", gethostbyname_ex)+ patch.setattr(socket, "gethostbyaddr", gethostbyaddr)+ patch.setattr(socket, "getnameinfo", getnameinfo)+ try:+ bounded_get = importlib.import_module("lib.bounded_get")+ except ModuleNotFoundError as error:+ if error.name not in ("lib", "lib.bounded_get"):+ raise+ else:+ original_get = bounded_get.get++ def worker_get(req, *args, **kwargs):+ target = urlsplit(req.full_url)+ address = (target.hostname, target.port if target.port is not None else (443 if target.scheme == "https" else 80))+ if target.hostname == "localhost":+ # Isolated workers resolve the hostname outside the parent socket patches.+ deny("bounded_get", address)+ destinations("bounded_get", *address, kind=socket.SOCK_STREAM)+ return original_get(req, *args, **kwargs)++ patch.setattr(bounded_get, "get", worker_get)+ yield+ if attempts:+ pytest.fail("Unexpected network attempts:\n" + "\n".join(attempts))diff --git a/tests/test_chrome_cdp.py b/tests/test_chrome_cdp.pyindex c0123b1d..d760f15b 100644--- a/tests/test_chrome_cdp.py+++ b/tests/test_chrome_cdp.py@@ -389,9 +389,8 @@ def test_wsconn_connect_refuses_wss():def test_read_x_cookies_no_reachable_endpoint_returns_none():- # A port with nothing listening: connection refused, returns None.- with socket.socket() as s:- s.bind(("127.0.0.1", 0))- dead_port = s.getsockname()[1]- config = {"BROWSER_CDP_URL": f"http://127.0.0.1:{dead_port}", "BROWSER_CONSENT": "true"}- assert chrome_cdp.read_x_cookies(config) is None+ config = {"BROWSER_CDP_URL": "http://127.0.0.1:18800", "BROWSER_CONSENT": "true"}+ with mock.patch("urllib.request.urlopen", side_effect=ConnectionRefusedError) as request:+ assert chrome_cdp.read_x_cookies(config) is None+ request.assert_called_once()+ assert request.call_args.args[0] == "http://127.0.0.1:18800/json/version"diff --git a/tests/test_doctor_cache.py b/tests/test_doctor_cache.pyindex 44713428..12d7ea94 100644--- a/tests/test_doctor_cache.py+++ b/tests/test_doctor_cache.py@@ -76,6 +76,7 @@ class _Hermetic:self.probe_spy = mock.Mock(side_effect=probe or _fake_probe)self._patches = [mock.patch("lib.health.probe_dependency", self.probe_spy),+ mock.patch("lib.doctor._probe_sources", return_value={}),mock.patch("lib.bird_x.is_bird_installed", return_value=False),mock.patch("lib.bird_x.set_credentials", lambda *a, **k: None),mock.patch("lib.bird_x.get_bird_status", return_value=dict(BIRD_STATUS_OFF)),diff --git a/tests/test_env_cookies.py b/tests/test_env_cookies.pyindex a255e777..896b1781 100644--- a/tests/test_env_cookies.py+++ b/tests/test_env_cookies.py@@ -197,7 +197,8 @@ class TestGetConfigCookieIntegration:"FROM_BROWSER": "auto","LAST30DAYS_CONFIG_DIR": "",}- with patch.dict(os.environ, env_patch, clear=False):+ with patch.dict(os.environ, env_patch, clear=False), \+ patch("lib.chrome_cdp.read_x_cookies", return_value=None):config = get_config(policy=ConfigLoadPolicy(browser_cookies="read"))assert config["AUTH_TOKEN"] == "browser_tok"assert config["CT0"] == "browser_ct0"diff --git a/tests/test_last_run_state.py b/tests/test_last_run_state.pyindex af445cda..54677614 100644--- a/tests/test_last_run_state.py+++ b/tests/test_last_run_state.py@@ -194,6 +194,7 @@ class LastRunStateTests(unittest.TestCase):config = {"OPENROUTER_API_KEY": "or-test"}with mock.patch.object(cli.env, "CONFIG_DIR", config_dir), \mock.patch.object(cli.env, "get_config", return_value=config), \+ mock.patch("lib.resolve.auto_resolve", return_value={}), \mock.patch.object(cli.pipeline, "diagnose", return_value=_diag()), \mock.patch.object(cli.pipeline, "run", return_value=fresh_report) as run_mock, \mock.patch.object(cli.ui, "ProgressDisplay"), \diff --git a/tests/test_network_guard.py b/tests/test_network_guard.pynew file mode 100644index 00000000..1ce2f3b5--- /dev/null+++ b/tests/test_network_guard.py@@ -0,0 +1,634 @@+import os+import socket+import subprocess+import sys+import textwrap+import uuid+from pathlib import Path++import pytest+++def _run_probe(tmp_path, body):+ probe = tmp_path / "test_probe.py"+ probe.write_text(textwrap.dedent(body), encoding="utf-8")+ root = Path(__file__).resolve().parents[1]+ environment = dict(os.environ)+ environment["PYTHONPATH"] = os.pathsep.join([str(root), environment.get("PYTHONPATH", "")])+ return subprocess.run(+ [sys.executable, "-m", "pytest", "-q", "--tb=short", "-p", "tests.network_guard", str(probe)],+ cwd=tmp_path, env=environment, capture_output=True, text=True, timeout=30,+ )++[email protected]("operation", [+ "socket.create_connection((host, 443))",+ "socket.getaddrinfo(host, 443)",+ "socket.gethostbyname(host)",+ "socket.gethostbyname_ex(host)",+ "socket.gethostbyaddr(host)",+ "socket.socket().connect((host, 443))",+ "socket.socket().connect_ex((host, 443))",+ "socket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(b'probe', (host, 53))",+])+def test_swallowed_network_attempt_fails_test(tmp_path, operation):+ host = f"forbidden-{uuid.uuid4().hex}.invalid"+ result = _run_probe(tmp_path, f"""+ import socket++ def test_caught_transport_error():+ host = {host!r}+ try:+ {operation}+ except OSError:+ pass+ """)+ assert result.returncode == 1, result.stdout + result.stderr+ assert "1 passed, 1 error" in result.stdout+ assert "Unexpected network attempts" in result.stdout+ assert host in result.stdout++[email protected]("operation, host, expected", [+ ("gethostbyname", "localhost", "127.0.0.1"),+ ("gethostbyname", "127.0.0.2", "127.0.0.2"),+ ("gethostbyname_ex", "localhost", ("localhost", [], ["127.0.0.1"])),+ ("gethostbyname_ex", "127.0.0.2", ("127.0.0.2", [], ["127.0.0.2"])),+ ("gethostbyaddr", "localhost", ("localhost", [], ["127.0.0.1"])),+ ("gethostbyaddr", "127.0.0.2", ("localhost", [], ["127.0.0.2"])),+ ("gethostbyaddr", "::1", ("localhost", [], ["::1"])),+])+def test_loopback_resolvers_do_not_delegate_to_libc(tmp_path, operation, host, expected):+ result = _run_probe(tmp_path, f"""+ import socket++ calls = []+ def system_resolver(host):+ calls.append(host)+ return {expected!r}+ socket.{operation} = system_resolver++ def test_local_answer():+ assert socket.{operation}({host!r}) == {expected!r}+ assert calls == [], 'loopback lookup reached the system resolver'+ """)+ assert result.returncode == 0, result.stdout + result.stderr+ assert "1 passed" in result.stdout++[email protected]("operation", ["gethostbyname", "gethostbyname_ex"])+def test_ipv4_resolvers_reject_ipv6_without_libc(tmp_path, operation):+ result = _run_probe(tmp_path, f"""+ import socket+ import pytest++ calls = []+ def system_resolver(host):+ calls.append(host)+ raise socket.gaierror(socket.EAI_FAMILY, 'IPv4 lookup requires an IPv4 address')+ socket.{operation} = system_resolver++ def test_ipv4_only_contract():+ with pytest.raises(socket.gaierror):+ socket.{operation}('::1')+ assert calls == [], 'IPv6 input reached the IPv4 system resolver'+ """)+ assert result.returncode == 0, result.stdout + result.stderr+ assert "1 passed" in result.stdout+++def test_owned_getaddrinfo_delegates_only_numeric_addresses_and_services(tmp_path):+ result = _run_probe(tmp_path, """+ import socket++ system_resolver = socket.getaddrinfo+ calls = []+ def numeric_resolver(host, port, family=0, type=0, proto=0, flags=0):+ calls.append((host, port, flags))+ assert flags & socket.AI_NUMERICHOST, 'system resolver lacks AI_NUMERICHOST'+ assert flags & socket.AI_NUMERICSERV, 'system resolver lacks AI_NUMERICSERV'+ return system_resolver(host, port, family, type, proto, flags)+ socket.getaddrinfo = numeric_resolver++ def test_owned_localhost():+ with socket.socket() as server:+ server.bind(('127.0.0.1', 0))+ port = server.getsockname()[1]+ result = socket.getaddrinfo('localhost', port, type=socket.SOCK_STREAM)+ assert {item[4] for item in result} == {('127.0.0.1', port)}+ assert calls+ assert all(host == '127.0.0.1' for host, _, _ in calls)+ """)+ assert result.returncode == 0, result.stdout + result.stderr+ assert "1 passed" in result.stdout++[email protected]("form", ["text", "bytes", "four_byte_hostname"])+def test_bind_hostname_is_denied_before_original_method(tmp_path, form):+ host = f"bind-{uuid.uuid4().hex}.invalid"+ if form == "bytes":+ host = host.encode("ascii")+ elif form == "four_byte_hostname":+ host = b"abcd"+ result = _run_probe(tmp_path, f"""+ import socket++ delegated = []+ def original_bind(sock, address):+ delegated.append(address)+ raise OSError('controlled bind resolver canary; no DNS was called')+ socket.socket.bind = original_bind++ def test_denied_hostname():+ with socket.socket() as server:+ try:+ server.bind(({host!r}, 0))+ except OSError:+ pass+ assert delegated == [], 'hostname reached original bind'+ """)+ assert result.returncode == 1, result.stdout + result.stderr+ assert "1 passed, 1 error" in result.stdout, result.stdout + result.stderr+ assert "Unexpected network attempts" in result.stdout+ assert "bind:" in result.stdout++[email protected]("family, host, expected", [+ ("AF_INET", "localhost", "127.0.0.1"),+ ("AF_INET", "", "0.0.0.0"),+ ("AF_INET", "127.0.0.1", "127.0.0.1"),+ ("AF_INET", b"localhost", "127.0.0.1"),+ ("AF_INET", b"", "0.0.0.0"),+ ("AF_INET", b"127.0.0.1", "127.0.0.1"),+ ("AF_INET6", "localhost", "::1"),+ ("AF_INET6", "", "::"),+ ("AF_INET6", "::1", "::1"),+ ("AF_INET6", b"localhost", "::1"),+ ("AF_INET6", b"", "::"),+ ("AF_INET6", b"::1", "::1"),+])+def test_bind_passes_numeric_host_and_preserves_sockaddr_fields(tmp_path, family, host, expected):+ trailing = (0,) if family == "AF_INET" else (0, 17, 29)+ result = _run_probe(tmp_path, f"""+ import socket++ delegated = []+ def original_bind(sock, address):+ delegated.append(address)+ raise OSError('controlled numeric bind; no system call was made')+ socket.socket.bind = original_bind++ class BoundSocket:+ family = socket.{family}++ def test_numeric_boundary():+ try:+ socket.socket.bind(BoundSocket(), ({host!r}, *{trailing!r}))+ except OSError:+ pass+ assert delegated == [({expected!r}, *{trailing!r})]+ """)+ assert result.returncode == 0, result.stdout + result.stderr+ assert "1 passed" in result.stdout++[email protected]("family, host", [("AF_INET", "::1"), ("AF_INET6", "127.0.0.1")])+def test_bind_rejects_wrong_ip_family_before_original_method(tmp_path, family, host):+ result = _run_probe(tmp_path, f"""+ import socket+ import pytest++ delegated = []+ def original_bind(sock, address):+ delegated.append(address)+ raise socket.gaierror(socket.EAI_FAMILY, 'wrong address family')+ socket.socket.bind = original_bind++ class BoundSocket:+ family = socket.{family}++ def test_family_error_is_local():+ with pytest.raises(socket.gaierror) as error:+ socket.socket.bind(BoundSocket(), ({host!r}, 0))+ assert error.value.errno == socket.EAI_FAMILY+ assert delegated == [], 'wrong-family host reached original bind'+ """)+ assert result.returncode == 0, result.stdout + result.stderr+ assert "1 passed" in result.stdout+++def test_bind_preserves_unix_socket_address(tmp_path):+ if not hasattr(socket, "AF_UNIX"):+ pytest.skip("AF_UNIX is unavailable on this platform")+ result = _run_probe(tmp_path, """+ import socket++ delegated = []+ def original_bind(sock, address):+ delegated.append(address)+ raise OSError('controlled Unix bind; no system call was made')+ socket.socket.bind = original_bind++ class BoundSocket:+ family = socket.AF_UNIX++ def test_unix_boundary():+ try:+ socket.socket.bind(BoundSocket(), '/tmp/owned-fixture.sock')+ except OSError:+ pass+ assert delegated == ['/tmp/owned-fixture.sock']+ """)+ assert result.returncode == 0, result.stdout + result.stderr+ assert "1 passed" in result.stdout++[email protected]("kind", ["SOCK_STREAM", "SOCK_DGRAM"])+def test_localhost_bind_preserves_real_owned_transport(tmp_path, kind):+ canary = f"bound-{uuid.uuid4().hex}".encode("ascii")+ result = _run_probe(tmp_path, f"""+ import socket++ def test_owned_bound_transport():+ with socket.socket(socket.AF_INET, socket.{kind}) as server:+ server.bind(('localhost', 0))+ server.settimeout(1)+ assert server.getsockname()[0] == '127.0.0.1'+ address = ('localhost', server.getsockname()[1])+ if socket.{kind} == socket.SOCK_STREAM:+ server.listen()+ with socket.create_connection(address) as client:+ client.sendall({canary!r})+ accepted, _ = server.accept()+ with accepted:+ assert accepted.recv(128) == {canary!r}+ else:+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as client:+ client.sendto({canary!r}, address)+ assert server.recv(128) == {canary!r}+ """)+ assert result.returncode == 0, result.stdout + result.stderr+ assert "1 passed" in result.stdout++[email protected]("flags", [0, socket.NI_NUMERICHOST, socket.NI_NUMERICSERV])+def test_getnameinfo_rejects_resolver_modes_without_libc(tmp_path, flags):+ result = _run_probe(tmp_path, f"""+ import socket++ calls = []+ def system_resolver(address, flags):+ calls.append((address, flags))+ return 'resolver-host', 'resolver-service'+ socket.getnameinfo = system_resolver++ def test_no_reverse_resolution():+ try:+ socket.getnameinfo(('127.0.0.2', 80), {flags!r})+ except OSError:+ pass+ assert calls == [], 'reverse name/service lookup reached the system resolver'+ """)+ assert result.returncode == 1, result.stdout + result.stderr+ assert "1 passed, 1 error" in result.stdout+ assert "Unexpected network attempts" in result.stdout+ assert "getnameinfo" in result.stdout++[email protected]("address", [("127.0.0.2", 80), ("::1", 80, 0, 0)])+def test_getnameinfo_numeric_mode_remains_usable(tmp_path, address):+ result = _run_probe(tmp_path, f"""+ import socket++ system_resolver = socket.getnameinfo+ calls = []+ def numeric_resolver(address, flags):+ calls.append((address, flags))+ assert flags & socket.NI_NUMERICHOST+ assert flags & socket.NI_NUMERICSERV+ return system_resolver(address, flags)+ socket.getnameinfo = numeric_resolver++ def test_numeric_answer():+ flags = socket.NI_NUMERICHOST | socket.NI_NUMERICSERV+ assert socket.getnameinfo({address!r}, flags) == ({address[0]!r}, '80')+ assert calls == [({address!r}, flags)]+ """)+ assert result.returncode == 0, result.stdout + result.stderr+ assert "1 passed" in result.stdout++[email protected]("address", [("203.0.113.8", 443), ("127.0.0.1", 18800), ("localhost", 9222)])+def test_unowned_ip_or_loopback_connection_fails_test(tmp_path, address):+ result = _run_probe(tmp_path, f"""+ import socket++ def test_no_ambient_service():+ try:+ socket.create_connection({address!r})+ except OSError:+ pass+ """)+ assert result.returncode == 1, result.stdout + result.stderr+ assert "1 passed, 1 error" in result.stdout+ assert "Unexpected network attempts" in result.stdout+ assert address[0] in result.stdout+++def test_swallowed_worker_network_attempt_fails_test(tmp_path):+ host = f"worker-{uuid.uuid4().hex}.invalid"+ result = _run_probe(tmp_path, f"""+ import socket+ from concurrent.futures import ThreadPoolExecutor++ def test_worker():+ def work():+ try:+ socket.create_connection(({host!r}, 443))+ except OSError:+ return []+ with ThreadPoolExecutor(max_workers=1) as executor:+ assert executor.submit(work).result() == []+ """)+ assert result.returncode == 1, result.stdout + result.stderr+ assert "1 passed, 1 error" in result.stdout+ assert "Unexpected network attempts" in result.stdout+ assert host in result.stdout+++def test_owned_loopback_transport_remains_real(tmp_path):+ result = _run_probe(tmp_path, """+ import socket++ def test_local_exchange():+ with socket.socket() as server:+ server.bind(('127.0.0.1', 0))+ server.listen()+ with socket.create_connection(('localhost', server.getsockname()[1])) as client:+ client.sendall(b'owned transport')+ connection, _ = server.accept()+ with connection:+ assert connection.recv(64) == b'owned transport'+ """)+ assert result.returncode == 0, result.stdout + result.stderr+ assert "1 passed" in result.stdout+++def test_owned_port_does_not_authorize_another_loopback_address(tmp_path):+ canary = f"address-{uuid.uuid4().hex}"+ result = _run_probe(tmp_path, f"""+ import socket+ import pytest++ ambient = socket.socket()+ ambient.bind(('127.0.0.2', 0))+ ambient.listen()+ ambient.setblocking(False)++ def test_exact_address():+ with ambient, socket.socket() as owned:+ owned.bind(('127.0.0.1', ambient.getsockname()[1]))+ try:+ with socket.create_connection(ambient.getsockname()) as client:+ client.sendall({canary.encode()!r})+ except OSError:+ pass+ with pytest.raises(BlockingIOError):+ accepted, _ = ambient.accept()+ with accepted:+ assert accepted.recv(128) != {canary.encode()!r}+ """)+ assert result.returncode == 1, result.stdout + result.stderr+ assert "1 passed, 1 error" in result.stdout+ assert "Unexpected network attempts" in result.stdout+ assert "127.0.0.2" in result.stdout++[email protected]("operation", ["sendto", "sendmsg"])+def test_owned_tcp_port_does_not_authorize_udp(tmp_path, operation):+ if operation == "sendmsg" and not hasattr(socket.socket, "sendmsg"):+ pytest.skip("sendmsg is unavailable on this platform")+ canary = f"protocol-{uuid.uuid4().hex}"+ call = f"sender.sendto({canary.encode()!r}, address)" if operation == "sendto" else f"sender.sendmsg([{canary.encode()!r}], [], 0, address)"+ result = _run_probe(tmp_path, f"""+ import socket+ import pytest++ ambient = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ ambient.bind(('127.0.0.1', 0))+ ambient.setblocking(False)++ def test_exact_transport():+ with ambient, socket.socket() as owned, socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sender:+ address = ambient.getsockname()+ owned.bind(address)+ try:+ {call}+ except OSError:+ pass+ with pytest.raises(BlockingIOError):+ assert ambient.recv(128) != {canary.encode()!r}+ """)+ assert result.returncode == 1, result.stdout + result.stderr+ assert "1 passed, 1 error" in result.stdout+ assert "Unexpected network attempts" in result.stdout+ assert operation in result.stdout++[email protected]("operation", ["sendto", "sendmsg"])+def test_owned_udp_transport_remains_real(tmp_path, operation):+ if operation == "sendmsg" and not hasattr(socket.socket, "sendmsg"):+ pytest.skip("sendmsg is unavailable on this platform")+ canary = f"owned-{uuid.uuid4().hex}"+ call = f"sender.sendto({canary.encode()!r}, address)" if operation == "sendto" else f"sender.sendmsg([{canary.encode()!r}], [], 0, address)"+ result = _run_probe(tmp_path, f"""+ import socket++ def test_udp_exchange():+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server, socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sender:+ server.bind(('127.0.0.1', 0))+ server.settimeout(1)+ address = ('localhost', server.getsockname()[1])+ {call}+ assert server.recv(128) == {canary.encode()!r}+ """)+ assert result.returncode == 0, result.stdout + result.stderr+ assert "1 passed" in result.stdout+++def test_guard_restores_every_patched_socket_function(tmp_path):+ result = _run_probe(tmp_path, """+ import atexit+ import socket++ socket_names = ['bind', 'close', 'detach', 'connect', 'connect_ex', 'sendto']+ if hasattr(socket.socket, 'sendmsg'):+ socket_names.append('sendmsg')+ module_names = ['create_connection', 'getaddrinfo', 'gethostbyname',+ 'gethostbyname_ex', 'gethostbyaddr', 'getnameinfo']+ originals = [(socket.socket, name, getattr(socket.socket, name)) for name in socket_names]+ originals += [(socket, name, getattr(socket, name)) for name in module_names]++ def verify_restored():+ for owner, name, original in originals:+ assert getattr(owner, name) is original, f'{name} was not restored'+ print(f'restored-{len(originals)}-socket-functions')+ atexit.register(verify_restored)++ def test_owned_transport():+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server, socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sender:+ server.bind(('127.0.0.1', 0))+ server.settimeout(1)+ sender.sendto(b'restoration transport', server.getsockname())+ assert server.recv(64) == b'restoration transport'+ """)+ assert result.returncode == 0, result.stdout + result.stderr+ assert "1 passed" in result.stdout+ count = 12 + int(hasattr(socket.socket, "sendmsg"))+ assert f"restored-{count}-socket-functions" in result.stdout, result.stdout + result.stderr+++def test_detached_fixture_does_not_authorize_a_port(tmp_path):+ result = _run_probe(tmp_path, """+ import os+ import socket++ def test_detached_fixture():+ server = socket.socket()+ server.bind(('127.0.0.1', 0))+ address = server.getsockname()+ descriptor = server.detach()+ os.close(descriptor)+ try:+ socket.create_connection(address)+ except OSError:+ pass+ """)+ assert result.returncode == 1, result.stdout + result.stderr+ assert "1 passed, 1 error" in result.stdout+ assert "Unexpected network attempts" in result.stdout+++def test_closed_fixture_does_not_authorize_a_port(tmp_path):+ result = _run_probe(tmp_path, """+ import socket++ def test_fixture_closed():+ with socket.socket() as server:+ server.bind(('127.0.0.1', 0))+ address = server.getsockname()+ try:+ socket.create_connection(address)+ except OSError:+ pass+ """)+ assert result.returncode == 1, result.stdout + result.stderr+ assert "1 passed, 1 error" in result.stdout+ assert "Unexpected network attempts" in result.stdout+++def test_fixture_teardown_network_attempt_fails_test(tmp_path):+ host = f"teardown-{uuid.uuid4().hex}.invalid"+ result = _run_probe(tmp_path, f"""+ import socket+ import pytest++ @pytest.fixture+ def resource():+ yield+ try:+ socket.create_connection(({host!r}, 443))+ except OSError:+ pass++ def test_teardown(resource):+ pass+ """)+ assert result.returncode == 1, result.stdout + result.stderr+ assert "1 passed, 1 error" in result.stdout+ assert "Unexpected network attempts" in result.stdout+ assert host in result.stdout++[email protected]("allowed", [False, True])+def test_worker_boundary_guards_destination_and_preserves_allowed_call(tmp_path, allowed):+ host = f"worker-boundary-{uuid.uuid4().hex}.invalid"+ result = _run_probe(tmp_path, f"""+ import socket+ import sys+ import types+ from urllib.request import Request++ package = types.ModuleType('lib')+ package.__path__ = []+ worker = types.ModuleType('lib.bounded_get')+ calls = []+ def get(req, **kwargs):+ calls.append((req.full_url, kwargs))+ return b'owned payload'+ worker.get = get+ sys.modules['lib'] = package+ sys.modules['lib.bounded_get'] = worker++ def test_worker_destination():+ if {allowed!r}:+ with socket.socket() as server:+ server.bind(('127.0.0.1', 0))+ url = f'http://127.0.0.1:{{server.getsockname()[1]}}/fixture'+ assert worker.get(Request(url), timeout=1, deadline_monotonic=123) == b'owned payload'+ assert calls == [(url, {{'timeout': 1, 'deadline_monotonic': 123}})]+ else:+ try:+ worker.get(Request('https://{host}/fixture'), timeout=1, deadline_monotonic=123)+ except OSError:+ pass+ assert calls == []+ """)+ assert result.returncode == (0 if allowed else 1), result.stdout + result.stderr+ if allowed:+ assert "1 passed" in result.stdout+ else:+ assert "1 passed, 1 error" in result.stdout+ assert "Unexpected network attempts" in result.stdout+ assert host in result.stdout+++def test_worker_hostname_url_does_not_delegate_to_libc(tmp_path):+ result = _run_probe(tmp_path, """+ import socket+ import sys+ import types+ from urllib.request import Request++ package = types.ModuleType('lib')+ package.__path__ = []+ worker = types.ModuleType('lib.bounded_get')+ launches = []+ worker.get = lambda req, **kwargs: launches.append(req.full_url)+ sys.modules['lib'] = package+ sys.modules['lib.bounded_get'] = worker++ system_resolver = socket.getaddrinfo+ lookups = []+ def resolver(host, port, family=0, type=0, proto=0, flags=0):+ lookups.append(host)+ numeric_host = '127.0.0.1' if host == 'localhost' else host+ return system_resolver(numeric_host, port, family, type, proto,+ flags | socket.AI_NUMERICHOST | socket.AI_NUMERICSERV)+ socket.getaddrinfo = resolver++ def test_no_worker_hostname_resolution():+ with socket.socket() as server:+ server.bind(('127.0.0.1', 0))+ url = f'http://localhost:{server.getsockname()[1]}/fixture'+ try:+ worker.get(Request(url), timeout=1, deadline_monotonic=123)+ except OSError:+ pass+ assert 'localhost' not in lookups, 'worker hostname reached the system resolver'+ assert launches == []+ """)+ assert result.returncode == 1, result.stdout + result.stderr+ assert "1 passed, 1 error" in result.stdout+ assert "Unexpected network attempts" in result.stdout+ assert "bounded_get" in result.stdoutdiff --git a/tests/test_polymarket.py b/tests/test_polymarket.pyindex 82421980..ba823d5e 100644--- a/tests/test_polymarket.py+++ b/tests/test_polymarket.py@@ -439,18 +439,18 @@ def test_search_polymarket_query_expansion():# Should expand to multiple queriesassert len(queries) >= 2-@patch('lib.polymarket.http.post')---def test_search_polymarket_http_error_handling(mock_post):+@patch('lib.polymarket.http.request')+def test_search_polymarket_http_error_handling(mock_request):"""Test graceful handling of HTTP errors."""from lib.http import HTTPError- mock_post.side_effect = HTTPError("HTTP 429: Rate limit")+ mock_request.side_effect = HTTPError("HTTP 429: Rate limit", status_code=429)result = polymarket.search_polymarket("test", "2026-01-01", "2026-01-31")- # Should return structure with error- assert "events" in result or "error" in result+ assert mock_request.call_count > 0+ assert all(call.args[0] == "GET" for call in mock_request.call_args_list)+ assert result["events"] == []+ assert "HTTP 429: Rate limit" in result["error"]# === Tests for parse_polymarket_response() ===diff --git a/tests/test_x_envelope.py b/tests/test_x_envelope.pyindex fbf74ea5..1b7bd128 100644--- a/tests/test_x_envelope.py+++ b/tests/test_x_envelope.py@@ -857,9 +857,11 @@ class TestPipelineWiring:def test_exclude_sources_x_ignores_the_envelope_with_a_receipt(self, tmp_path):envelope = _read(_basic(tmp_path))- report, stderr = _capture(lambda: _run(- envelope, config={"EXCLUDE_SOURCES": "x"}, requested=None, plan=_plan(("reddit",)),- ))+ with mock.patch("lib.reddit_public.search_reddit_public", return_value=[]) as search:+ report, stderr = _capture(lambda: _run(+ envelope, config={"EXCLUDE_SOURCES": "x"}, requested=None, plan=_plan(("reddit",)),+ ))+ search.assert_called()assert "x" not in report.items_by_sourceassert "envelope ignored" in stderrassert envelope.topic_items, "an ignored envelope is not consumed"diff --git a/tests/test_youtube_yt.py b/tests/test_youtube_yt.pyindex 0a940e87..dd5711d9 100644--- a/tests/test_youtube_yt.py+++ b/tests/test_youtube_yt.py@@ -12,6 +12,13 @@ from unittest import mockfrom lib import youtube_yt+def _write_transcript_fixture(directory):+ (Path(directory) / "abc123.en.vtt").write_text(+ "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nOffline transcript fixture.\n",+ encoding="utf-8",+ )++class _DummyProc:def __init__(self):self.pid = 12345@@ -82,8 +89,10 @@ class TestYtDlpFlags(unittest.TestCase):with tempfile.TemporaryDirectory() as temp_dir, \mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=self._fake_result()) as run_mock:- youtube_yt.fetch_transcript("abc123", temp_dir)+ _write_transcript_fixture(temp_dir)+ transcript = youtube_yt.fetch_transcript("abc123", temp_dir)+ self.assertEqual(transcript, "Offline transcript fixture.")cmd = run_mock.call_args.args[0]self.assertIn("--ignore-config", cmd)self.assertIn("--no-cookies-from-browser", cmd)@@ -125,8 +134,10 @@ class TestYtDlpSubLangs(unittest.TestCase):mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=self._fake_result()) as run_mock:os.environ.pop("LAST30DAYS_YT_SUB_LANGS", None)- youtube_yt.fetch_transcript("abc123", temp_dir)+ _write_transcript_fixture(temp_dir)+ transcript = youtube_yt.fetch_transcript("abc123", temp_dir)+ self.assertEqual(transcript, "Offline transcript fixture.")cmd = run_mock.call_args_list[0].args[0]idx = cmd.index("--sub-lang")self.assertEqual(cmd[idx + 1], "en,es,pt")@@ -136,8 +147,10 @@ class TestYtDlpSubLangs(unittest.TestCase):mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "fr,de,it"}), \mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=self._fake_result()) as run_mock:- youtube_yt.fetch_transcript("abc123", temp_dir)+ _write_transcript_fixture(temp_dir)+ transcript = youtube_yt.fetch_transcript("abc123", temp_dir)+ self.assertEqual(transcript, "Offline transcript fixture.")cmd = run_mock.call_args_list[0].args[0]idx = cmd.index("--sub-lang")self.assertEqual(cmd[idx + 1], "fr,de,it")