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())
+80
View File
@@ -0,0 +1,80 @@
import hashlib
import json
import zipfile
from types import SimpleNamespace
import pytest
from fastapi import APIRouter, FastAPI
from fastapi.testclient import TestClient
from k1link.fleet.netbird import backups
from k1link.web.netbird_backup_api import register
def archive(path, *, extra=None):
files = {name: b"synthetic-private-state" for name in backups.REQUIRED}
if extra:
files.update(extra)
manifest = {
"schema": "missioncore.netbird-transfer/v1",
"domain": "network.example",
"management_url": "https://network.example:8443",
"identity_sha256": "a" * 64,
"files": {
name: {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()}
for name, data in files.items()
},
}
with zipfile.ZipFile(path, "w") as output:
output.writestr("manifest.json", json.dumps(manifest))
for name, data in files.items():
output.writestr(name, data)
path.chmod(0o600)
return path
def test_private_backup_import_deduplicates_and_export_checks_integrity(tmp_path):
root = tmp_path / "fleet"
source = archive(tmp_path / "input.zip")
original = source.read_bytes()
row = backups.admit(root, source)
assert not source.exists()
assert "synthetic-private-state" not in json.dumps(row)
saved = backups.download(root, row["id"])
assert saved.read_bytes() == original
assert saved.stat().st_mode & 0o077 == 0
source.write_bytes(original)
assert backups.admit(root, source) == row
assert len(backups.catalog(root)["items"]) == 1
saved.write_bytes(b"x" * len(original))
with pytest.raises(zipfile.BadZipFile):
backups.download(root, row["id"])
def test_invalid_archive_cannot_write_paths_or_replace_previous_backup(tmp_path):
root = tmp_path / "fleet"
safe = backups.admit(root, archive(tmp_path / "safe.zip"))
unsafe = archive(tmp_path / "unsafe.zip", extra={"../../outside": b"no"})
with pytest.raises(ValueError):
backups.admit(root, unsafe)
assert not (tmp_path / "outside").exists()
assert backups.catalog(root)["items"] == [safe]
def test_api_import_export_is_binary_and_does_not_return_secrets(tmp_path):
app = FastAPI()
router = APIRouter()
register(router, lambda: SimpleNamespace(root=tmp_path / "fleet"))
app.include_router(router)
raw = archive(tmp_path / "source.zip").read_bytes()
with TestClient(app) as client:
response = client.post("/netbird/backups", content=raw)
assert response.status_code == 200
row = response.json()
assert "synthetic-private-state" not in response.text
assert client.get("/netbird/backups").json()["items"] == [row]
downloaded = client.get(f"/netbird/backups/{row['id']}/download")
assert downloaded.content == raw
assert downloaded.headers["cache-control"] == "no-store"
assert client.post("/netbird/backups", content=b"not an archive").status_code == 409
assert not list((tmp_path / "fleet/networks/netbird-backups").glob(".upload-*"))
+63
View File
@@ -0,0 +1,63 @@
"""Package preparation admission uses synthetic OS/dpkg state; no host mutation."""
import hashlib
import importlib.util
import json
from pathlib import Path
from types import SimpleNamespace
import pytest
@pytest.fixture
def installer(tmp_path, monkeypatch):
source = Path(__file__).parents[2] / 'apps/node-agent/packaging/netbird_install.py'
spec = importlib.util.spec_from_file_location('node_netbird_install', source)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
system = tmp_path / 'os-release'
system.write_text('ID=ubuntu\nVERSION_ID="24.04"\n')
monkeypatch.setattr(module, 'Path', lambda name: system if name == '/etc/os-release' else Path(name))
monkeypatch.setattr(module.os, 'uname', lambda: SimpleNamespace(machine='x86_64'))
module.ROOT = tmp_path
payload = b'synthetic pinned Debian payload'
(tmp_path / 'netbird.deb').write_bytes(payload)
lock = {'version': '0.82.0', 'items': [{'id': 'linux-amd64', 'filename': 'netbird.deb', 'bytes': len(payload), 'sha256': hashlib.sha256(payload).hexdigest()}]}
(tmp_path / 'clients.lock.json').write_text(json.dumps(lock))
return module
def test_existing_other_version_is_preserved(installer, monkeypatch):
calls = []
def run(argv, **kwargs):
calls.append(argv)
return SimpleNamespace(returncode=0, stdout='0.99.0')
monkeypatch.setattr(installer.subprocess, 'run', run)
with pytest.raises(ValueError, match='другая версия'):
installer.install()
assert len(calls) == 1 and calls[0][0] == '/usr/bin/dpkg-query'
def test_corrupted_payload_never_reaches_package_manager(installer, monkeypatch):
(installer.ROOT / 'netbird.deb').write_bytes(b'corrupt')
monkeypatch.setattr(installer.subprocess, 'run', lambda *a, **kw: pytest.fail('OS mutation'))
with pytest.raises(ValueError, match='повреждён'):
installer.install()
def test_first_install_and_repeat_preserve_credentials(installer, monkeypatch):
calls = []
installed = False
def run(argv, **kwargs):
nonlocal installed
calls.append(argv)
if argv[0] == '/usr/bin/dpkg-query':
return SimpleNamespace(returncode=0 if installed else 1, stdout='0.82.0\tinstalled' if installed else '')
if argv[0] == '/usr/bin/apt-get':
installed = True
return SimpleNamespace(returncode=0, stdout='')
monkeypatch.setattr(installer.subprocess, 'run', run)
installer.install()
installer.install()
assert sum(c[0] == '/usr/bin/apt-get' for c in calls) == 1
assert all('up' not in c and 'down' not in c and 'login' not in c for c in calls)
assert any('--no-remove' in c for c in calls)
+35
View File
@@ -0,0 +1,35 @@
"""Exercise the operator HTTP contract, including the third network provider."""
from types import SimpleNamespace
from fastapi import APIRouter, FastAPI
from fastapi.testclient import TestClient
from k1link.web.fleet_api import local_operator
from k1link.web.fleet_network_api import register
def test_netbird_selection_reaches_admission_without_weakening_http_boundary():
calls = []
def start(*args):
calls.append(args)
raise ValueError("Отключите управление перед изменением сети борта.")
app = FastAPI()
router = APIRouter(prefix="/api/v1/fleet")
register(router, local_operator)
app.include_router(router)
app.state.fleet = SimpleNamespace(network_profiles=SimpleNamespace(start=start))
body = {"provider": "netbird", "profile_id": None, "expected_revision": 5}
with TestClient(app, base_url="http://127.0.0.1", client=("127.0.0.1", 32123)) as web:
path = "/api/v1/fleet/board/network-profile"
denied = web.put(path, json=body, headers={"Origin": "https://unrelated.example"})
assert denied.status_code == 403 and not calls
response = web.put(path, json=body)
assert response.status_code == 409
assert "Отключите управление" in response.json()["detail"]
assert calls == [("board", "netbird", None, 5)]
assert web.put(path, json=body | {"provider": "unknown"}).status_code == 422
assert web.put(path, json=body | {"expected_revision": "5"}).status_code == 422
assert len(calls) == 1
@@ -0,0 +1,43 @@
"""A phase reported over the previous route cannot confirm the candidate route."""
import threading
from types import SimpleNamespace
import pytest
from k1link.fleet.network_profiles import NetworkProfiles
@pytest.mark.parametrize("phase", ["verifying", "applied"])
def test_wait_requires_phase_and_candidate_endpoint(tmp_path, monkeypatch, phase):
fleet = SimpleNamespace(root=tmp_path, trust=SimpleNamespace(core_id="core_test"),
stop=threading.Event())
profiles = NetworkProfiles(fleet)
target = "https://10.203.45.2:8782"
profiles.latest["node"] = {"endpoint": "https://100.64.2.3:8782",
"value": {"operation_id": "op", "phase": phase}}
waits = []
def receive_candidate(*, timeout):
waits.append(timeout)
profiles.latest["node"] = {"endpoint": target,
"value": {"operation_id": "op", "phase": phase}}
monkeypatch.setattr(profiles.changed, "wait", receive_candidate)
accepted = profiles.wait("node", "op", phase, endpoint=target)
assert len(waits) == 1
assert accepted["endpoint"] == target
def test_wrong_route_never_confirms_and_rollback_remains_terminal(tmp_path, monkeypatch):
fleet = SimpleNamespace(root=tmp_path, trust=SimpleNamespace(core_id="core_test"),
stop=threading.Event())
profiles = NetworkProfiles(fleet)
profiles.latest["node"] = {"endpoint": "https://100.64.2.3:8782",
"value": {"operation_id": "op", "phase": "verifying"}}
def receive_rollback(*, timeout):
profiles.latest["node"]["value"].update(phase="rolled_back", error="rolled back")
monkeypatch.setattr(profiles.changed, "wait", receive_rollback)
with pytest.raises(ValueError, match="rolled back"):
profiles.wait("node", "op", "verifying", endpoint="https://10.203.45.2:8782")
+63
View File
@@ -146,3 +146,66 @@ def test_core_accepts_more_than_fifty_routes(monkeypatch):
config['role']='node';config['address']='10.203.45.83'
with pytest.raises(ValueError, match='only its Core'):
module.validate(config)
def test_failed_reimport_preserves_new_revocation_and_other_profile_changes(tmp_path, monkeypatch):
import copy
fleet = SimpleNamespace(root=tmp_path, trust=SimpleNamespace(core_id='core_test'))
profiles = NetworkProfiles(fleet)
row = {**document(), 'name': 'Fleet', 'state': 'ready',
'status': {'peers': [{'id': 'node_1', 'kind': 'node'}]}}
identity = row['server_id']
other = 'wg_' + '2' * 32
profiles.profiles[identity] = copy.deepcopy(row)
profiles.profiles[other] = {**row, 'server_id': other, 'name': 'Before'}
def fail(*args):
profiles.profiles[other]['name'] = 'Concurrent change'
profiles.revoke_node('node_1')
profiles.profiles[identity]['endpoint'] = 'https://failed.example:19444'
raise ValueError('retry')
monkeypatch.setattr(profiles, '_import_file', fail)
with pytest.raises(ValueError, match='retry'):
profiles.import_file(json.dumps(document()))
assert profiles.profiles[identity]['endpoint'] == row['endpoint']
assert profiles.profiles[identity]['revocations'] == ['node_1']
assert profiles.profiles[other]['name'] == 'Concurrent change'
def test_netbird_offer_requires_same_server_and_narrow_exact_peers(tmp_path):
operator = dict(state='connected', server_url='https://network.example.org', network='10.204.0.0/16', address='10.204.1.2')
listened, saved = [], []
fleet = SimpleNamespace(root=tmp_path, trust=SimpleNamespace(core_id='core_test'),
netbird=SimpleNamespace(observation=lambda: operator.copy()),
listen=listened.append, save=lambda row: saved.append(row.copy()))
manager = NetworkProfiles(fleet)
row = {'node_id': 'board'}
board = {**operator, 'address': '10.204.1.3'}
assert manager.netbird_offer(row, {'netbird': {**board, 'server_url': 'https://other.example.org'}}) is None
assert manager.netbird_offer(row, {'netbird': {**board, 'state': 'unavailable'}}) is None
assert not listened and not saved
offer = manager.netbird_offer(row, {'netbird': board})
assert offer['config']['allowed_ips'] == ['10.204.1.2/32']
assert row['network_paths'] == {'netbird': {'core': '10.204.1.2', 'node': '10.204.1.3'}}
manager.netbird_offer(row, {'netbird': board})
assert len(saved) == 1
def test_local_netbird_request_uses_control_guard_and_is_not_replayed(tmp_path, monkeypatch):
fleet = SimpleNamespace(root=tmp_path, trust=SimpleNamespace(core_id='core_test'))
manager = NetworkProfiles(fleet)
row = {'id': 'vehicle', 'node_id': 'board'}
calls = []
def start(*args):
calls.append(args)
raise ValueError('Отключите управление перед изменением сети борта.')
monkeypatch.setattr(manager, 'start', start)
request = {'id': '1'*32, 'provider': 'netbird', 'revision': 3, 'expires_at': int(time.time()) + 100}
heartbeat = {'network_profile': {'provider': 'tailscale', 'phase': 'applied', 'revision': 3, 'local_request': request}}
first = manager.heartbeat(row, heartbeat)
second = manager.heartbeat(row, heartbeat)
assert first == second and 'Отключите управление' in first['network_request_result']['error']
assert calls == [('vehicle', 'netbird', 'netbird', 3)]
request['id'] = '2'*32
request['expires_at'] = int(time.time()) - 1
assert not manager.heartbeat(row, heartbeat)
assert len(calls) == 1
+132
View File
@@ -0,0 +1,132 @@
"""Recovery of local listeners must not choose a different board provider."""
import copy
import threading
from types import SimpleNamespace
import pytest
from k1link.fleet import recovery
from k1link.fleet.registry import FleetRegistry
def saved_board():
return {
"id": "vehicle", "enrollment": "paired", "core_address": "10.204.1.2",
"network_active": "netbird",
"network_paths": {
"netbird": {"core": "10.204.1.2", "node": "10.204.1.3"},
"wg_previous": {"core": "10.203.7.2", "node": "10.203.7.3"},
},
"binding": {"binding_id": "unchanged", "endpoint": "https://10.204.1.2:8782"},
"inventory": {"networks": [
{"up": True, "addresses": ["192.168.3.4/24", "100.64.20.4/32"]},
{"up": False, "addresses": ["100.64.21.4/32"]},
]},
}
def routing(monkeypatch, source):
calls = []
class Route:
def __enter__(self):
return self
def __exit__(self, *args):
pass
def connect(self, destination):
calls.append(destination)
if isinstance(source, Exception):
raise source
def getsockname(self):
return source, 30000
def send(self, *args):
pytest.fail("Listener recovery must not send packets")
def socket(family, kind):
assert family == recovery.socket.AF_INET
assert kind == recovery.socket.SOCK_DGRAM
return Route()
monkeypatch.setattr(recovery.socket, "socket", socket)
return calls
def test_restart_restores_return_listener_without_selecting_tailscale(monkeypatch):
calls = routing(monkeypatch, "100.64.20.5")
row = saved_board()
before = copy.deepcopy(row)
assert recovery.listener_addresses(row) == ["10.203.7.2", "10.204.1.2", "100.64.20.5"]
assert calls == [("100.64.20.4", 8781)]
assert recovery.node_addresses(row) == ["10.204.1.3"]
assert row == before
@pytest.mark.parametrize("source", ["192.168.3.5", "10.204.1.2", OSError("No route")])
def test_missing_tailnet_does_not_open_underlay_or_other_vpn_listener(monkeypatch, source):
routing(monkeypatch, source)
assert recovery.listener_addresses(saved_board()) == ["10.203.7.2", "10.204.1.2"]
def test_listener_uses_current_route_instead_of_a_cached_host_address(monkeypatch):
routing(monkeypatch, "100.64.20.9")
assert "100.64.20.9" in recovery.listener_addresses(saved_board())
row = saved_board()
row["inventory"] = {}
assert recovery.listener_addresses(row) == ["10.203.7.2", "10.204.1.2"]
def test_reconcile_retries_alternative_listener_after_address_returns(monkeypatch):
routing(monkeypatch, "100.64.20.5")
stop = threading.Event()
row = saved_board()
revoked = {**saved_board(), "id": "revoked", "enrollment": "revoked",
"core_address": "10.203.8.2"}
fleet = SimpleNamespace(
stop=stop, lock=threading.RLock(), routers=SimpleNamespace(prune=lambda: None),
network_profiles=SimpleNamespace(reconcile=lambda: None),
rows=lambda: [row, revoked], listeners={}, previews={},
)
attempts = []
def listen(address):
attempts.append(address)
if address == "100.64.20.5" and attempts.count(address) == 1:
raise OSError("Interface not ready")
fleet.listeners[address] = SimpleNamespace(refresh_at=float("inf"))
fleet.listen = listen
ticks = []
def wait(_):
ticks.append(1)
if len(ticks) == 2:
stop.set()
monkeypatch.setattr(stop, "wait", wait)
FleetRegistry.reconcile(fleet)
assert attempts.count("100.64.20.5") == 2
assert "100.64.20.5" in fleet.listeners
assert "10.203.7.2" in fleet.listeners
assert "10.203.8.2" not in fleet.listeners
assert row["network_active"] == "netbird"
def test_start_keeps_fallback_listener_when_primary_vps_is_absent(monkeypatch):
routing(monkeypatch, "100.64.20.5")
monkeypatch.setattr(threading, "Thread", lambda **kw: SimpleNamespace(start=lambda: None))
attempts = []
def listen(address):
attempts.append(address)
if address == "10.204.1.2":
raise OSError("Primary address absent")
fleet = SimpleNamespace(lock=threading.RLock(), rows=lambda: [saved_board()],
network_profiles=SimpleNamespace(profiles={}), listen=listen,
reconcile=lambda: None)
FleetRegistry.start(fleet)
assert set(attempts) == {"10.204.1.2", "10.203.7.2", "100.64.20.5"}