fix topology of cards

This commit is contained in:
Udo
2026-12-02 12:43:23 +05:00
parent b3babe73bd
commit c3b33217e4
19 changed files with 1177 additions and 1845 deletions
+57 -17
View File
@@ -1,11 +1,17 @@
"""Фикстура, повторяющая профиль BridgeOverNetbird и ноды из панели."""
"""Фикстура сети: вход RU-01 (профиль Bridge) + 6 выходных нод (профиль Default)."""
SC = ["domain:soundcloud.com", "domain:sndcdn.com", "domain:soundcloud.cloud"]
BRIDGE_IPS = ["100.106.180.60", "100.106.64.26", "100.106.214.118",
"100.106.134.18", "100.106.36.222", "100.106.221.7"]
NODE_NAMES = ["FR-01", "NL-01", "FI-01", "NL-04", "CH-01", "BR-01"]
EXIT_NAMES = ["FR-01", "NL-01", "FI-01", "NL-04", "CH-01", "BR-01"]
BRIDGE_UUID = "aaaaaaaa-0000-0000-0000-000000000001"
DEFAULT_UUID = "bbbbbbbb-0000-0000-0000-000000000002"
INB_BRIDGE = "inb-bridge" # RU_NODE_IN
INB_VLESS = "inb-def-vless" # DEFAULT_IN, 443
INB_SS = "inb-def-ss" # BRIDGE_SS_IN, 9999
def make_profile() -> dict:
def bridge_profile() -> dict:
rules = [
{"port": 25, "outboundTag": "BLOCK"},
{"ip": ["geoip:private"], "outboundTag": "BLOCK"},
@@ -32,25 +38,59 @@ def make_profile() -> dict:
{"tag": "BRIDGE_AUTO", "selector": ["BRIDGE_"], "strategy": {"type": "leastPing"},
"fallbackTag": "BRIDGE_1"}]},
}
return {"uuid": "aaaaaaaa-0000-0000-0000-000000000001", "name": "BridgeOverNetbird",
"config": config, "inbounds": [{"uuid": "inb-1", "tag": "RU_NODE_IN"}],
"nodes": [{"uuid": "n-ru", "name": "RU-01", "countryCode": "RU"}]}
return {"uuid": BRIDGE_UUID, "name": "BridgeOverNetbird", "config": config,
"inbounds": [{"uuid": INB_BRIDGE, "tag": "RU_NODE_IN", "type": "vless", "port": 443}]}
def default_profile() -> dict:
config = {
"inbounds": [
{"tag": "DEFAULT_IN", "port": 443, "protocol": "vless"},
{"tag": "BRIDGE_SS_IN", "port": 9999, "protocol": "shadowsocks",
"settings": {"password": "SECRET-SS"}},
],
"outbounds": [{"tag": "DIRECT", "protocol": "freedom"}, {"tag": "BLOCK", "protocol": "blackhole"}],
"routing": {"rules": [
{"protocol": ["bittorrent"], "outboundTag": "BLOCK"},
{"ip": ["geoip:private"], "outboundTag": "BLOCK"},
]},
}
return {"uuid": DEFAULT_UUID, "name": "Default", "config": config, "inbounds": [
{"uuid": INB_VLESS, "tag": "DEFAULT_IN", "type": "vless", "port": 443},
{"uuid": INB_SS, "tag": "BRIDGE_SS_IN", "type": "shadowsocks", "port": 9999}]}
def make_profiles() -> list[dict]:
return [default_profile(), bridge_profile()]
def make_nodes() -> list[dict]:
nodes = [{"name": n, "address": ip, "countryCode": "XX", "isConnected": True, "isDisabled": False,
ru = {"uuid": "n-ru", "name": "RU-01", "address": "100.106.247.44", "countryCode": "RU",
"isConnected": True, "isDisabled": False,
"ips": [{"ip": "91.201.43.187", "status": "OUTBOUND"}, {"ip": "100.106.247.44", "status": "MANAGEMENT"}],
"configProfile": {"activeConfigProfileUuid": BRIDGE_UUID, "activeInbounds": [{"uuid": INB_BRIDGE}]},
"system": {"info": {"networkInterfaces": ["lo", "wt0"]}}}
exits = [{"uuid": f"n-{i}", "name": n, "address": ip, "countryCode": "XX",
"isConnected": True, "isDisabled": False,
"ips": [{"ip": ip, "status": "MANAGEMENT"}, {"ip": f"1.1.1.{i}", "status": "OUTBOUND"}],
"configProfile": {"activeConfigProfileUuid": DEFAULT_UUID,
"activeInbounds": [{"uuid": INB_VLESS}, {"uuid": INB_SS}]},
"system": {"info": {"networkInterfaces": ["lo", "wt0"]}}}
for i, (n, ip) in enumerate(zip(NODE_NAMES, BRIDGE_IPS))]
nodes.append({"name": "US-01", "address": "78.153.155.226", "ips": [], "system": None})
return nodes
for i, (n, ip) in enumerate(zip(EXIT_NAMES, BRIDGE_IPS))]
unused = {"uuid": "n-us", "name": "US-01", "address": "78.153.155.226", "ips": [],
"configProfile": {"activeConfigProfileUuid": None, "activeInbounds": []}, "system": None}
return [ru, *exits, unused]
def make_hosts() -> list[dict]:
inbound = {"configProfileInboundUuid": "inb-1"}
hosts = [{"uuid": f"h{r}", "remark": f"host-r{r}", "vlessRouteId": r, "inbound": inbound}
for r in (3, 7, 8)]
hosts.append({"uuid": "hn", "remark": "no-route", "vlessRouteId": None, "inbound": inbound})
hosts.append({"uuid": "hx", "remark": "other-profile", "vlessRouteId": 1,
"inbound": {"configProfileInboundUuid": "foreign"}})
return hosts
def host(uuid, remark, node, inbound, route=None):
return {"uuid": uuid, "remark": remark, "address": "node-ru.example", "port": 443,
"vlessRouteId": route, "nodes": [node],
"inbound": {"configProfileUuid": "x", "configProfileInboundUuid": inbound}}
return [
host("h3", "Bridge-Ivi", "n-ru", INB_BRIDGE, 3),
host("h7", "Bridge-Auto", "n-ru", INB_BRIDGE, 7),
host("h8", "Bridge-Mira-SC", "n-ru", INB_BRIDGE, 8),
host("hn", "Bridge-NoRoute", "n-ru", INB_BRIDGE, None),
host("hd", "Direct-FI", "n-2", INB_VLESS), # прямое подключение к выходной ноде
]
+8 -21
View File
@@ -5,9 +5,9 @@ import pytest
from app import create_app
from app.config import Settings
from app.remnawave import RemnawaveError
from .fixtures import make_hosts, make_nodes, make_profile
from .fixtures import make_hosts, make_nodes, make_profiles
KEY = "aaaaaaaa-0000-0000-0000-000000000001"
KEY = "network-v2"
class FakeClient:
@@ -19,9 +19,7 @@ class FakeClient:
self.calls += 1
if self.fail:
raise RemnawaveError("панель недоступна", "upstream_unreachable")
other = {"uuid": "bbbbbbbb-0000-0000-0000-000000000002", "name": "Default",
"config": {"inbounds": [], "outbounds": [], "routing": {"rules": []}}, "inbounds": []}
return {"profiles": [other, make_profile()], "hosts": make_hosts(), "nodes": make_nodes()}
return {"profiles": make_profiles(), "hosts": make_hosts(), "nodes": make_nodes()}
def make_settings(tmp_path, **kw):
@@ -37,29 +35,18 @@ def client_and_fake(tmp_path):
return app.test_client(), fake
def test_graph_default_profile_is_the_one_with_vless_route(client_and_fake):
def test_graph_endpoint_returns_whole_network(client_and_fake):
c, _ = client_and_fake
r = c.get("/api/graph")
assert r.status_code == 200
body = r.get_json()
assert body["profile"]["name"] == "BridgeOverNetbird"
assert body["graph"]["warnings"]
g = body["graph"]
assert {n["type"] for n in g["nodes"]} == {"host", "node", "balancer", "outbound"}
assert g["warnings"] and g["paths"]
assert body["positionsKey"] == KEY
assert "SECRET" not in r.get_data(as_text=True)
def test_profile_by_name_and_unknown(client_and_fake):
c, _ = client_and_fake
assert c.get("/api/graph?profile=default").get_json()["profile"]["name"] == "Default"
r = c.get("/api/graph?profile=nope")
assert r.status_code == 404 and r.get_json()["error"] == "profile_not_found"
def test_profiles_list(client_and_fake):
c, _ = client_and_fake
names = [p["name"] for p in c.get("/api/profiles").get_json()["profiles"]]
assert names == ["Default", "BridgeOverNetbird"]
def test_cache_and_refresh_throttle(client_and_fake):
c, fake = client_and_fake
c.get("/api/graph"); c.get("/api/graph"); c.get("/api/profiles")
+209 -52
View File
@@ -2,96 +2,253 @@ import copy
import pytest
from app.graph import build_graph, parse_vless_route
from .fixtures import make_hosts, make_nodes, make_profile
from app.graph import build_graph, parse_vless_route, ranges
from .fixtures import (EXIT_NAMES, INB_BRIDGE, INB_SS, INB_VLESS, make_hosts, make_nodes, make_profiles)
def build(profiles=None, hosts=None, nodes=None):
return build_graph(profiles or make_profiles(), hosts or make_hosts(), nodes or make_nodes())
def by_id(g):
return {n["id"]: n for n in g["nodes"]}
def targets(g, src):
return [e["target"] for e in g["edges"] if e["source"] == src]
def edges_from(g, src):
return [e for e in g["edges"] if e["source"] == src]
def card_by_name(g, name):
return next(n for n in g["nodes"] if n["type"] == "node" and n["label"] == name)
def out_card(g, tag):
return next(n for n in g["nodes"] if n["type"] == "outbound" and tag in n["label"].split(" · "))
@pytest.fixture
def g():
return build_graph(make_profile(), make_hosts(), make_nodes())
return build()
def test_parse_vless_route():
def test_parse_vless_route_and_ranges():
assert parse_vless_route(None) is None
assert parse_vless_route(5) == {5}
assert parse_vless_route("8-14") == set(range(8, 15))
assert parse_vless_route("1,3,8-10") == {1, 3, 8, 9, 10}
assert ranges([14, 15, 16, 20]) == "#14–#16, #20"
def test_all_bridges_resolve(g):
assert not [n for n in g["nodes"] if n["type"] == "unresolved"]
expected = {"BRIDGE_1": "FR-01", "BRIDGE_2": "NL-01", "BRIDGE_3": "FI-01",
"BRIDGE_4": "NL-04", "BRIDGE_5": "CH-01", "BRIDGE_6": "BR-01"}
for out, node in expected.items():
assert targets(g, f"out:{out}") == [f"node:{node}"]
assert "node:US-01" not in by_id(g)
def test_each_host_has_exactly_one_thread_to_its_node(g):
for h in (n for n in g["nodes"] if n["type"] == "host"):
assert len(edges_from(g, h["id"])) == 1
assert {n["id"] for n in g["nodes"] if n["type"] == "host"} == {"host:h3", "host:h7", "host:h8", "host:hn", "host:hd"}
def test_shadowed_rules(g):
shadowed = [n["data"]["index"] for n in g["nodes"] if n["type"] == "rule" and n["data"]["shadowed"]]
assert shadowed == list(range(14, 22))
assert sum("недостижимо" in w for w in g["warnings"]) == 8
def test_bridge_host_lands_on_its_rule_row(g):
land = {e["source"]: e["targetHandle"] for e in g["edges"] if e["kind"] == "host"}
assert land["host:h3"] == f"rin:{INB_BRIDGE}:8" # vlessRoute 3 -> BRIDGE_3
assert land["host:h7"] == f"rin:{INB_BRIDGE}:12" # vlessRoute 7 -> балансер
assert land["host:h8"] == f"rin:{INB_BRIDGE}:13" # route 8 упирается в catch-all
assert land["host:hn"] == f"rin:{INB_BRIDGE}:13"
e3 = next(e for e in g["edges"] if e["source"] == "host:h3")
assert e3["target"] == "node:n-ru" and e3["label"] == "route 3"
def test_host_trace(g):
b = by_id(g)
assert b["host:h3"]["data"]["trace"][-1] == "rule:8" # route 3 -> BRIDGE_3
assert b["host:h7"]["data"]["trace"][-1] == "rule:12" # route 7 -> BRIDGE_AUTO
assert b["host:h8"]["data"]["trace"][-1] == "rule:13" # route 8 упирается в catch-all
assert b["host:hn"]["data"]["trace"][-1] == "rule:13"
assert "host:hx" not in b # хост другого профиля
def test_direct_host_lands_on_default_row_of_exit_node(g):
e = next(e for e in g["edges"] if e["source"] == "host:hd")
assert e["target"] == "node:n-2"
assert e["targetHandle"] == f"rin:{INB_VLESS}:default" # правила условные -> дальше "по умолчанию"
def test_node_card_sections_and_rows(g):
ru = card_by_name(g, "RU-01")["data"]
assert ru["profile"]["name"] == "BridgeOverNetbird"
(sec,) = ru["sections"]
assert (sec["tag"], sec["port"], sec["protocol"]) == ("RU_NODE_IN", 443, "vless")
assert len(sec["rows"]) == 22
assert [r["index"] for r in sec["rows"] if r["shadowed"]] == list(range(14, 22))
assert all(not r["hasEdge"] for r in sec["rows"] if r["shadowed"])
fi = card_by_name(g, "FI-01")["data"]
assert [s["tag"] for s in fi["sections"]] == ["DEFAULT_IN", "BRIDGE_SS_IN"]
assert all(s["rows"][-1]["default"] for s in fi["sections"])
assert all(r["common"] for s in fi["sections"] for r in s["rows"])
def test_shadowed_warning_is_aggregated(g):
w = [w["text"] for w in g["warnings"] if "недостижимы" in w["text"]]
assert w == ["RU-01 / RU_NODE_IN: недостижимы правила #14–#21 (выше catch-all #13)"]
def test_bridge_outbound_leads_to_exit_nodes_inbound_row(g):
o = out_card(g, "BRIDGE_3")
assert o["data"]["destName"] == "FI-01"
(link,) = edges_from(g, o["id"])
assert (link["target"], link["targetHandle"]) == ("node:n-2", f"inb:{INB_SS}")
assert link["label"] == "100.106.214.118:9999"
def test_outbound_shared_by_several_nodes_is_one_card():
nodes = make_nodes()
ru2 = copy.deepcopy(nodes[0])
ru2.update(uuid="n-ru2", name="RU-02", address="100.106.247.45")
ru2["ips"] = [{"ip": "100.106.247.45", "status": "MANAGEMENT"}]
g = build(nodes=[*nodes, ru2], hosts=make_hosts() + [
{"uuid": "h-ru2", "remark": "Bridge-RU2", "vlessRouteId": 3, "nodes": ["n-ru2"],
"inbound": {"configProfileInboundUuid": INB_BRIDGE}}])
cards = [n for n in g["nodes"] if n["type"] == "outbound" and "BRIDGE_3" in n["label"]]
assert len(cards) == 1
assert cards[0]["data"]["users"] == ["RU-01", "RU-02"]
# а вот DIRECT у каждой ноды свой: у него разные публичные IP
directs = [n for n in g["nodes"] if n["type"] == "outbound" and n["data"]["protocol"] == "freedom"]
assert len({n["data"]["owner"] for n in directs}) == len(directs) >= 2
def test_blackhole_is_shared_but_direct_is_per_node(g):
blocks = [n for n in g["nodes"] if n["type"] == "outbound" and n["data"]["protocol"] == "blackhole"]
assert len(blocks) == 1 and blocks[0]["data"]["users"] == sorted(["RU-01", *EXIT_NAMES])
directs = [n for n in g["nodes"] if n["type"] == "outbound" and n["data"]["protocol"] == "freedom"]
assert sorted(n["data"]["owner"] for n in directs) == sorted(["RU-01", *EXIT_NAMES])
assert all(n["data"]["exit"] for n in directs) # у каждой ноды свой публичный IP
def test_balancer_card_and_members(g):
(bal,) = [n for n in g["nodes"] if n["type"] == "balancer"]
assert bal["label"] == "BRIDGE_AUTO" and len(bal["data"]["members"]) == 6
assert bal["data"]["aliveMembers"] == bal["data"]["members"]
es = edges_from(g, bal["id"])
assert {e["kind"] for e in es} == {"member"}
assert [e["label"] for e in es if e["label"]] == ["fallback"] # BRIDGE_1 входит в селектор
assert next(e for e in es if e["label"])["target"] == out_card(g, "BRIDGE_1")["id"]
def test_fallback_outside_selector_gets_its_own_edge():
profiles = make_profiles()
profiles[1]["config"]["routing"]["balancers"][0]["fallbackTag"] = "DIRECT"
g = build(profiles=profiles)
(bal,) = [n for n in g["nodes"] if n["type"] == "balancer"]
fb = [e for e in edges_from(g, bal["id"]) if e["kind"] == "fallback"]
assert len(fb) == 1 and fb[0]["target"] == out_card(g, "DIRECT")["id"]
def test_path_of_bridge_host_crosses_both_nodes(g):
p = g["paths"]["host:h3"]
o = out_card(g, "BRIDGE_3")["id"]
assert {"node:n-ru", o, "node:n-2"} <= set(p["nodes"])
assert "node:n-3" not in p["nodes"] # NL-04 не задействован
ru = p["rows"]["node:n-ru"]
assert f"{INB_BRIDGE}:8" in ru["active"] and f"{INB_BRIDGE}:0" in ru["active"]
assert set(ru["pass"]) == {f"{INB_BRIDGE}:6", f"{INB_BRIDGE}:7"}
fi = p["rows"]["node:n-2"]
assert f"inb:{INB_SS}" in fi["active"] and f"{INB_SS}:default" in fi["active"]
link = edges_from(g, o)[0]["id"]
assert link in p["edges"]
def test_path_through_balancer_reaches_every_member(g):
p = g["paths"]["host:h7"]
assert all(n in p["nodes"] for n in ("node:n-0", "node:n-1", "node:n-2", "node:n-3", "node:n-4", "node:n-5"))
assert [n for n in p["nodes"] if n.startswith("bal:")]
def test_direct_host_path_stays_on_one_node(g):
p = g["paths"]["host:hd"]
assert "node:n-ru" not in p["nodes"]
assert f"{INB_VLESS}:default" in p["rows"]["node:n-2"]["active"]
def test_unused_nodes_are_not_drawn(g):
assert "node:n-us" not in by_id(g)
def test_no_secrets_in_output(g):
dump = str(g)
assert "SECRET" not in dump
assert "SECRET" not in str(g)
def test_disabled_and_offline_nodes():
def test_disabled_and_offline_exit_nodes():
nodes = make_nodes()
for n in nodes:
if n["name"] == "NL-04":
n["isDisabled"] = True
if n["name"] == "BR-01":
n["isConnected"] = False
nodes.insert(0, {"name": "OLD-FR", "address": "100.106.180.60", "isDisabled": True,
"ips": [{"ip": "100.106.180.60", "status": "MANAGEMENT"}], "system": None})
g = build_graph(make_profile(), make_hosts(), nodes)
b = by_id(g)
assert targets(g, "out:BRIDGE_1") == ["node:FR-01"] # живая нода выигрывает у дубля
assert b["node:NL-04"]["data"]["state"] == "disabled"
assert b["node:BR-01"]["data"]["state"] == "offline"
assert b["bal:BRIDGE_AUTO"]["data"]["aliveMembers"] == ["BRIDGE_1", "BRIDGE_2", "BRIDGE_3", "BRIDGE_5"]
dead = {e["source"] for e in g["edges"] if e["kind"] == "link" and e["data"].get("dead")}
assert dead == {"out:BRIDGE_4", "out:BRIDGE_6"}
g = build(nodes=nodes)
assert card_by_name(g, "NL-04")["data"]["state"] == "disabled"
assert card_by_name(g, "BR-01")["data"]["state"] == "offline"
dead = {e["source"] for e in g["edges"] if e["kind"] == "link" and e["data"]["dead"]}
assert dead == {out_card(g, "BRIDGE_4")["id"], out_card(g, "BRIDGE_6")["id"]}
(bal,) = [n for n in g["nodes"] if n["type"] == "balancer"]
assert len(bal["data"]["aliveMembers"]) == 4
assert any("нода disabled" in w["text"] for w in g["warnings"])
def test_all_nodes_down_warns():
def test_all_exits_down_warns_and_marks_hosts():
nodes = make_nodes()
for n in nodes:
for n in nodes[1:]:
n["isDisabled"] = True
g = build_graph(make_profile(), make_hosts(), nodes)
assert any("нет ни одного живого члена" in w for w in g["warnings"])
assert by_id(g)["host:h3"]["data"]["exitAlive"] is False
g = build(nodes=nodes)
assert any("без живых членов" in w["text"] for w in g["warnings"])
assert by_id(g)["host:h7"]["data"]["exitAlive"] is False
def test_unresolved_outbound():
def test_duplicate_disabled_node_with_same_address_does_not_win():
nodes = make_nodes()
nodes.insert(0, {"uuid": "n-old", "name": "OLD-FR", "address": BRIDGE_FIRST, "isDisabled": True,
"ips": [{"ip": BRIDGE_FIRST, "status": "MANAGEMENT"}], "system": None,
"configProfile": {"activeConfigProfileUuid": None, "activeInbounds": []}})
g = build(nodes=nodes)
assert out_card(g, "BRIDGE_1")["data"]["destName"] == "FR-01"
BRIDGE_FIRST = "100.106.180.60"
def test_unresolved_internal_address_is_flagged():
nodes = [n for n in make_nodes() if n["name"] != "NL-04"]
g = build_graph(make_profile(), make_hosts(), nodes)
assert "unresolved:100.106.134.18" in by_id(g)
assert any("не найден" in w for w in g["warnings"])
g = build(nodes=nodes)
o = out_card(g, "BRIDGE_4")
assert o["data"]["alive"] is False and o["data"]["destName"] is None
assert any("не найден" in w["text"] for w in g["warnings"])
def test_host_not_bound_to_single_node_warns():
hosts = make_hosts()
hosts[0]["nodes"] = [] # пусто -> все ноды с этим инбаундом (здесь только RU-01)
hosts[1]["nodes"] = ["n-ru", "n-2"]
g = build(hosts=hosts)
texts = [w["text"] for w in g["warnings"]]
assert any("Bridge-Auto" in t and "2 нодам" in t for t in texts)
assert len(edges_from(g, "host:h7")) == 2
def test_host_inbound_not_active_on_node():
hosts = make_hosts()
hosts[4]["inbound"]["configProfileInboundUuid"] = INB_BRIDGE # у FI-01 такого инбаунда нет
g = build(hosts=hosts)
e = next(e for e in g["edges"] if e["source"] == "host:hd")
assert e["targetHandle"] == "head"
assert any("не активен на ноде FI-01" in w["text"] for w in g["warnings"])
def test_missing_outbound_and_balancer_are_reported():
profiles = make_profiles()
profiles[1]["config"]["routing"]["rules"][0]["outboundTag"] = "NOPE"
profiles[1]["config"]["routing"]["rules"][1]["balancerTag"] = "NOBAL"
del profiles[1]["config"]["routing"]["rules"][1]["outboundTag"]
g = build(profiles=profiles)
texts = " | ".join(w["text"] for w in g["warnings"])
assert "несуществующий outbound NOPE" in texts and "несуществующий балансер NOBAL" in texts
def test_input_not_mutated():
profile, hosts, nodes = make_profile(), make_hosts(), make_nodes()
snapshot = copy.deepcopy((profile, hosts, nodes))
build_graph(profile, hosts, nodes)
assert (profile, hosts, nodes) == snapshot
args = (make_profiles(), make_hosts(), make_nodes())
snapshot = copy.deepcopy(args)
build_graph(*args)
assert args == snapshot
def test_all_edge_endpoints_exist(g):
ids = set(by_id(g))
for e in g["edges"]:
assert e["source"] in ids and e["target"] in ids, e["id"]
assert len({e["id"] for e in g["edges"]}) == len(g["edges"])
for p in g["paths"].values():
assert set(p["edges"]) <= {e["id"] for e in g["edges"]}