init commit
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
"""Фикстура, повторяющая профиль BridgeOverNetbird и ноды из панели."""
|
||||
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"]
|
||||
|
||||
|
||||
def make_profile() -> dict:
|
||||
rules = [
|
||||
{"port": 25, "outboundTag": "BLOCK"},
|
||||
{"ip": ["geoip:private"], "outboundTag": "BLOCK"},
|
||||
{"domain": ["geosite:private"], "outboundTag": "BLOCK"},
|
||||
{"protocol": ["bittorrent"], "outboundTag": "BLOCK"},
|
||||
{"domain": ["geosite:category-ru", "domain:ru"], "outboundTag": "DIRECT"},
|
||||
{"ip": ["geoip:ru"], "outboundTag": "DIRECT"},
|
||||
*[{"vlessRoute": i, "outboundTag": f"BRIDGE_{i}"} for i in range(1, 7)],
|
||||
{"vlessRoute": 7, "balancerTag": "BRIDGE_AUTO"},
|
||||
{"inboundTag": ["RU_NODE_IN"], "balancerTag": "BRIDGE_AUTO"},
|
||||
*[{"domain": SC, "vlessRoute": 7 + i, "outboundTag": f"BRIDGE_{i}"} for i in range(1, 7)],
|
||||
{"domain": SC, "vlessRoute": 14, "balancerTag": "BRIDGE_AUTO"},
|
||||
{"vlessRoute": "8-14", "balancerTag": "BRIDGE_AUTO"},
|
||||
]
|
||||
config = {
|
||||
"inbounds": [{"tag": "RU_NODE_IN", "port": 443, "protocol": "vless",
|
||||
"streamSettings": {"realitySettings": {"privateKey": "SECRET-KEY"}}}],
|
||||
"outbounds": [{"tag": "DIRECT", "protocol": "freedom"},
|
||||
{"tag": "BLOCK", "protocol": "blackhole"}] + [
|
||||
{"tag": f"BRIDGE_{i + 1}", "protocol": "shadowsocks",
|
||||
"settings": {"servers": [{"address": ip, "port": 9999, "password": "SECRET-PASS"}]}}
|
||||
for i, ip in enumerate(BRIDGE_IPS)],
|
||||
"routing": {"rules": rules, "balancers": [
|
||||
{"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"}]}
|
||||
|
||||
|
||||
def make_nodes() -> list[dict]:
|
||||
nodes = [{"name": n, "address": ip, "countryCode": "XX", "isConnected": True, "isDisabled": False,
|
||||
"ips": [{"ip": ip, "status": "MANAGEMENT"}, {"ip": f"1.1.1.{i}", "status": "OUTBOUND"}],
|
||||
"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
|
||||
|
||||
|
||||
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
|
||||
@@ -0,0 +1,138 @@
|
||||
import base64
|
||||
|
||||
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
|
||||
|
||||
KEY = "aaaaaaaa-0000-0000-0000-000000000001"
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self):
|
||||
self.calls = 0
|
||||
self.fail = False
|
||||
|
||||
def fetch_all(self):
|
||||
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()}
|
||||
|
||||
|
||||
def make_settings(tmp_path, **kw):
|
||||
base = dict(remnawave_url="http://x", remnawave_token="t", cache_ttl=30, data_dir=tmp_path)
|
||||
base.update(kw)
|
||||
return Settings(**base)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client_and_fake(tmp_path):
|
||||
fake = FakeClient()
|
||||
app = create_app(make_settings(tmp_path), client=fake)
|
||||
return app.test_client(), fake
|
||||
|
||||
|
||||
def test_graph_default_profile_is_the_one_with_vless_route(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"]
|
||||
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")
|
||||
assert fake.calls == 1
|
||||
c.get("/api/graph?refresh=1") # слишком рано, игнорируется
|
||||
assert fake.calls == 1
|
||||
|
||||
|
||||
def test_stale_snapshot_on_upstream_error(tmp_path):
|
||||
fake = FakeClient()
|
||||
c = create_app(make_settings(tmp_path, cache_ttl=0), client=fake).test_client()
|
||||
assert c.get("/api/graph").status_code == 200
|
||||
fake.fail = True
|
||||
r = c.get("/api/graph")
|
||||
assert r.status_code == 200
|
||||
meta = r.get_json()["meta"]
|
||||
assert meta["stale"] is True and "недоступна" in meta["lastError"]
|
||||
|
||||
|
||||
def test_upstream_error_without_cache(tmp_path):
|
||||
fake = FakeClient()
|
||||
fake.fail = True
|
||||
c = create_app(make_settings(tmp_path), client=fake).test_client()
|
||||
r = c.get("/api/graph")
|
||||
assert r.status_code == 502 and r.get_json()["error"] == "upstream_unreachable"
|
||||
|
||||
|
||||
def test_positions_roundtrip(client_and_fake):
|
||||
c, _ = client_and_fake
|
||||
assert c.get(f"/api/positions/{KEY}").get_json() == {"positions": {}}
|
||||
r = c.put(f"/api/positions/{KEY}", json={"positions": {"rule:0": {"x": 10, "y": 20.5}}})
|
||||
assert r.get_json() == {"saved": 1}
|
||||
assert c.get("/api/graph").get_json()["positions"] == {"rule:0": {"x": 10.0, "y": 20.5}}
|
||||
assert c.delete(f"/api/positions/{KEY}").status_code == 204
|
||||
assert c.get(f"/api/positions/{KEY}").get_json() == {"positions": {}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [
|
||||
{"positions": []},
|
||||
{"positions": {"a": {"x": "1", "y": 2}}},
|
||||
{"positions": {"a": {"x": float("inf"), "y": 2}}},
|
||||
{"positions": {"a": {"x": True, "y": 2}}},
|
||||
{"nope": 1},
|
||||
])
|
||||
def test_positions_validation(client_and_fake, payload):
|
||||
c, _ = client_and_fake
|
||||
assert c.put(f"/api/positions/{KEY}", json=payload).status_code == 400
|
||||
|
||||
|
||||
def test_positions_bad_key(client_and_fake):
|
||||
c, _ = client_and_fake
|
||||
assert c.put("/api/positions/..%2Fetc", json={"positions": {}}).status_code in (400, 404)
|
||||
assert c.get("/api/positions/x").status_code == 400
|
||||
|
||||
|
||||
def test_basic_auth(tmp_path):
|
||||
app = create_app(make_settings(tmp_path, basic_user="u", basic_password="p"), client=FakeClient())
|
||||
c = app.test_client()
|
||||
assert c.get("/api/health").status_code == 200
|
||||
assert c.get("/api/graph").status_code == 401
|
||||
good = {"Authorization": "Basic " + base64.b64encode(b"u:p").decode()}
|
||||
bad = {"Authorization": "Basic " + base64.b64encode(b"u:x").decode()}
|
||||
assert c.get("/api/graph", headers=good).status_code == 200
|
||||
assert c.get("/api/graph", headers=bad).status_code == 401
|
||||
|
||||
|
||||
def test_spa_fallback(tmp_path):
|
||||
dist = tmp_path / "dist"
|
||||
(dist / "assets").mkdir(parents=True)
|
||||
(dist / "index.html").write_text("<h1>viz</h1>")
|
||||
(dist / "assets" / "a.js").write_text("1")
|
||||
c = create_app(make_settings(tmp_path, frontend_dist=dist), client=FakeClient()).test_client()
|
||||
assert b"viz" in c.get("/").data
|
||||
assert c.get("/assets/a.js").data == b"1"
|
||||
assert b"viz" in c.get("/some/route").data
|
||||
assert c.get("/api/unknown").status_code == 404
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Клиент против локального поддельного Remnawave (формы ответов как в спеке v3.4.11)."""
|
||||
import json
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
|
||||
import pytest
|
||||
|
||||
from app.remnawave import RemnawaveClient, RemnawaveError
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
seen_auth: list = []
|
||||
|
||||
def do_GET(self): # noqa: N802
|
||||
Handler.seen_auth.append(self.headers.get("Authorization"))
|
||||
if self.headers.get("Authorization") != "Bearer good":
|
||||
self.send_response(401); self.end_headers(); return
|
||||
bodies = {
|
||||
"/api/nodes": {"response": [{"name": "FR-01"}]},
|
||||
"/api/hosts": {"response": [{"remark": "h"}]},
|
||||
"/api/config-profiles": {"response": {"total": 1, "configProfiles": [{"name": "P"}]}},
|
||||
}
|
||||
if self.path == "/api/broken":
|
||||
payload = b"<html>not json</html>"
|
||||
elif self.path in bodies:
|
||||
payload = json.dumps(bodies[self.path]).encode()
|
||||
else:
|
||||
self.send_response(500); self.end_headers(); return
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def base():
|
||||
srv = HTTPServer(("127.0.0.1", 0), Handler)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
yield f"http://127.0.0.1:{srv.server_port}"
|
||||
srv.shutdown()
|
||||
|
||||
|
||||
def test_fetch_all_unwraps_responses(base):
|
||||
c = RemnawaveClient(base, "good")
|
||||
data = c.fetch_all()
|
||||
assert data == {"profiles": [{"name": "P"}], "hosts": [{"remark": "h"}], "nodes": [{"name": "FR-01"}]}
|
||||
|
||||
|
||||
def test_bad_token(base):
|
||||
with pytest.raises(RemnawaveError) as e:
|
||||
RemnawaveClient(base, "bad").nodes()
|
||||
assert e.value.code == "upstream_auth" and "bad" not in e.value.message
|
||||
|
||||
|
||||
def test_non_json_and_http_error(base):
|
||||
c = RemnawaveClient(base, "good")
|
||||
with pytest.raises(RemnawaveError) as e:
|
||||
c._get("/api/broken")
|
||||
assert e.value.code == "upstream_bad_response"
|
||||
with pytest.raises(RemnawaveError) as e:
|
||||
c._get("/api/other")
|
||||
assert e.value.code == "upstream_http"
|
||||
|
||||
|
||||
def test_unreachable():
|
||||
with pytest.raises(RemnawaveError) as e:
|
||||
RemnawaveClient("http://127.0.0.1:1", "t", timeout=1).nodes()
|
||||
assert e.value.code in {"upstream_unreachable", "upstream_timeout"}
|
||||
|
||||
|
||||
def test_extra_headers_are_sent(base):
|
||||
Handler.seen_auth.clear()
|
||||
RemnawaveClient(base, "good", extra_headers={"X-Forwarded-Proto": "https"}).nodes()
|
||||
assert Handler.seen_auth == ["Bearer good"]
|
||||
assert RemnawaveClient(base, "good", extra_headers={"X-A": "1"}).headers["X-A"] == "1"
|
||||
@@ -0,0 +1,97 @@
|
||||
import copy
|
||||
|
||||
import pytest
|
||||
|
||||
from app.graph import build_graph, parse_vless_route
|
||||
from .fixtures import make_hosts, make_nodes, make_profile
|
||||
|
||||
|
||||
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]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def g():
|
||||
return build_graph(make_profile(), make_hosts(), make_nodes())
|
||||
|
||||
|
||||
def test_parse_vless_route():
|
||||
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}
|
||||
|
||||
|
||||
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_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_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_no_secrets_in_output(g):
|
||||
dump = str(g)
|
||||
assert "SECRET" not in dump
|
||||
|
||||
|
||||
def test_disabled_and_offline_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"}
|
||||
|
||||
|
||||
def test_all_nodes_down_warns():
|
||||
nodes = make_nodes()
|
||||
for n in nodes:
|
||||
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
|
||||
|
||||
|
||||
def test_unresolved_outbound():
|
||||
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"])
|
||||
|
||||
|
||||
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
|
||||
Reference in New Issue
Block a user