zapret-kvn/tests/test_naive_live.py
loop-uh a099b40b11
Some checks failed
Windows project source guards / test (push) Failing after 3m14s
Naive family live tests skip as unproven when the test key is not accepted (expired canary key failed the gate control run)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-29 11:45:13 -05:00

193 lines
9.4 KiB
Python

"""Live: a real NaiveProxy key brings a real page through the real planner, the real sing-box front and the stock naive.exe.
Owner decision 2026-11-25 (tests on real data) and 2026-11-27 (stock naive is the core). The key is the canary key of the
naive bot session (tests/real_naive_key.py); the run needs Windows, ``core/naive.exe`` and ``core/sing-box.exe`` of the
build. Proxy mode, so no route of the machine changes. Nothing here prints the key, the server name or an address.
"""
from __future__ import annotations
import os
import subprocess
import tempfile
import time
import unittest
import urllib.request
from pathlib import Path
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PyQt6.QtWidgets import QApplication
_existing = QApplication.instance()
app = _existing if isinstance(_existing, QApplication) else (_existing or QApplication([]))
from tests import real_naive_key
from xray_fluent.constants import NAIVE_PATH_DEFAULT, SINGBOX_PATH_DEFAULT
from xray_fluent.engines.naive.manager import NaiveManager
from xray_fluent.engines.singbox.runtime_planner import parse_singbox_document, plan_singbox_proxy_runtime
from xray_fluent.importer.link_parser import parse_single
ROOT = Path(__file__).resolve().parents[1]
TEMPLATE_PATH = ROOT / "data" / "templates" / "sing-box" / "default.json"
_RUNNABLE = os.name == "nt" and NAIVE_PATH_DEFAULT.is_file() and SINGBOX_PATH_DEFAULT.is_file() and real_naive_key.available()
def _listening(port: int) -> bool:
import socket
try:
with socket.create_connection(("127.0.0.1", port), timeout=0.3):
return True
except OSError:
return False
@unittest.skipUnless(_RUNNABLE, "needs Windows, core/naive.exe, core/sing-box.exe and the real NaiveProxy test key")
class NaiveLiveTests(unittest.TestCase):
def test_a_real_key_brings_a_real_page_through_the_front_and_the_stock_client(self) -> None:
node = parse_single(real_naive_key.key_line())
document = parse_singbox_document(TEMPLATE_PATH, TEMPLATE_PATH.read_text(encoding="utf-8"))
plan = plan_singbox_proxy_runtime(document, node)
self.assertEqual("naive_sidecar", plan.outcome)
sidecar = plan.naive_sidecar
manager = NaiveManager()
logs: list[str] = []
manager.log_received.connect(logs.append)
started = manager.start(
sidecar.config, sidecar.relay_port, relay_username=sidecar.relay_username,
relay_password=sidecar.relay_password, context=sidecar.context, secrets=sidecar.secrets,
server_host=sidecar.server_host,
)
self.assertTrue(started, "the stock client did not bring the key's tunnel up: " + " | ".join(logs[-5:]))
self.assertTrue(manager.is_running)
front = None
directory = tempfile.mkdtemp(prefix="zkvn-naive-live-")
try:
config_path = Path(directory) / "singbox.json"
import json
config_path.write_text(json.dumps(plan.singbox_config), encoding="utf-8")
check = subprocess.run(
[str(SINGBOX_PATH_DEFAULT), "check", "-c", str(config_path)],
cwd=str(SINGBOX_PATH_DEFAULT.parent), capture_output=True, text=True, timeout=60,
)
self.assertEqual(0, check.returncode, "sing-box rejected the plan: " + check.stderr[-400:])
front = subprocess.Popen(
[str(SINGBOX_PATH_DEFAULT), "run", "-c", str(config_path)],
cwd=str(SINGBOX_PATH_DEFAULT.parent), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
deadline = time.monotonic() + 30
while time.monotonic() < deadline and not _listening(plan.http_port):
time.sleep(0.3)
self.assertTrue(_listening(plan.http_port), "the front did not open its HTTP proxy port")
opener = urllib.request.build_opener(
urllib.request.ProxyHandler({
"http": f"http://127.0.0.1:{plan.http_port}", "https": f"http://127.0.0.1:{plan.http_port}",
})
)
statuses = []
for url in ("http://cp.cloudflare.com/generate_204", "https://www.google.com/generate_204"):
with opener.open(url, timeout=40) as reply:
statuses.append(reply.status)
self.assertEqual([204, 204], statuses)
# The helper stays alive for the session and is the one process that holds the tunnel.
self.assertTrue(manager.is_running)
finally:
if front is not None:
front.kill()
front.wait(10)
manager.stop()
self.assertFalse(manager.process_alive)
import shutil
shutil.rmtree(directory, ignore_errors=True)
self.assertFalse(any("naive" in line.lower() and "secret" in line.lower() for line in logs))
key_secret = real_naive_key.key_line().split("@")[0].rsplit(":", 1)[-1]
self.assertFalse(any(key_secret in line for line in logs), "the secret reached a log line")
# The family tests need the stock client and the real key, on Windows (naive.exe) or elsewhere via KVN_NAIVE_BINARY
# (the Linux build of the same client). Only the trusted resolver's answer is controlled, so that the name has an IPv6
# address that is never reachable (a documentation prefix with no route) next to the server's real IPv4 address.
_NAIVE_BINARY = Path(os.environ["KVN_NAIVE_BINARY"]) if os.environ.get("KVN_NAIVE_BINARY") else NAIVE_PATH_DEFAULT
@unittest.skipUnless(_NAIVE_BINARY.is_file() and real_naive_key.available(), "needs the stock naive client and the real key")
class NaiveFamilyLiveTests(unittest.TestCase):
def _run(self, *, ipv6_first: bool, rounds: int = 2):
import socket
from unittest import mock
from urllib.parse import urlparse
from xray_fluent.engines.naive import manager as naive_manager
from xray_fluent.network import server_family
from xray_fluent.network.bootstrap_dns import BootstrapResolution
node = parse_single(real_naive_key.key_line())
document = parse_singbox_document(TEMPLATE_PATH, TEMPLATE_PATH.read_text(encoding="utf-8"))
side = plan_singbox_proxy_runtime(document, node).naive_sidecar
proxy = urlparse(side.config["proxy"])
v4 = socket.getaddrinfo(proxy.hostname, proxy.port or 443, socket.AF_INET)[0][4][0]
resolution = BootstrapResolution(addresses=frozenset({"2001:db8:dead::1", v4}), source="doh")
server_family.MEMORY.reset()
manager = NaiveManager()
manager.server_ipv6_first = ipv6_first
logs: list[str] = []
manager.log_received.connect(logs.append)
timings = []
try:
with mock.patch.object(naive_manager, "NAIVE_PATH_DEFAULT", _NAIVE_BINARY), \
mock.patch.object(naive_manager, "resolve_bootstrap", lambda name: resolution), \
mock.patch.object(naive_manager, "capture_runtime_config", lambda exe, config: None):
for _ in range(rounds):
began = time.monotonic()
ok = manager.start(side.config, side.relay_port, relay_username=side.relay_username,
relay_password=side.relay_password, context=side.context, secrets=side.secrets,
server_host=side.server_host)
timings.append((ok, time.monotonic() - began, [line for line in logs if "stage=" in line]))
logs.clear()
manager.stop()
finally:
manager.stop()
return timings, server_family.MEMORY.prefer_ipv6(side.server_host, True)
_key_works: bool | None = None
def _require_a_working_key(self) -> None:
"""The family tests mean something only with a key its node accepts: the canary keys expire by themselves, and a dead
key would fail the control run for a reason that has nothing to do with the address families. Unproven, not failed."""
cls = type(self)
if cls._key_works is None:
try:
(ok, _took, _lines), = self._run(ipv6_first=False, rounds=1)[0]
except OSError:
ok = False
cls._key_works = bool(ok)
if not cls._key_works:
self.skipTest("the NaiveProxy test key is not accepted by its node (expired?): the family behaviour is unproven here")
def test_a_dead_ipv6_costs_one_window_then_ipv4_is_remembered(self) -> None:
self._require_a_working_key()
timings, prefers_ipv6 = self._run(ipv6_first=True)
(ok1, took1, lines1), (ok2, took2, lines2) = timings
self.assertTrue(ok1, "the tunnel did not come up over IPv4 after IPv6 stayed silent")
self.assertTrue(any("retrying over IPv4" in line for line in lines1))
self.assertTrue(ok2)
self.assertFalse(any("retrying over IPv4" in line for line in lines2), "memory must start the second try on IPv4")
self.assertLess(took2, took1 - 3.0)
self.assertFalse(prefers_ipv6)
def test_without_ipv6_first_the_ipv4_address_is_pinned_and_nothing_is_retried(self) -> None:
self._require_a_working_key()
timings, _ = self._run(ipv6_first=False)
for ok, _took, lines in timings:
self.assertTrue(ok)
self.assertTrue(any("IPv4" in line for line in lines))
self.assertFalse(any("address_family" in line for line in lines))
if __name__ == "__main__":
unittest.main()