fix topology of cards
This commit is contained in:
+209
-52
@@ -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"]}
|
||||
|
||||
Reference in New Issue
Block a user