init commit

This commit is contained in:
Udo
2026-12-01 10:02:27 +05:00
commit 200083e3ef
36 changed files with 5611 additions and 0 deletions
+89
View File
@@ -0,0 +1,89 @@
"""Flask-бэкенд визуализатора маршрутов Remnawave."""
from __future__ import annotations
import hmac
import logging
from datetime import datetime, timezone
from types import SimpleNamespace
from flask import Flask, abort, jsonify, request, send_from_directory
from .cache import SnapshotCache
from .config import Settings
from .positions import PositionStore
from .remnawave import RemnawaveClient
from .routes import bp
def create_app(settings: Settings | None = None, client=None) -> Flask:
settings = settings or Settings.from_env()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
if client is None:
client = RemnawaveClient(settings.remnawave_url, settings.remnawave_token,
settings.http_timeout, settings.verify_tls, settings.extra_headers)
def load():
data = client.fetch_all()
data["fetchedAt"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
return data
app = Flask(__name__)
app.json.ensure_ascii = False
app.config["MAX_CONTENT_LENGTH"] = 1024 * 1024
app.extensions["rwviz"] = SimpleNamespace(
settings=settings,
cache=SnapshotCache(load, settings.cache_ttl),
positions=PositionStore(settings.data_dir / "positions.json"),
)
app.register_blueprint(bp)
if settings.basic_user and settings.basic_password:
want_user, want_pass = settings.basic_user, settings.basic_password
@app.before_request
def _auth():
if request.method == "OPTIONS" or request.path == "/api/health":
return None
a = request.authorization
ok = (a is not None
and hmac.compare_digest(a.username or "", want_user)
and hmac.compare_digest(a.password or "", want_pass))
if not ok:
return jsonify(error="unauthorized", message="Нужна авторизация"), 401, {
"WWW-Authenticate": 'Basic realm="rw-viz"'}
return None
else:
logging.getLogger(__name__).warning(
"BASIC_AUTH_USER/PASSWORD не заданы: API открыт всем, кто достанет до порта")
if settings.cors_origins:
@app.after_request
def _cors(resp):
origin = request.headers.get("Origin")
if origin in settings.cors_origins:
resp.headers["Access-Control-Allow-Origin"] = origin
resp.headers["Vary"] = "Origin"
resp.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
resp.headers["Access-Control-Allow-Methods"] = "GET, PUT, DELETE, OPTIONS"
return resp
dist = settings.frontend_dist
if dist and dist.is_dir():
@app.get("/", defaults={"path": ""})
@app.get("/<path:path>")
def _spa(path: str):
if path.startswith("api/"):
abort(404)
if path and (dist / path).is_file():
return send_from_directory(dist, path)
return send_from_directory(dist, "index.html")
@app.errorhandler(404)
def _404(_e):
return jsonify(error="not_found", message="Не найдено"), 404
@app.errorhandler(413)
def _413(_e):
return jsonify(error="too_large", message="Слишком большое тело запроса"), 413
return app
+37
View File
@@ -0,0 +1,37 @@
"""TTL-кэш снимка панели. При ошибке панели отдаёт устаревший снимок."""
from __future__ import annotations
import threading
import time
from typing import Any, Callable
from .remnawave import RemnawaveError
MIN_REFRESH_INTERVAL = 5.0 # ?refresh=1 не чаще, чем раз в 5 секунд
class SnapshotCache:
def __init__(self, loader: Callable[[], Any], ttl: float):
self._loader = loader
self._ttl = ttl
self._lock = threading.Lock()
self._value: Any = None
self._at = 0.0
def get(self, force: bool = False) -> tuple[Any, dict]:
with self._lock:
age = time.monotonic() - self._at
fresh = self._value is not None and age < self._ttl
if force and age < MIN_REFRESH_INTERVAL:
force = False
if fresh and not force:
return self._value, {"cached": True, "stale": False, "ageSeconds": round(age, 1)}
try:
self._value = self._loader()
self._at = time.monotonic()
return self._value, {"cached": False, "stale": False, "ageSeconds": 0.0}
except RemnawaveError as e:
if self._value is None:
raise
return self._value, {"cached": True, "stale": True,
"ageSeconds": round(age, 1), "lastError": e.message}
+68
View File
@@ -0,0 +1,68 @@
"""Настройки из переменных окружения."""
from __future__ import annotations
import json
import os
from dataclasses import dataclass, field
from pathlib import Path
try: # python-dotenv необязателен: в Docker всё приходит из env_file
from dotenv import load_dotenv
load_dotenv()
except ImportError: # pragma: no cover
pass
def _bool(value: str | None, default: bool) -> bool:
if value is None or value == "":
return default
return value.strip().lower() in {"1", "true", "yes", "on"}
@dataclass(frozen=True)
class Settings:
remnawave_url: str
remnawave_token: str
cache_ttl: float = 30.0
http_timeout: float = 10.0
verify_tls: bool = True
extra_headers: dict[str, str] = field(default_factory=dict)
default_profile: str | None = None
data_dir: Path = Path("data")
basic_user: str | None = None
basic_password: str | None = None
frontend_dist: Path | None = None
cors_origins: tuple[str, ...] = ()
@classmethod
def from_env(cls) -> "Settings":
url = os.environ.get("REMNAWAVE_URL", "").strip().rstrip("/")
token = os.environ.get("REMNAWAVE_TOKEN", "").strip()
if not url or not token:
raise RuntimeError("Нужны переменные REMNAWAVE_URL и REMNAWAVE_TOKEN")
extra: dict[str, str] = {}
raw_headers = os.environ.get("REMNAWAVE_EXTRA_HEADERS", "").strip()
if raw_headers:
try:
extra = {str(k): str(v) for k, v in json.loads(raw_headers).items()}
except (ValueError, AttributeError) as e:
raise RuntimeError("REMNAWAVE_EXTRA_HEADERS должен быть JSON-объектом") from e
dist = os.environ.get("FRONTEND_DIST", "").strip()
origins = tuple(o.strip() for o in os.environ.get("CORS_ORIGINS", "").split(",") if o.strip())
return cls(
remnawave_url=url,
remnawave_token=token,
cache_ttl=float(os.environ.get("CACHE_TTL", "30")),
http_timeout=float(os.environ.get("HTTP_TIMEOUT", "10")),
verify_tls=_bool(os.environ.get("VERIFY_TLS"), True),
extra_headers=extra,
default_profile=os.environ.get("DEFAULT_PROFILE", "").strip() or None,
data_dir=Path(os.environ.get("DATA_DIR", "data")),
basic_user=os.environ.get("BASIC_AUTH_USER") or None,
basic_password=os.environ.get("BASIC_AUTH_PASSWORD") or None,
frontend_dist=Path(dist) if dist else None,
cors_origins=origins,
)
+252
View File
@@ -0,0 +1,252 @@
"""Сборка графа маршрутизации Remnawave: профиль + хосты + ноды -> {nodes, edges, warnings}.
Колонки слева направо: host -> inbound -> rule(ы) -> balancer -> outbound -> node.
Только чтение, без статистики и юзеров.
"""
from __future__ import annotations
# Ключи правила, которые мы умеем вычислять точно (остальные = "условные").
_TARGET_KEYS = {"outboundTag", "balancerTag", "ruleTag", "type"}
_EXACT_KEYS = {"vlessRoute", "inboundTag"}
def parse_vless_route(value) -> set[int] | None:
"""1 | "8-14" | "1,3,8-10" -> множество номеров; None, если поля нет."""
if value is None:
return None
if isinstance(value, int):
return {value}
out: set[int] = set()
for part in str(value).split(","):
part = part.strip()
if "-" in part:
a, b = part.split("-", 1)
out.update(range(int(a), int(b) + 1))
elif part:
out.add(int(part))
return out
def _conditions(rule: dict) -> set[str]:
return set(rule) - _TARGET_KEYS
def _opaque(rule: dict) -> set[str]:
"""Условия, которые нельзя вычислить статически (domain, ip, port, protocol...)."""
return _conditions(rule) - _EXACT_KEYS
def rule_label(rule: dict) -> str:
parts = []
for k in sorted(_conditions(rule)):
v = rule[k]
if isinstance(v, list):
shown = ", ".join(map(str, v[:3])) + (f" +{len(v) - 3}" if len(v) > 3 else "")
else:
shown = str(v)
parts.append(f"{k}: {shown}")
return "; ".join(parts) or "любой трафик"
def find_shadowed(rules: list[dict], inbound_tags: set[str]) -> set[int]:
"""Правила после catch-all недостижимы (Xray: первое совпавшее правило выигрывает)."""
for i, r in enumerate(rules):
cond = _conditions(r)
if not cond or (cond == {"inboundTag"} and set(r["inboundTag"]) >= inbound_tags):
return set(range(i + 1, len(rules)))
return set()
def trace_host(rules: list[dict], route: int | None, inbound_tag: str) -> list[int]:
"""Индексы правил, через которые может пройти трафик хоста, до первого безусловного."""
path: list[int] = []
for i, r in enumerate(rules):
routes = parse_vless_route(r.get("vlessRoute"))
if routes is not None and route not in routes:
continue
tags = r.get("inboundTag")
if tags and inbound_tag not in tags:
continue
path.append(i)
if not _opaque(r):
break
return path
def node_state(n: dict) -> str:
"""disabled | connecting | offline | online."""
if n.get("isDisabled"):
return "disabled"
if n.get("isConnecting"):
return "connecting"
return "offline" if n.get("isConnected") is False else "online"
def build_node_index(nodes: list[dict]) -> dict[str, dict]:
"""ip -> нода. MANAGEMENT-адреса в приоритете, затем address, затем остальные ips.
Живые ноды идут первыми: если отключённая нода хранит тот же адрес, что и рабочая,
выигрывает рабочая.
"""
ordered = sorted(nodes, key=lambda n: node_state(n) != "online") # sort стабильный
idx: dict[str, dict] = {}
for n in ordered:
for e in n.get("ips") or []:
if e["status"] == "MANAGEMENT":
idx.setdefault(e["ip"], n)
for n in ordered:
idx.setdefault(n["address"], n)
for e in n.get("ips") or []:
idx.setdefault(e["ip"], n)
return idx
def node_info(n: dict) -> dict:
ips = n.get("ips") or []
by = lambda st: [e["ip"] for e in ips if e["status"] == st] # noqa: E731
ifaces = ((n.get("system") or {}).get("info") or {}).get("networkInterfaces") or []
return {
"name": n["name"],
"country": n.get("countryCode"),
"state": node_state(n),
"connected": n.get("isConnected"),
"disabled": bool(n.get("isDisabled")),
"mgmt": by("MANAGEMENT"),
"exit": by("OUTBOUND"),
"inbound": by("INBOUND"),
"reserve": by("RESERVE"),
"netbird": "wt0" in ifaces,
}
def outbound_ip(ob: dict) -> str | None:
try:
return ob["settings"]["servers"][0]["address"]
except (KeyError, IndexError, TypeError):
return None # freedom / blackhole
def build_graph(profile: dict, hosts: list[dict], nodes: list[dict]) -> dict:
cfg = profile["config"]
rules = cfg.get("routing", {}).get("rules", [])
balancers = cfg.get("routing", {}).get("balancers", [])
outbounds = cfg.get("outbounds", [])
inbounds = cfg.get("inbounds", [])
inbound_tags = {i["tag"] for i in inbounds}
G_nodes: list[dict] = []
G_edges: list[dict] = []
warnings: list[str] = []
def add_node(id_, type_, label, **data):
G_nodes.append({"id": id_, "type": type_, "label": label, "data": data})
def add_edge(src, dst, kind="flow", label=None, **data):
G_edges.append({"id": f"{src}->{dst}:{kind}", "source": src, "target": dst,
"kind": kind, "label": label, "data": data})
shadowed = find_shadowed(rules, inbound_tags)
idx = build_node_index(nodes)
def _out_alive(o: dict) -> bool:
ip = outbound_ip(o)
if ip is None: # freedom / blackhole
return True
n = idx.get(ip)
return n is not None and node_state(n) == "online"
alive = {o["tag"]: _out_alive(o) for o in outbounds}
bal_members = {
b["tag"]: [o["tag"] for o in outbounds
if any(o["tag"].startswith(x) for x in b.get("selector", []))]
for b in balancers
}
def target_alive(r: dict) -> bool:
if "balancerTag" in r:
return any(alive.get(m, False) for m in bal_members.get(r["balancerTag"], []))
return alive.get(r.get("outboundTag"), False)
# inbounds
for i in inbounds:
add_node(f"inb:{i['tag']}", "inbound", i["tag"],
port=i.get("port"), protocol=i.get("protocol"))
# rules + цепочка fallthrough + цель
for i, r in enumerate(rules):
rid = f"rule:{i}"
add_node(rid, "rule", f"#{i} {rule_label(r)}", index=i, shadowed=i in shadowed,
vlessRoute=sorted(parse_vless_route(r.get("vlessRoute")) or []))
target = f"bal:{r['balancerTag']}" if "balancerTag" in r else f"out:{r.get('outboundTag')}"
add_edge(rid, target, "target", dead=i in shadowed)
if i + 1 < len(rules):
add_edge(rid, f"rule:{i + 1}", "fallthrough", dead=(i + 1) in shadowed)
if i in shadowed:
warnings.append(f"rule #{i} ({rule_label(r)}) недостижимо: выше есть catch-all")
if rules:
for tag in inbound_tags:
add_edge(f"inb:{tag}", "rule:0", "flow")
# balancers
for b in balancers:
members = bal_members[b["tag"]]
live = [m for m in members if alive[m]]
add_node(f"bal:{b['tag']}", "balancer", b["tag"],
strategy=(b.get("strategy") or {}).get("type"), members=members,
aliveMembers=live)
for m in members:
add_edge(f"bal:{b['tag']}", f"out:{m}", "member", dead=not alive[m])
fb = b.get("fallbackTag")
if fb:
add_edge(f"bal:{b['tag']}", f"out:{fb}", "fallback", "fallback",
dead=not alive.get(fb, False))
if not live:
warnings.append(f"balancer {b['tag']}: нет ни одного живого члена")
elif fb and not alive.get(fb, False):
warnings.append(f"balancer {b['tag']}: fallback {fb} ведёт на нерабочую ноду")
# outbounds -> ноды
seen_nodes: set[str] = set()
for o in outbounds:
ip = outbound_ip(o)
add_node(f"out:{o['tag']}", "outbound", o["tag"], protocol=o["protocol"], ip=ip,
alive=alive[o["tag"]])
if ip is None:
continue
n = idx.get(ip)
if n is None:
add_node(f"unresolved:{ip}", "unresolved", ip)
add_edge(f"out:{o['tag']}", f"unresolved:{ip}", "link")
warnings.append(f"outbound {o['tag']}: адрес {ip} не найден ни в одной карточке ноды")
continue
nid = f"node:{n['name']}"
if nid not in seen_nodes:
seen_nodes.add(nid)
add_node(nid, "node", n["name"], **node_info(n))
add_edge(f"out:{o['tag']}", nid, "link", ip, dead=not alive[o["tag"]])
if not alive[o["tag"]]:
warnings.append(f"outbound {o['tag']} → {n['name']}: нода {node_state(n)}")
# хосты профиля
uuid_to_tag = {i["uuid"]: i["tag"] for i in (profile.get("inbounds") or [])}
for h in hosts:
tag = uuid_to_tag.get((h.get("inbound") or {}).get("configProfileInboundUuid"))
if tag is None:
continue # хост другого профиля
route = h.get("vlessRouteId")
path = trace_host(rules, route, tag)
end = path[-1] if path else None
hid = f"host:{h['uuid']}"
add_node(hid, "host", h["remark"], address=h.get("address"), port=h.get("port"),
vlessRouteId=route, disabled=h.get("isDisabled"),
trace=[f"rule:{i}" for i in path],
exitAlive=target_alive(rules[end]) if end is not None else False)
add_edge(hid, f"inb:{tag}", "flow")
if end is not None:
add_edge(hid, f"rule:{end}", "route", f"route {route}" if route is not None else "default",
dead=not target_alive(rules[end]))
if not target_alive(rules[end]) and not h.get("isDisabled"):
warnings.append(f"хост {h['remark']}: выход правила #{end} ведёт на нерабочую ноду")
return {"nodes": G_nodes, "edges": G_edges, "warnings": warnings}
+82
View File
@@ -0,0 +1,82 @@
"""Хранилище позиций узлов (JSON-файл, запись атомарная)."""
from __future__ import annotations
import json
import logging
import math
import os
import re
import tempfile
import threading
from pathlib import Path
log = logging.getLogger(__name__)
MAX_ENTRIES = 5000
_KEY_RE = re.compile(r"^[0-9A-Za-z-]{8,64}$")
def valid_key(key: str) -> bool:
return bool(_KEY_RE.match(key))
def clean_positions(raw) -> dict[str, dict[str, float]]:
if not isinstance(raw, dict):
raise ValueError("positions должен быть объектом {id: {x, y}}")
if len(raw) > MAX_ENTRIES:
raise ValueError("слишком много узлов")
out: dict[str, dict[str, float]] = {}
for node_id, pos in raw.items():
if not isinstance(node_id, str) or not 0 < len(node_id) <= 200:
raise ValueError("некорректный id узла")
if not isinstance(pos, dict):
raise ValueError(f"позиция {node_id!r} должна быть объектом")
coords = []
for axis in ("x", "y"):
v = pos.get(axis)
if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v):
raise ValueError(f"{node_id!r}: {axis} должно быть конечным числом")
coords.append(float(v))
out[node_id] = {"x": coords[0], "y": coords[1]}
return out
class PositionStore:
def __init__(self, path: Path):
self.path = path
self._lock = threading.Lock()
def _read(self) -> dict:
try:
return json.loads(self.path.read_text(encoding="utf-8"))
except FileNotFoundError:
return {}
except ValueError:
log.warning("positions: файл %s повреждён, начинаю с пустого", self.path)
return {}
def _write(self, data: dict) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=self.path.parent, prefix=".positions-")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=1)
os.replace(tmp, self.path)
except BaseException:
Path(tmp).unlink(missing_ok=True)
raise
def get(self, key: str) -> dict:
with self._lock:
return self._read().get(key, {})
def put(self, key: str, positions: dict) -> None:
with self._lock:
data = self._read()
data[key] = positions
self._write(data)
def delete(self, key: str) -> None:
with self._lock:
data = self._read()
if data.pop(key, None) is not None:
self._write(data)
+64
View File
@@ -0,0 +1,64 @@
"""Клиент Remnawave API (только чтение)."""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
from typing import Any
import requests
class RemnawaveError(Exception):
"""Ошибка обращения к панели. Токен в сообщения не попадает."""
def __init__(self, message: str, code: str = "upstream_error", http_status: int = 502):
super().__init__(message)
self.message = message
self.code = code
self.http_status = http_status
class RemnawaveClient:
def __init__(self, base_url: str, token: str, timeout: float = 10.0,
verify: bool = True, extra_headers: dict[str, str] | None = None):
self.base = base_url.rstrip("/")
self.timeout = timeout
self.verify = verify
self.headers = {"Authorization": f"Bearer {token}", "Accept": "application/json",
**(extra_headers or {})}
def _get(self, path: str) -> Any:
try:
r = requests.get(f"{self.base}{path}", headers=self.headers,
timeout=self.timeout, verify=self.verify)
except requests.Timeout:
raise RemnawaveError(f"Таймаут запроса {path}", "upstream_timeout", 504) from None
except requests.RequestException as e:
raise RemnawaveError(f"Не удалось подключиться к Remnawave ({type(e).__name__})",
"upstream_unreachable") from None
if r.status_code in (401, 403):
raise RemnawaveError("Remnawave отклонил токен (401/403)", "upstream_auth")
if not r.ok:
raise RemnawaveError(f"{path}: HTTP {r.status_code}", "upstream_http")
try:
body = r.json()
except ValueError:
raise RemnawaveError(f"{path}: ответ не JSON (проверь REMNAWAVE_URL)",
"upstream_bad_response") from None
return body.get("response", body) if isinstance(body, dict) else body
def profiles(self) -> list[dict]:
data = self._get("/api/config-profiles")
return data.get("configProfiles", []) if isinstance(data, dict) else data
def hosts(self) -> list[dict]:
return self._get("/api/hosts")
def nodes(self) -> list[dict]:
return self._get("/api/nodes")
def fetch_all(self) -> dict[str, list[dict]]:
"""Три запроса параллельно."""
calls = {"profiles": self.profiles, "hosts": self.hosts, "nodes": self.nodes}
with ThreadPoolExecutor(max_workers=3) as ex:
futures = {k: ex.submit(fn) for k, fn in calls.items()}
return {k: f.result() for k, f in futures.items()}
+116
View File
@@ -0,0 +1,116 @@
"""HTTP API."""
from __future__ import annotations
from flask import Blueprint, current_app, jsonify, request
from .graph import build_graph
from .positions import clean_positions, valid_key
from .remnawave import RemnawaveError
bp = Blueprint("api", __name__, url_prefix="/api")
class ProfileNotFound(LookupError):
pass
def _svc():
return current_app.extensions["rwviz"]
def _rules(profile: dict) -> list[dict]:
return ((profile.get("config") or {}).get("routing") or {}).get("rules") or []
def pick_profile(profiles: list[dict], wanted: str | None, default: str | None) -> dict | None:
profiles = [p for p in profiles if isinstance(p.get("config"), dict)]
key = (wanted or default or "").strip().lower()
if key:
for p in profiles:
if p["uuid"].lower() == key or p["name"].lower() == key:
return p
raise ProfileNotFound(wanted or default)
for p in profiles: # по умолчанию - первый профиль с vlessRoute
if any("vlessRoute" in r for r in _rules(p)):
return p
return profiles[0] if profiles else None
@bp.get("/health")
def health():
return {"status": "ok"}
@bp.get("/profiles")
def profiles():
snap, meta = _svc().cache.get()
items = [{
"uuid": p["uuid"],
"name": p["name"],
"inbounds": len(p.get("inbounds") or []),
"rules": len(_rules(p)),
"nodes": [n.get("name") for n in p.get("nodes") or []],
} for p in snap["profiles"] if isinstance(p.get("config"), dict)]
return jsonify({"profiles": items, "meta": {**meta, "fetchedAt": snap["fetchedAt"]}})
@bp.get("/graph")
def graph():
svc = _svc()
force = request.args.get("refresh", "").lower() in {"1", "true", "yes"}
snap, meta = svc.cache.get(force=force)
profile = pick_profile(snap["profiles"], request.args.get("profile"), svc.settings.default_profile)
if profile is None:
return jsonify(error="no_profiles", message="В панели нет config-профилей"), 404
try:
result = build_graph(profile, snap["hosts"], snap["nodes"])
except (KeyError, TypeError, ValueError) as e:
current_app.logger.exception("graph build failed")
return jsonify(error="graph_build_failed",
message=f"Не удалось разобрать профиль {profile['name']!r}: {type(e).__name__}: {e}"), 422
return jsonify({
"profile": {"uuid": profile["uuid"], "name": profile["name"]},
"graph": result,
"positions": svc.positions.get(profile["uuid"]),
"meta": {**meta, "fetchedAt": snap["fetchedAt"]},
})
@bp.get("/positions/<key>")
def get_positions(key: str):
if not valid_key(key):
return jsonify(error="bad_key", message="Некорректный идентификатор профиля"), 400
return jsonify({"positions": _svc().positions.get(key)})
@bp.put("/positions/<key>")
def put_positions(key: str):
if not valid_key(key):
return jsonify(error="bad_key", message="Некорректный идентификатор профиля"), 400
body = request.get_json(silent=True)
if not isinstance(body, dict) or "positions" not in body:
return jsonify(error="bad_body", message='Ожидается {"positions": {...}}'), 400
try:
positions = clean_positions(body["positions"])
except ValueError as e:
return jsonify(error="bad_positions", message=str(e)), 400
_svc().positions.put(key, positions)
return jsonify({"saved": len(positions)})
@bp.delete("/positions/<key>")
def delete_positions(key: str):
if not valid_key(key):
return jsonify(error="bad_key", message="Некорректный идентификатор профиля"), 400
_svc().positions.delete(key)
return "", 204
@bp.errorhandler(RemnawaveError)
def _upstream(e: RemnawaveError):
return jsonify(error=e.code, message=e.message), e.http_status
@bp.errorhandler(ProfileNotFound)
def _no_profile(e: ProfileNotFound):
return jsonify(error="profile_not_found", message=f"Профиль {e} не найден"), 404
+2
View File
@@ -0,0 +1,2 @@
[pytest]
testpaths = tests
+2
View File
@@ -0,0 +1,2 @@
-r requirements.txt
pytest>=8.0
+4
View File
@@ -0,0 +1,4 @@
Flask>=3.0,<4
requests>=2.32,<3
gunicorn>=22.0
python-dotenv>=1.0
View File
+56
View File
@@ -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
+138
View File
@@ -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
+78
View File
@@ -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"
+97
View File
@@ -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
+3
View File
@@ -0,0 +1,3 @@
from app import create_app
app = create_app()