feat(network): integrate NetBird clients, profiles and private backups

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 00:42:25 +03:00
parent 1e77b198cb
commit 2c0a10b687
47 changed files with 2721 additions and 82 deletions
+438
View File
@@ -0,0 +1,438 @@
import hashlib
from pathlib import Path
from types import SimpleNamespace
import pytest
from fastapi import APIRouter, FastAPI
from fastapi.testclient import TestClient
from k1link.fleet.netbird import assets, client
from k1link.web.fleet_api import local_operator
from k1link.web.netbird_api import register
@pytest.mark.parametrize(
"url",
[
"http://example.com",
"https://admin:password@example.com",
"https://example.com/api",
"https://example.com?key=secret",
"https://localhost",
"https://127.0.0.1",
"https://169.254.169.254",
"https://example.com:99999",
"--help",
],
)
def test_server_url_rejects_unsafe_or_ambiguous_target(url):
with pytest.raises(ValueError):
client.server_url(url)
def test_connected_means_selected_daemon_profile_and_private_overlay():
status = {
"management": {"url": "https://network.example:8443", "connected": True},
"signal": {"connected": True},
"profileName": "mission-core",
"netbirdIp": "10.204.5.7/16",
}
assert client.project_status(status, "https://network.example:8443")["state"] == "connected"
assert client.project_status(status, "https://other.example")["state"] == "other_network"
assert (
client.project_status(status | {"profileName": "personal"}, "https://network.example:8443")[
"state"
]
== "other_network"
)
assert (
client.project_status(
status | {"netbirdIp": "100.80.6.113/16"}, "https://network.example:8443"
)["state"]
== "address_conflict"
)
assert (
client.project_status(
status | {"signal": {"connected": False}}, "https://network.example:8443"
)["state"]
== "disconnected"
)
def test_damaged_local_profile_does_not_stop_mission_core(tmp_path):
path = tmp_path / "networks/netbird.json"
path.parent.mkdir()
path.write_text("damaged")
value = client.Client(tmp_path)
assert value.server == ""
assert value.error
def test_foreign_connected_client_is_never_reconfigured(tmp_path, monkeypatch):
value = client.Client(tmp_path)
monkeypatch.setattr(client, "executable", lambda: Path("/synthetic/netbird"))
monkeypatch.setattr(value, "status", lambda **kw: {"state": "other_network"})
monkeypatch.setattr(client.subprocess, "Popen", lambda *a, **kw: pytest.fail("must not spawn"))
value.connect("https://our.example")
value.worker.join(timeout=2)
assert "другую сеть" in value.error
assert not value.path.exists()
def test_failed_server_preflight_never_runs_client_or_saves_target(tmp_path, monkeypatch):
value = client.Client(tmp_path)
monkeypatch.setattr(value, "status", lambda **kw: {"state": "disconnected"})
monkeypatch.setattr(client, "preflight", lambda url: (_ for _ in ()).throw(ValueError()))
monkeypatch.setattr(client.subprocess, "Popen", lambda *a, **kw: pytest.fail("must not spawn"))
value._connect(Path("/synthetic/netbird"), "https://our.example")
assert value.error and not value.pending
assert not value.path.exists()
def test_local_catalog_rejects_modified_payload_and_symlink(tmp_path, monkeypatch):
payload = b"synthetic vendor package"
row = dict(
id="test",
label="Test",
filename="test.pkg",
bytes=len(payload),
sha256=hashlib.sha256(payload).hexdigest(),
)
monkeypatch.setattr(assets, "LOCK", {"items": [row]})
directory = assets.directory(tmp_path)
directory.mkdir(parents=True)
file = directory / "test.pkg"
file.write_bytes(payload)
assert assets.verify(tmp_path, "test") == file
file.write_bytes(b"X" * len(payload))
assert not assets.catalog(tmp_path)["items"][0]["available"]
file.unlink()
other = tmp_path / "other.pkg"
other.write_bytes(payload)
file.symlink_to(other)
with pytest.raises(ValueError):
assets.verify(tmp_path, "test")
with pytest.raises(ValueError):
assets.verify(tmp_path, "../other.pkg")
def test_network_controls_have_same_local_operator_boundary(tmp_path):
app = FastAPI()
router = APIRouter(prefix="/api/v1/fleet")
register(router, local_operator)
app.include_router(router)
app.state.fleet = SimpleNamespace(
netbird=SimpleNamespace(status=lambda: {"state": "missing_client"}), root=tmp_path
)
with TestClient(app, base_url="http://127.0.0.1", client=("127.0.0.1", 32123)) as web:
assert web.get("/api/v1/fleet/netbird").status_code == 200
assert (
web.post(
"/api/v1/fleet/netbird/install", headers={"Origin": "https://unrelated.example"}
).status_code
== 403
)
assert (
web.get("/api/v1/fleet/netbird", headers={"Host": "unrelated.example"}).status_code
== 403
)
assert web.get("/api/v1/fleet/netbird/clients/unknown").status_code == 404
def test_client_does_not_request_dns_routes_remote_shell_or_motion():
assert "--disable-dns" in client.SAFE_FLAGS
assert "--disable-client-routes" in client.SAFE_FLAGS
assert "--disable-server-routes" in client.SAFE_FLAGS
assert "--allow-server-ssh=false" in client.SAFE_FLAGS
assert "--network-monitor=true" in client.SAFE_FLAGS
def test_preflight_refuses_redirect_before_contacting_destination():
handler = client._NoRedirect()
request = client.urllib.request.Request(
"https://network.example/.well-known/missioncore-network.json"
)
with pytest.raises(ValueError, match="перенаправляет"):
handler.redirect_request(request, None, 302, "Found", {}, "http://127.0.0.1:8000")
@pytest.mark.skipif(client.platform.system() != "Darwin", reason="macOS installer staging")
def test_macos_install_stages_verified_package_outside_protected_folder(tmp_path, monkeypatch):
payload = b"synthetic signed installer"
package = tmp_path / "Downloads" / "NetBird.pkg"
package.parent.mkdir()
package.write_bytes(payload)
monkeypatch.setattr(client, "item", lambda _: {"sha256": hashlib.sha256(payload).hexdigest()})
observed = []
def install(arguments, **kwargs):
import re
assert arguments[:2] == ["/usr/bin/osascript", "-e"]
match = re.search(r"(/private/tmp/ndc-netbird-install-[^ /]+/NetBird.pkg)", arguments[2])
staged = Path(match[1])
assert staged.read_bytes() == payload
assert staged.stat().st_mode & 0o077 == 0
assert "with administrator privileges" in arguments[2]
observed.append(staged)
return SimpleNamespace(returncode=0)
monkeypatch.setattr(client.subprocess, "run", install)
value = client.Client(tmp_path)
value._install(package)
assert not value.error
assert len(observed) == 1 and not observed[0].exists()
assert package.read_bytes() == payload
def connected_raw():
return {
"management": {"url": "https://network.example:8443", "connected": True},
"signal": {"connected": True},
"profileName": client.PROFILE,
"daemonVersion": client.VERSION,
"netbirdIp": "10.204.5.7/16",
}
def test_selected_network_and_daemon_version_are_required():
raw = connected_raw()
assert (
client.project_status(raw, "https://network.example:8443", "10.205.0.0/16")["state"]
== "address_conflict"
)
assert (
client.project_status(
raw | {"netbirdIp": "10.203.172.2/24"}, "https://network.example:8443"
)["state"]
== "address_conflict"
)
assert (
client.project_status(raw | {"daemonVersion": "0.81.0"}, "https://network.example:8443")[
"state"
]
== "unsupported_client"
)
def test_slow_probe_does_not_block_cancel_and_other_polls(tmp_path, monkeypatch):
import threading
import time
value = client.Client(tmp_path)
entered, release = threading.Event(), threading.Event()
monkeypatch.setattr(client, "executable", lambda: Path("/synthetic/netbird"))
def invoke(*args):
entered.set()
assert release.wait(3)
return SimpleNamespace(returncode=1, stdout="")
monkeypatch.setattr(client, "invoke", invoke)
thread = threading.Thread(target=value.status)
thread.start()
try:
assert entered.wait(1)
start = time.monotonic()
assert value.status()["state"] == "unavailable"
value.cancel()
assert time.monotonic() - start < 0.5
finally:
release.set()
thread.join(3)
def test_failed_cli_status_cannot_be_connected(tmp_path, monkeypatch):
import json
value = client.Client(tmp_path)
value.server = "https://network.example:8443"
monkeypatch.setattr(client, "executable", lambda: Path("/synthetic/netbird"))
monkeypatch.setattr(
client,
"invoke",
lambda _, cmd, *args: SimpleNamespace(
returncode=0 if cmd == "version" else 1,
stdout=client.VERSION if cmd == "version" else json.dumps(connected_raw()),
),
)
assert value.status()["state"] == "unavailable"
def test_cancelled_preflight_cannot_launch_connection(tmp_path, monkeypatch):
import threading
value = client.Client(tmp_path)
entered, release = threading.Event(), threading.Event()
monkeypatch.setattr(client, "executable", lambda: Path("/synthetic/netbird"))
monkeypatch.setattr(value, "status", lambda **kw: {"state": "disconnected"})
def preflight(url):
entered.set()
assert release.wait(3)
return {"network": "10.204.0.0/16"}
monkeypatch.setattr(client, "preflight", preflight)
monkeypatch.setattr(client.subprocess, "Popen", lambda *a, **kw: pytest.fail("cancelled"))
value.connect("https://network.example:8443")
assert entered.wait(1)
with pytest.raises(ValueError, match="текущей операции"):
value.connect("https://network.example:8443")
value.cancel()
release.set()
value.worker.join(3)
assert not value.path.exists() and not value.pending
assert "отменено" in value.error
def test_repeated_connect_verifies_server_without_restart(tmp_path, monkeypatch):
import json
value = client.Client(tmp_path)
value.server = "https://network.example:8443"
monkeypatch.setattr(client, "executable", lambda: Path("/synthetic/netbird"))
monkeypatch.setattr(value, "status", lambda **kw: {"state": "connected"})
monkeypatch.setattr(client, "preflight", lambda url: {"network": "10.204.0.0/16"})
monkeypatch.setattr(
client.subprocess, "Popen", lambda *a, **kw: pytest.fail("already connected")
)
value.connect(value.server)
value.worker.join(3)
assert not value.error and not value.pending
assert json.loads(value.path.read_text())["network"] == "10.204.0.0/16"
assert "token" not in value.path.read_text()
def test_preflight_requires_verified_access_policy(tmp_path, monkeypatch):
import io
import json
url = "https://network.example:8443"
receipt = {
"schema": "missioncore.netbird-server/v1",
"ready": True,
"management_url": url,
"network": "10.204.0.0/16",
"client_version": client.VERSION,
}
def opener(*args):
def open_response(*args, **kwargs):
stream = io.BytesIO(json.dumps(receipt).encode())
stream.url = url + "/.well-known/missioncore-network.json"
return stream
return SimpleNamespace(open=open_response)
monkeypatch.setattr(client.urllib.request, "build_opener", opener)
with pytest.raises(ValueError, match="правила доступа"):
client.preflight(url)
receipt["access_policy_revision"] = 1
with pytest.raises(ValueError, match="без срока действия"):
client.preflight(url)
receipt.update(
session_policy_revision=1,
peer_login_expiration_enabled=False,
peer_inactivity_expiration_enabled=False,
)
assert client.preflight(url)["ready"]
for key in ("peer_login_expiration_enabled", "peer_inactivity_expiration_enabled"):
receipt[key] = True
with pytest.raises(ValueError, match="без срока действия"):
client.preflight(url)
receipt[key] = False
def test_verified_download_keeps_the_checked_descriptor(tmp_path, monkeypatch):
payload = b"verified bytes"
row = dict(
id="test",
label="Test",
filename="test.pkg",
bytes=len(payload),
sha256=hashlib.sha256(payload).hexdigest(),
)
monkeypatch.setattr(assets, "LOCK", {"items": [row]})
folder = assets.directory(tmp_path)
folder.mkdir(parents=True)
file = folder / row["filename"]
file.write_bytes(payload)
with assets.open_verified(tmp_path, "test") as (stream, _):
replacement = folder / "replacement"
replacement.write_bytes(b"unchecked bytes")
replacement.replace(file)
assert stream.read() == payload
@pytest.mark.parametrize("confirmed", [True, False])
def test_cli_exit_requires_daemon_confirmation_and_uses_scoped_flags(
tmp_path, monkeypatch, confirmed
):
import io
value = client.Client(tmp_path)
calls = []
states = iter(
[{"state": "disconnected"}, {"state": "connected" if confirmed else "disconnected"}]
)
monkeypatch.setattr(value, "status", lambda **kw: next(states, {"state": "disconnected"}))
monkeypatch.setattr(client, "preflight", lambda url: {"network": "10.204.0.0/16"})
monkeypatch.setattr(client, "VERIFY_SECONDS", 0.01)
def spawn(args, **kwargs):
calls.append(args)
return SimpleNamespace(
stdout=io.BytesIO(b"Connected\n"), poll=lambda: 0, wait=lambda **kw: 0
)
monkeypatch.setattr(client.subprocess, "Popen", spawn)
value._connect(Path("/synthetic/netbird"), "https://network.example:8443")
assert len(calls) == 1 and calls[0][:4] == [
"/synthetic/netbird",
"up",
"--profile",
client.PROFILE,
]
assert set(client.SAFE_FLAGS) <= set(calls[0])
assert "--no-browser" in calls[0]
assert not value.pending and not value.auth_url
if confirmed:
assert not value.error
else:
assert "соединение не подтверждено" in value.error
def test_cancel_wins_over_preflight_timeout(tmp_path, monkeypatch):
value = client.Client(tmp_path)
monkeypatch.setattr(value, "status", lambda **kw: {"state": "disconnected"})
def preflight(url):
value.pending = "connecting"
assert value.cancel()["pending"] == "cancelling"
raise TimeoutError("connection deadline")
monkeypatch.setattr(client, "preflight", preflight)
value._connect(Path("/synthetic/netbird"), "https://network.example:8443")
assert "отменено" in value.error
assert not value.path.exists() and not value.pending
def test_onboard_setup_key_stays_out_of_argv_and_persistent_profile(tmp_path, monkeypatch):
import io
value = client.Client(tmp_path)
secret = '00000000-1111-2222-3333-444444444444'
observed = []
states = iter([{'state': 'disconnected'}, {'state': 'connected'}])
monkeypatch.setattr(value, 'status', lambda **kw: next(states))
monkeypatch.setattr(client, 'preflight', lambda url: {'network': '10.204.0.0/16'})
monkeypatch.setenv('NB_MANAGEMENT_URL', 'https://foreign.example.org')
def spawn(argv, **kw):
observed.append((argv, kw['env']))
return SimpleNamespace(stdout=io.BytesIO(b'Connected\n'), poll=lambda: 0, wait=lambda **kw: 0)
monkeypatch.setattr(client.subprocess, 'Popen', spawn)
value._connect(Path('/synthetic/netbird'), 'https://network.example.org', secret)
assert observed[0][1]['NB_SETUP_KEY'] == secret
assert 'NB_MANAGEMENT_URL' not in observed[0][1]
assert secret not in ' '.join(observed[0][0])
assert secret not in value.path.read_text()
assert secret not in str(value._snapshot())