WireGuard overlay persists remote NAT1TO1 at install, opens WebRTC via ShellCrash trusted CIDRs, and reconfigures Neko after wg-quick restarts. Neko proxy probes Google before proxycheap. Console defaults to multi-channel Pro; docs updated. Co-authored-by: Cursor <cursoragent@cursor.com>
384 lines
19 KiB
Python
384 lines
19 KiB
Python
import tempfile
|
|
import unittest
|
|
from pathlib import Path
|
|
from unittest.mock import patch
|
|
|
|
from src.wireguard_config import (
|
|
WireGuardConfigError,
|
|
configure_neko_wireguard_access,
|
|
normalize_wireguard_keepalive_config,
|
|
normalize_wireguard_overlay_config,
|
|
parse_wireguard_config,
|
|
save_imported_wireguard_config,
|
|
wireguard_runtime_status,
|
|
)
|
|
|
|
|
|
SAMPLE_WG = """\
|
|
[Interface]
|
|
Address = 10.88.0.6/32
|
|
PrivateKey = AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
|
|
DNS = 1.1.1.1
|
|
MTU = 1360
|
|
|
|
[Peer]
|
|
PublicKey = BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=
|
|
PresharedKey = CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC=
|
|
Endpoint = 129.204.21.129:51820
|
|
AllowedIPs = 10.88.0.0/24
|
|
PersistentKeepalive = 25
|
|
"""
|
|
|
|
|
|
class WireGuardConfigTests(unittest.TestCase):
|
|
def test_parse_redacts_keys_and_extracts_endpoint(self) -> None:
|
|
parsed = parse_wireguard_config(SAMPLE_WG, name="Tencent Relay.conf")
|
|
|
|
self.assertEqual(parsed["name"], "Tencent-Relay")
|
|
self.assertEqual(parsed["interface"]["addresses"], ["10.88.0.6/32"])
|
|
self.assertEqual(parsed["interface"]["mtu"], 1360)
|
|
self.assertEqual(parsed["peers"][0]["endpoint_host"], "129.204.21.129")
|
|
self.assertEqual(parsed["peers"][0]["endpoint_port"], 51820)
|
|
self.assertEqual(parsed["peers"][0]["allowed_ips"], ["10.88.0.0/24"])
|
|
self.assertIn("PrivateKey = <redacted:", parsed["redacted_config"])
|
|
self.assertIn("PublicKey = <redacted:", parsed["redacted_config"])
|
|
self.assertNotIn("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", parsed["redacted_config"])
|
|
|
|
def test_save_imported_config_writes_managed_file_and_route_template(self) -> None:
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
result = save_imported_wireguard_config(SAMPLE_WG, name="wg-vps", repo_root=Path(tmp))
|
|
|
|
saved = Path(result["path"])
|
|
self.assertEqual(saved.relative_to(tmp).as_posix(), "config/wireguard/imports/wg-vps.conf")
|
|
self.assertTrue(saved.is_file())
|
|
self.assertIn("route -p add 129.204.21.129", result["windows_route_template"]["powershell"])
|
|
self.assertTrue(Path(result["summary_path"]).is_file())
|
|
|
|
def test_preserve_mode_adds_missing_keepalive(self) -> None:
|
|
no_keepalive = SAMPLE_WG.replace("PersistentKeepalive = 25\n", "")
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
result = save_imported_wireguard_config(no_keepalive, name="wg-vps", repo_root=Path(tmp))
|
|
|
|
saved = Path(result["path"]).read_text(encoding="utf-8")
|
|
self.assertIn("PersistentKeepalive = 25", saved)
|
|
self.assertEqual(result["health"]["missing_keepalive_peer_count"], 0)
|
|
self.assertTrue(result["overlay"]["keepalive"]["changed"])
|
|
|
|
def test_keepalive_normalizer_adds_only_endpoint_peers(self) -> None:
|
|
content = SAMPLE_WG.replace("PersistentKeepalive = 25\n", "") + "\n[Peer]\nPublicKey = DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD=\nAllowedIPs = 10.88.0.9/32\n"
|
|
|
|
normalized, meta = normalize_wireguard_keepalive_config(content)
|
|
|
|
self.assertEqual(normalized.count("PersistentKeepalive = 25"), 1)
|
|
self.assertTrue(meta["changed"])
|
|
|
|
def test_invalid_endpoint_is_rejected(self) -> None:
|
|
bad = SAMPLE_WG.replace("Endpoint = 129.204.21.129:51820", "Endpoint = 129.204.21.129:notaport")
|
|
with self.assertRaises(WireGuardConfigError):
|
|
parse_wireguard_config(bad)
|
|
|
|
def test_overlay_mode_removes_default_routes_and_adds_keepalive(self) -> None:
|
|
full_tunnel = SAMPLE_WG.replace("AllowedIPs = 10.88.0.0/24", "AllowedIPs = 0.0.0.0/0, ::/0").replace(
|
|
"PersistentKeepalive = 25\n",
|
|
"",
|
|
).replace(
|
|
"MTU = 1360\n",
|
|
"",
|
|
)
|
|
|
|
normalized, meta = normalize_wireguard_overlay_config(full_tunnel, name="wg-easy")
|
|
|
|
self.assertTrue(meta["changed"])
|
|
self.assertIn("AllowedIPs = 10.88.0.0/24", normalized)
|
|
self.assertNotIn("0.0.0.0/0", normalized)
|
|
self.assertIn("PersistentKeepalive = 25", normalized)
|
|
self.assertIn("MTU = 1360", normalized)
|
|
|
|
def test_save_overlay_mode_persists_normalized_config(self) -> None:
|
|
full_tunnel = SAMPLE_WG.replace("AllowedIPs = 10.88.0.0/24", "AllowedIPs = 0.0.0.0/0")
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
result = save_imported_wireguard_config(full_tunnel, name="wg-easy", repo_root=Path(tmp), route_mode="overlay")
|
|
|
|
saved = Path(result["path"]).read_text(encoding="utf-8")
|
|
self.assertEqual(result["route_mode"], "overlay")
|
|
self.assertIn("AllowedIPs = 10.88.0.0/24", saved)
|
|
self.assertTrue(result["overlay"]["changed"])
|
|
|
|
def test_runtime_status_falls_back_to_ip_when_wg_show_is_not_permitted(self) -> None:
|
|
def fake_run(args: list[str], **_: object) -> dict[str, object]:
|
|
if args[:4] == ["wg", "show", "all", "dump"]:
|
|
return {"ok": False, "stdout": "", "stderr": "Unable to access interface wgeasy: Operation not permitted"}
|
|
if args[:4] == ["ip", "-j", "address", "show"]:
|
|
return {
|
|
"ok": True,
|
|
"stdout": '[{"ifname":"wgeasy","addr_info":[{"local":"10.88.0.2","prefixlen":32}]}]',
|
|
"stderr": "",
|
|
}
|
|
if args[:5] == ["ip", "-d", "-j", "link", "show"]:
|
|
return {
|
|
"ok": True,
|
|
"stdout": '[{"ifname":"wgeasy","linkinfo":{"info_kind":"wireguard"}}]',
|
|
"stderr": "",
|
|
}
|
|
if args[:2] == ["systemctl", "is-active"]:
|
|
return {"ok": True, "stdout": "active", "stderr": ""}
|
|
if args[:2] == ["systemctl", "is-enabled"]:
|
|
return {"ok": True, "stdout": "enabled", "stderr": ""}
|
|
return {"ok": False, "stdout": "", "stderr": ""}
|
|
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
with patch("src.wireguard_config.shutil.which", return_value="/usr/bin/tool"), patch(
|
|
"src.wireguard_config._run_command",
|
|
side_effect=fake_run,
|
|
), patch(
|
|
"src.wireguard_config._system_wireguard_configs",
|
|
return_value=[],
|
|
):
|
|
status = wireguard_runtime_status(repo_root=Path(tmp))
|
|
|
|
self.assertTrue(status["active"])
|
|
self.assertEqual(status["quality"]["status"], "detected")
|
|
self.assertEqual(status["quality"]["score"], 45)
|
|
self.assertEqual(status["interfaces"][0]["name"], "wgeasy")
|
|
self.assertEqual(status["interfaces"][0]["addresses"], ["10.88.0.2/32"])
|
|
self.assertFalse(status["interfaces"][0]["details_available"])
|
|
self.assertEqual(status["interfaces"][0]["systemd"]["active"], "active")
|
|
|
|
def test_runtime_status_uses_readable_config_when_wg_details_are_blocked(self) -> None:
|
|
system_config = parse_wireguard_config(SAMPLE_WG.replace("Address = 10.88.0.6/32", "Address = 10.88.0.4/32"), name="wgeasy")
|
|
system_config.update({"path": "/etc/wireguard/wgeasy.conf", "source": "system", "readable": True})
|
|
|
|
def fake_run(args: list[str], **_: object) -> dict[str, object]:
|
|
if args[:4] == ["wg", "show", "all", "dump"]:
|
|
return {"ok": False, "stdout": "", "stderr": "Unable to access interface wgeasy: Operation not permitted"}
|
|
if args[:4] == ["ip", "-j", "address", "show"]:
|
|
return {
|
|
"ok": True,
|
|
"stdout": '[{"ifname":"wgeasy","addr_info":[{"local":"10.88.0.4","prefixlen":32}]}]',
|
|
"stderr": "",
|
|
}
|
|
if args[:5] == ["ip", "-d", "-j", "link", "show"]:
|
|
return {
|
|
"ok": True,
|
|
"stdout": '[{"ifname":"wgeasy","linkinfo":{"info_kind":"wireguard"}}]',
|
|
"stderr": "",
|
|
}
|
|
if args[:2] == ["systemctl", "is-active"]:
|
|
return {"ok": True, "stdout": "active", "stderr": ""}
|
|
if args[:2] == ["systemctl", "is-enabled"]:
|
|
return {"ok": True, "stdout": "enabled", "stderr": ""}
|
|
return {"ok": False, "stdout": "", "stderr": ""}
|
|
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
with patch("src.wireguard_config.shutil.which", return_value="/usr/bin/tool"), patch(
|
|
"src.wireguard_config._run_command",
|
|
side_effect=fake_run,
|
|
), patch("src.wireguard_config._system_wireguard_configs", return_value=[system_config]), patch(
|
|
"src.wireguard_config._endpoint_route_diagnostics",
|
|
return_value=[],
|
|
):
|
|
status = wireguard_runtime_status(repo_root=Path(tmp))
|
|
|
|
self.assertEqual(status["quality"]["status"], "detected")
|
|
self.assertEqual(status["quality"]["configured_peer_count"], 1)
|
|
self.assertEqual(status["interfaces"][0]["configured_from"]["name"], "wgeasy")
|
|
self.assertEqual(status["interfaces"][0]["configured_peers"][0]["endpoint"], "129.204.21.129:51820")
|
|
self.assertIn("VPS endpoint was loaded from config", " ".join(status["quality"]["reasons"]))
|
|
|
|
def test_runtime_status_reports_configured_when_config_exists_but_interface_is_down(self) -> None:
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
save_imported_wireguard_config(SAMPLE_WG, name="wg-vps", repo_root=Path(tmp))
|
|
with patch("src.wireguard_config.shutil.which", return_value=None), patch(
|
|
"src.wireguard_config._system_wireguard_configs",
|
|
return_value=[],
|
|
):
|
|
status = wireguard_runtime_status(repo_root=Path(tmp))
|
|
|
|
self.assertFalse(status["active"])
|
|
self.assertEqual(status["quality"]["status"], "configured")
|
|
self.assertEqual(status["quality"]["configured_peer_count"], 1)
|
|
self.assertIn("start wg-quick@wg-vps", " ".join(status["recommendations"]))
|
|
|
|
def test_runtime_status_reports_quality_and_configured_neko_remote_urls(self) -> None:
|
|
now = 1_700_000_000
|
|
|
|
def fake_run(args: list[str], **_: object) -> dict[str, object]:
|
|
if args[:4] == ["wg", "show", "all", "dump"]:
|
|
return {
|
|
"ok": True,
|
|
"stdout": "\n".join(
|
|
[
|
|
"wg0\tpriv\tpub\t51820\toff",
|
|
f"wg0\tpeer\tpsk\t129.204.21.129:51820\t10.88.0.0/24\t{now - 30}\t4096\t8192\t25",
|
|
]
|
|
),
|
|
"stderr": "",
|
|
}
|
|
if args[:4] == ["ip", "-j", "address", "show"]:
|
|
return {
|
|
"ok": True,
|
|
"stdout": '[{"ifname":"wg0","addr_info":[{"local":"10.88.0.2","prefixlen":24}]}]',
|
|
"stderr": "",
|
|
}
|
|
if args[:2] == ["systemctl", "is-active"]:
|
|
return {"ok": True, "stdout": "active", "stderr": ""}
|
|
if args[:2] == ["systemctl", "is-enabled"]:
|
|
return {"ok": True, "stdout": "enabled", "stderr": ""}
|
|
return {"ok": False, "stdout": "", "stderr": ""}
|
|
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
env = Path(tmp) / "config" / "system-stack.env"
|
|
env.parent.mkdir(parents=True)
|
|
env.write_text(
|
|
"NEKO_ACCESS_MODE=remote\nNEKO_WIREGUARD_HOST=10.88.0.2\nNEKO_INSTANCE_COUNT=2\nNEKO_HTTP_PORT=9200\n",
|
|
encoding="utf-8",
|
|
)
|
|
with patch("src.wireguard_config.shutil.which", return_value="/usr/bin/tool"), patch(
|
|
"src.wireguard_config._run_command",
|
|
side_effect=fake_run,
|
|
), patch("src.wireguard_config.time.time", return_value=now):
|
|
status = wireguard_runtime_status(repo_root=Path(tmp))
|
|
|
|
self.assertEqual(status["quality"]["status"], "connected")
|
|
self.assertEqual(status["quality"]["fresh_peer_count"], 1)
|
|
self.assertEqual(status["quality"]["best_handshake_age_seconds"], 30)
|
|
self.assertEqual(status["neko_access"]["mode"], "remote")
|
|
self.assertTrue(status["neko_access"]["remote_ready"])
|
|
self.assertEqual(status["neko_access"]["remote_urls"][0]["url"], "http://10.88.0.2:9200")
|
|
self.assertEqual(status["neko_access"]["remote_urls"][1]["url"], "http://10.88.0.2:9201")
|
|
|
|
def test_configure_neko_remote_requires_active_wireguard(self) -> None:
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
with patch("src.wireguard_config.wireguard_runtime_status", return_value={"active": False, "interfaces": []}):
|
|
with self.assertRaises(WireGuardConfigError):
|
|
configure_neko_wireguard_access(repo_root=Path(tmp), mode="remote", restart=False)
|
|
|
|
def test_neko_browser_proxy_defaults_off_and_can_be_enabled(self) -> None:
|
|
from src.wireguard_config import configure_neko_browser_proxy
|
|
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
repo = Path(tmp)
|
|
env = repo / "config" / "system-stack.env"
|
|
env.parent.mkdir(parents=True)
|
|
env.write_text(
|
|
"NEKO_SHELLCRASH_PROXY_PORT=7894\nSHELLCRASH_NEKO_PROXY_NODE=proxycheap\n",
|
|
encoding="utf-8",
|
|
)
|
|
direct_probe = {"global_direct_ok": True}
|
|
blocked_probe = {"global_direct_ok": False}
|
|
with patch("src.network_preflight.system_network_probe", return_value=direct_probe):
|
|
status = configure_neko_browser_proxy(repo_root=repo, enabled=False, restart=False)
|
|
self.assertFalse(status["enabled"])
|
|
self.assertEqual(status["resolved_proxy"], "")
|
|
|
|
with patch("src.network_preflight.system_network_probe", return_value=blocked_probe):
|
|
with patch("src.wireguard_config._reconfigure_neko_containers", return_value={"ok": True, "skipped": False}):
|
|
enabled = configure_neko_browser_proxy(repo_root=repo, enabled=True, restart=True)
|
|
self.assertTrue(enabled["enabled"])
|
|
self.assertEqual(enabled["resolved_proxy"], "http://host.docker.internal:7894")
|
|
self.assertIn("ENABLE_NEKO_BROWSER_PROXY=1", env.read_text(encoding="utf-8"))
|
|
self.assertIn("NEKO_BROWSER_PROXY_MANUAL=1", env.read_text(encoding="utf-8"))
|
|
self.assertIn("NEKO_BROWSER_PROXY=\n", env.read_text(encoding="utf-8"))
|
|
|
|
with patch("src.network_preflight.system_network_probe", return_value=blocked_probe):
|
|
shellcrash_off = configure_neko_browser_proxy(repo_root=repo, enabled=False, restart=False)
|
|
self.assertFalse(shellcrash_off["enabled"])
|
|
self.assertEqual(shellcrash_off["resolved_proxy"], "http://host.docker.internal:7890")
|
|
|
|
def test_neko_browser_proxy_auto_enables_when_shellcrash_only(self) -> None:
|
|
from src.wireguard_config import ensure_neko_browser_proxy_for_network
|
|
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
repo = Path(tmp)
|
|
env = repo / "config" / "system-stack.env"
|
|
env.parent.mkdir(parents=True)
|
|
env.write_text(
|
|
"ENABLE_NEKO_BROWSER_PROXY=0\nSHELLCRASH_ATTACH_NEKO=auto\nNEKO_SHELLCRASH_PROXY_PORT=7894\n",
|
|
encoding="utf-8",
|
|
)
|
|
probe = {
|
|
"global_direct_ok": False,
|
|
"global_proxy_ok": True,
|
|
"shellcrash": {"running": True, "mixed_port": "7890"},
|
|
"shellcrash_policy": {"attach_neko_mode": "auto"},
|
|
"mode": "shellcrash",
|
|
}
|
|
with patch("src.network_preflight.system_network_probe", return_value=probe):
|
|
with patch("src.network_preflight.shellcrash_listener_egress_ok", return_value=True):
|
|
with patch("src.wireguard_config._reconfigure_neko_containers", return_value={"ok": True, "skipped": False}):
|
|
result = ensure_neko_browser_proxy_for_network(repo_root=repo, restart=True)
|
|
self.assertTrue(result["applied"])
|
|
self.assertTrue(result["enabled"])
|
|
self.assertNotIn("NEKO_BROWSER_PROXY_MANUAL=1", env.read_text(encoding="utf-8"))
|
|
|
|
def test_neko_browser_proxy_auto_uses_mixed_when_proxycheap_dead(self) -> None:
|
|
from src.wireguard_config import ensure_neko_browser_proxy_for_network
|
|
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
repo = Path(tmp)
|
|
env = repo / "config" / "system-stack.env"
|
|
env.parent.mkdir(parents=True)
|
|
env.write_text(
|
|
"ENABLE_NEKO_BROWSER_PROXY=0\nSHELLCRASH_ATTACH_NEKO=auto\nNEKO_SHELLCRASH_PROXY_PORT=7894\n",
|
|
encoding="utf-8",
|
|
)
|
|
probe = {
|
|
"global_direct_ok": False,
|
|
"global_proxy_ok": True,
|
|
"shellcrash": {"running": True, "mixed_port": "7890"},
|
|
"shellcrash_policy": {"attach_neko_mode": "auto"},
|
|
"mode": "shellcrash",
|
|
}
|
|
with patch("src.network_preflight.system_network_probe", return_value=probe):
|
|
with patch("src.network_preflight.shellcrash_listener_egress_ok", return_value=False):
|
|
with patch("src.wireguard_config._reconfigure_neko_containers", return_value={"ok": True, "skipped": False}) as reconf:
|
|
result = ensure_neko_browser_proxy_for_network(repo_root=repo, restart=True)
|
|
self.assertTrue(result["applied"])
|
|
self.assertFalse(result["enabled"])
|
|
self.assertEqual(result["reason"], "direct_blocked_mixed_only")
|
|
reconf.assert_called_once()
|
|
|
|
def test_neko_browser_proxy_auto_skips_when_direct_ok(self) -> None:
|
|
from src.wireguard_config import ensure_neko_browser_proxy_for_network
|
|
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
repo = Path(tmp)
|
|
env = repo / "config" / "system-stack.env"
|
|
env.parent.mkdir(parents=True)
|
|
env.write_text("ENABLE_NEKO_BROWSER_PROXY=0\n", encoding="utf-8")
|
|
probe = {
|
|
"global_direct_ok": True,
|
|
"global_proxy_ok": True,
|
|
"shellcrash": {"running": True, "mixed_port": "7890"},
|
|
"shellcrash_policy": {"attach_neko_mode": "auto"},
|
|
"mode": "direct",
|
|
}
|
|
with patch("src.network_preflight.system_network_probe", return_value=probe):
|
|
result = ensure_neko_browser_proxy_for_network(repo_root=repo, restart=False)
|
|
self.assertFalse(result["applied"])
|
|
self.assertEqual(result["reason"], "not_needed")
|
|
|
|
def test_upsert_stack_env_dedupes_duplicate_keys(self) -> None:
|
|
from src.wireguard_config import _read_stack_env, _upsert_stack_env_values
|
|
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
repo = Path(tmp)
|
|
env = repo / "config" / "system-stack.env"
|
|
env.parent.mkdir(parents=True)
|
|
env.write_text(
|
|
"ENABLE_NEKO_BROWSER_PROXY=0\n"
|
|
"NEKO_BROWSER_PROXY_MANUAL=0\n"
|
|
"ENABLE_NEKO_BROWSER_PROXY=1\n",
|
|
encoding="utf-8",
|
|
)
|
|
changed = _upsert_stack_env_values(repo_root=repo, values={"ENABLE_NEKO_BROWSER_PROXY": "0"})
|
|
self.assertTrue(changed)
|
|
text = env.read_text(encoding="utf-8")
|
|
self.assertEqual(text.count("ENABLE_NEKO_BROWSER_PROXY="), 1)
|
|
self.assertIn("ENABLE_NEKO_BROWSER_PROXY=0", text)
|
|
self.assertFalse(_read_stack_env(repo)["ENABLE_NEKO_BROWSER_PROXY"] == "1")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|