feat(network): verify selected uplinks, roll back failures and manage NetBird policy
This commit is contained in:
@@ -144,7 +144,14 @@ def test_client_does_not_request_dns_routes_remote_shell_or_motion():
|
||||
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_platform_native_network_monitor_policy(monkeypatch):
|
||||
for name, expected in (("Linux", "false"), ("FreeBSD", "false"),
|
||||
("Darwin", "false"), ("Windows", "true")):
|
||||
monkeypatch.setattr(client.platform, "system", lambda: name)
|
||||
assert "--network-monitor=" + expected in client.safe_flags()
|
||||
assert set(client.SAFE_FLAGS).issubset(client.safe_flags())
|
||||
|
||||
|
||||
def test_preflight_refuses_redirect_before_contacting_destination():
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import copy
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.fleet.netbird import profile_policy as policy
|
||||
|
||||
|
||||
def prepared(tmp_path, monkeypatch):
|
||||
owner = tmp_path / "owner.json"
|
||||
owner.write_text(json.dumps({"server_url": "https://network.example:8443"}))
|
||||
artifact = tmp_path / "policy.pyz"
|
||||
artifact.write_bytes(b"synthetic-package")
|
||||
monkeypatch.setattr(policy.sys, "argv", [str(artifact)])
|
||||
monkeypatch.setattr(policy.os, "geteuid", lambda: 0)
|
||||
monkeypatch.setattr(policy.platform, "system", lambda: "Darwin")
|
||||
monkeypatch.setattr(policy, "RECEIPT", tmp_path / "receipt.json")
|
||||
active = {"username": "operator", "name": "a" * 32}
|
||||
config = {
|
||||
"Name": "mission-core",
|
||||
"NetworkMonitor": True,
|
||||
"PrivateKey": "synthetic-test-key",
|
||||
"DisableDNS": True,
|
||||
}
|
||||
current = {
|
||||
"daemonVersion": "0.82.0",
|
||||
"profileName": "mission-core",
|
||||
"publicKey": "synthetic-public",
|
||||
"netbirdIp": "10.204.1.2/16",
|
||||
"management": {"url": "https://network.example:8443", "connected": True},
|
||||
"signal": {"connected": True},
|
||||
}
|
||||
monkeypatch.setattr(policy, "config", lambda: (copy.deepcopy(active), copy.deepcopy(config)))
|
||||
monkeypatch.setattr(policy, "status", lambda: copy.deepcopy(current))
|
||||
calls = []
|
||||
|
||||
def invoke(*args):
|
||||
calls.append(args)
|
||||
assert args[1:3] == ("--profile", "a" * 32) and "service" not in args
|
||||
config["NetworkMonitor"] = "--network-monitor=true" in args
|
||||
return ""
|
||||
|
||||
monkeypatch.setattr(policy, "invoke", invoke)
|
||||
return owner, config, current, calls
|
||||
|
||||
|
||||
def test_preserves_active_owner_identity_and_explicit_rollback(tmp_path, monkeypatch):
|
||||
owner, config, status, calls = prepared(tmp_path, monkeypatch)
|
||||
before = copy.deepcopy(config)
|
||||
p = policy.plan(owner)
|
||||
assert "synthetic-test-key" not in json.dumps(p)
|
||||
assert policy.apply(owner, p["plan_sha256"])["identity_preserved"]
|
||||
assert config == {**before, "NetworkMonitor": False}
|
||||
assert not policy.apply(owner, policy.plan(owner)["plan_sha256"])["changed"]
|
||||
p = policy.plan(owner, rollback=True)
|
||||
policy.apply(owner, p["plan_sha256"], rollback=True)
|
||||
assert config == before and len(calls) == 2
|
||||
|
||||
|
||||
def test_changed_profile_and_foreign_network_are_refused(tmp_path, monkeypatch):
|
||||
owner, config, status, calls = prepared(tmp_path, monkeypatch)
|
||||
p = policy.plan(owner)
|
||||
config["DisableDNS"] = False
|
||||
with pytest.raises(ValueError, match="Plan changed"):
|
||||
policy.apply(owner, p["plan_sha256"])
|
||||
assert not calls
|
||||
status["management"]["url"] = "https://foreign.example"
|
||||
with pytest.raises(ValueError, match="Owned"):
|
||||
policy.plan(owner)
|
||||
|
||||
|
||||
def test_failed_reconnection_rolls_back_only_flag(tmp_path, monkeypatch):
|
||||
owner, config, status, calls = prepared(tmp_path, monkeypatch)
|
||||
checks = []
|
||||
|
||||
def health(before):
|
||||
checks.append(True)
|
||||
if len(checks) == 1:
|
||||
raise ValueError("connection failed")
|
||||
|
||||
monkeypatch.setattr(policy, "await_health", health)
|
||||
with pytest.raises(ValueError, match="connection failed"):
|
||||
policy.apply(owner, policy.plan(owner)["plan_sha256"])
|
||||
assert config["NetworkMonitor"] is True and len(calls) == 2
|
||||
assert json.loads(policy.RECEIPT.read_text())["state"] == "rolled_back"
|
||||
|
||||
|
||||
def test_package_deterministic(tmp_path):
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
path = Path(__file__).resolve().parents[2] / "scripts/build_netbird_policy.py"
|
||||
spec = importlib.util.spec_from_file_location("policy_builder", path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
a = module.build(tmp_path / "one.pyz")
|
||||
b = module.build(tmp_path / "two.pyz")
|
||||
assert a["sha256"] == b["sha256"]
|
||||
|
||||
|
||||
def test_official_cli_runs_as_active_profile_owner(tmp_path, monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
|
||||
monkeypatch.setattr(policy, "ROOT", tmp_path)
|
||||
(tmp_path / "active_profile.json").write_text(
|
||||
json.dumps({"username": "operator", "name": "a" * 32})
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
policy.pwd,
|
||||
"getpwnam",
|
||||
lambda name: (
|
||||
SimpleNamespace(pw_uid=501, pw_gid=20, pw_dir="/Users/operator")
|
||||
if name == "operator"
|
||||
else pytest.fail("Unexpected profile owner")
|
||||
),
|
||||
)
|
||||
monkeypatch.setenv("NB_MANAGEMENT_URL", "https://foreign.invalid")
|
||||
monkeypatch.setenv("SUDO_USER", "root")
|
||||
monkeypatch.setenv("HOME", "/var/root")
|
||||
calls = []
|
||||
|
||||
def run(command, **kwargs):
|
||||
calls.append((command, kwargs))
|
||||
return SimpleNamespace(returncode=0, stdout="ready", stderr="")
|
||||
|
||||
monkeypatch.setattr(policy.subprocess, "run", run)
|
||||
assert policy.invoke("up", "--profile", "a" * 32, "--network-monitor=false") == "ready"
|
||||
command, options = calls[0]
|
||||
assert command == [
|
||||
policy.BINARY,
|
||||
"up",
|
||||
"--profile",
|
||||
"a" * 32,
|
||||
"--network-monitor=false",
|
||||
"--log-file",
|
||||
"console",
|
||||
]
|
||||
assert (options["user"], options["group"], options["extra_groups"]) == (501, 20, [])
|
||||
assert options["env"]["HOME"] == "/Users/operator"
|
||||
assert not any(k.startswith(("NB_", "SUDO_")) for k in options["env"])
|
||||
assert options["timeout"] == 45 and options["capture_output"]
|
||||
@@ -0,0 +1,60 @@
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
from fastapi import APIRouter, FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from k1link.fleet.uplinks import Uplinks
|
||||
from k1link.web.fleet_api import local_operator
|
||||
from k1link.web.fleet_uplink_api import register
|
||||
|
||||
|
||||
def test_operator_origin_schema_freshness_and_exact_target():
|
||||
row = {"node_id": "board", "enrollment": "paired", "binding": {"binding_id": "pair"}}
|
||||
owner = Uplinks()
|
||||
ids = ["a" * 36, "b" * 36]
|
||||
owner.heartbeat(
|
||||
row,
|
||||
{
|
||||
"execution_binding": {"agent_instance_id": "runtime"},
|
||||
"uplink": {
|
||||
"supported": True,
|
||||
"protocol": 2,
|
||||
"current_id": ids[0],
|
||||
"revision": "c" * 64,
|
||||
"candidates": [
|
||||
{
|
||||
"id": x,
|
||||
"interface": "port" + str(i),
|
||||
"kind": "ethernet",
|
||||
"label": "test",
|
||||
"verified": True,
|
||||
}
|
||||
for i, x in enumerate(ids)
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
app, router = FastAPI(), APIRouter(prefix="/api/v1/fleet")
|
||||
register(router, local_operator)
|
||||
app.include_router(router)
|
||||
app.state.fleet = SimpleNamespace(
|
||||
lock=threading.RLock(),
|
||||
find=lambda _: row,
|
||||
uplinks=owner,
|
||||
network_profiles=SimpleNamespace(view=lambda _: {}),
|
||||
)
|
||||
body = dict(target=ids[1], revision="c" * 64, runtime="runtime", operation_id="d" * 32)
|
||||
path = "/api/v1/fleet/test/uplink"
|
||||
with TestClient(app, base_url="http://127.0.0.1", client=("127.0.0.1", 32123)) as client:
|
||||
assert (
|
||||
client.post(path, json=body, headers={"Origin": "https://other.invalid"}).status_code
|
||||
== 403
|
||||
)
|
||||
assert not owner.operations
|
||||
assert client.post(path, json=body | {"shell": "x"}).status_code == 422
|
||||
assert client.post(path, json=body | {"runtime": "old"}).status_code == 409
|
||||
assert client.get(path).headers["cache-control"] == "no-store"
|
||||
assert client.post(path, json=body).json()["phase"] == "queued"
|
||||
assert client.post(path, json=body).json()["id"] == body["operation_id"]
|
||||
assert owner.operations["board"]["target"] == ids[1]
|
||||
@@ -0,0 +1,78 @@
|
||||
import copy
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.fleet.uplinks import Uplinks
|
||||
from tests.test_board_uplinks import PAYLOAD, ROW
|
||||
|
||||
|
||||
def setup():
|
||||
clock=[1000]
|
||||
u=Uplinks(lambda:clock[0])
|
||||
p=copy.deepcopy(PAYLOAD)
|
||||
p['uplink']['fallback']={'enabled':True,'revision':0,'operation_id':''}
|
||||
u.heartbeat(ROW,p)
|
||||
command=dict(enabled=False,revision=0,runtime='runtime',operation_id='e'*32)
|
||||
return u,p,clock,command
|
||||
|
||||
|
||||
def test_setting_is_not_optimistically_applied_and_receipt_survives_core_restart():
|
||||
u,p,clock,command=setup()
|
||||
assert u.set_fallback(ROW,command)['phase']=='queued'
|
||||
assert u.view(ROW)['fallback']['enabled'] is True
|
||||
sent=u.heartbeat(ROW,p)['uplink_change']
|
||||
assert sent['kind']=='fallback' and sent['enabled'] is False
|
||||
p['uplink']['fallback']={'enabled':False,'revision':1,'operation_id':command['operation_id']}
|
||||
assert not u.heartbeat(ROW,p)
|
||||
assert u.view(ROW)['fallback_operation']['phase']=='applied'
|
||||
new=Uplinks(lambda:clock[0])
|
||||
new.heartbeat(ROW,p)
|
||||
assert new.view(ROW)['fallback']['enabled'] is False
|
||||
|
||||
|
||||
def test_timeout_or_old_node_never_pretends_setting_saved():
|
||||
u,p,clock,command=setup()
|
||||
u.set_fallback(ROW,command)
|
||||
clock[0]+=31
|
||||
assert not u.heartbeat(ROW,p)
|
||||
assert u.view(ROW)['fallback_operation']['phase']=='failed'
|
||||
p['uplink'].pop('fallback')
|
||||
u.heartbeat(ROW,p)
|
||||
with pytest.raises(ValueError):
|
||||
u.set_fallback(ROW,{**command,'operation_id':'f'*32})
|
||||
|
||||
|
||||
def test_new_runtime_receives_no_stale_policy_command():
|
||||
u,p,clock,command=setup()
|
||||
u.set_fallback(ROW,command)
|
||||
p['execution_binding']['agent_instance_id']='new'
|
||||
assert not u.heartbeat(ROW,p)
|
||||
assert u.view(ROW)['fallback_operation']['phase']=='failed'
|
||||
|
||||
|
||||
|
||||
def test_api_preserves_explicit_false_and_rejects_foreign_origin_and_bad_revision():
|
||||
import threading
|
||||
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_uplink_api import register
|
||||
|
||||
u, p, clock, command = setup()
|
||||
app, router = FastAPI(), APIRouter(prefix='/api/v1/fleet')
|
||||
register(router, local_operator)
|
||||
app.include_router(router)
|
||||
app.state.fleet = SimpleNamespace(lock=threading.RLock(), find=lambda _:ROW,
|
||||
uplinks=u, network_profiles=SimpleNamespace(view=lambda _:{}))
|
||||
with TestClient(app, base_url='http://127.0.0.1', client=('127.0.0.1', 12345)) as client:
|
||||
path='/api/v1/fleet/test/uplink/fallback'
|
||||
rejected = client.patch(path, json=command,
|
||||
headers={'Origin':'https://other.invalid'})
|
||||
assert rejected.status_code == 403
|
||||
assert client.patch(path, json={**command, 'enabled':'false'}).status_code == 422
|
||||
assert client.patch(path, json={**command, 'revision':False}).status_code == 422
|
||||
assert client.patch(path, json=command).json()['phase'] == 'queued'
|
||||
assert u.heartbeat(ROW,p)['uplink_change']['enabled'] is False
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Commands must be admitted by live, bound Node evidence, not remembered inventory."""
|
||||
|
||||
import copy
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.fleet.uplinks import Uplinks
|
||||
|
||||
A, B, REV, OP = "a" * 36, "b" * 36, "c" * 64, "d" * 32
|
||||
ROW = {"node_id": "board", "enrollment": "paired", "binding": {"binding_id": "pair"}}
|
||||
PAYLOAD = {
|
||||
"execution_binding": {"agent_instance_id": "runtime"},
|
||||
"uplink": {
|
||||
"supported": True,
|
||||
"protocol": 2,
|
||||
"path_verified": True,
|
||||
"revision": REV,
|
||||
"current_id": A,
|
||||
"candidates": [
|
||||
{"id": A, "label": "radio", "interface": "radio7", "kind": "wifi", "verified": True},
|
||||
{"id": B, "label": "cable", "interface": "port8", "kind": "ethernet", "verified": True},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def owner():
|
||||
now = [1000]
|
||||
owner = Uplinks(lambda: now[0])
|
||||
owner.heartbeat(ROW, PAYLOAD)
|
||||
return owner, now
|
||||
|
||||
|
||||
def start(u):
|
||||
return u.start(ROW, B, REV, "runtime", OP)
|
||||
|
||||
|
||||
def test_fresh_authority_duplicate_and_ack(owner):
|
||||
u, _ = owner
|
||||
assert start(u)["phase"] == "queued"
|
||||
assert start(u)["id"] == OP
|
||||
assert u.heartbeat(ROW, PAYLOAD)["uplink_change"]["target"] == B
|
||||
p = copy.deepcopy(PAYLOAD)
|
||||
p["uplink"]["operation"] = dict(
|
||||
id=OP,
|
||||
binding="pair:runtime",
|
||||
target=B,
|
||||
phase="verifying",
|
||||
nonce="f" * 32,
|
||||
path_verified=True,
|
||||
)
|
||||
assert u.heartbeat(ROW, p)["uplink_ack"]["id"] == OP
|
||||
p["uplink"]["operation"]["phase"] = "applied"
|
||||
assert u.heartbeat(ROW, p) == {}
|
||||
assert u.view(ROW)["operation"]["phase"] == "applied"
|
||||
|
||||
|
||||
def test_old_missing_and_stale_telemetry_has_no_authority(owner):
|
||||
u, now = owner
|
||||
now[0] += 21
|
||||
assert not u.view(ROW)["available"]
|
||||
with pytest.raises(ValueError):
|
||||
start(u)
|
||||
assert u.heartbeat(ROW, {"execution_binding": {"agent_instance_id": "runtime"}}) == {}
|
||||
assert u.view(ROW)["candidates"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["runtime", "binding", "unverified", "unsupported"])
|
||||
def test_changed_scope_and_failed_checks_reject_command(owner, kind):
|
||||
u, _ = owner
|
||||
p, row = copy.deepcopy(PAYLOAD), copy.deepcopy(ROW)
|
||||
if kind == "runtime":
|
||||
p["execution_binding"]["agent_instance_id"] = "new-runtime"
|
||||
elif kind == "binding":
|
||||
row["binding"]["binding_id"] = "new-pair"
|
||||
elif kind == "unverified":
|
||||
p["uplink"]["candidates"][1]["verified"] = False
|
||||
else:
|
||||
p["uplink"]["supported"] = False
|
||||
u.heartbeat(row, p)
|
||||
with pytest.raises(ValueError):
|
||||
start(u)
|
||||
|
||||
|
||||
def test_restarted_node_never_replays_or_receives_old_ack(owner):
|
||||
u, _ = owner
|
||||
start(u)
|
||||
p = copy.deepcopy(PAYLOAD)
|
||||
p["execution_binding"]["agent_instance_id"] = "new-runtime"
|
||||
assert not u.heartbeat(ROW, p)
|
||||
assert u.view(ROW)["operation"]["phase"] == "unknown"
|
||||
|
||||
|
||||
def test_timeout_is_unknown_not_false_rollback_success(owner):
|
||||
u, now = owner
|
||||
start(u)
|
||||
now[0] += 31
|
||||
assert not u.heartbeat(ROW, PAYLOAD)
|
||||
assert u.view(ROW)["operation"]["phase"] == "unknown"
|
||||
|
||||
|
||||
def test_invalid_payload_does_not_interrupt_other_heartbeat_work(owner):
|
||||
u, _ = owner
|
||||
p = copy.deepcopy(PAYLOAD)
|
||||
p["uplink"]["candidates"] *= 20
|
||||
assert u.heartbeat(ROW, p) == {}
|
||||
assert not u.view(ROW)["available"]
|
||||
|
||||
|
||||
def test_motion_guard_blocks_admission_and_is_released_after_rollback():
|
||||
from k1link.fleet.rover_control import RoverControl
|
||||
|
||||
control = RoverControl()
|
||||
u = Uplinks(lambda: 1000, guard=control.network_change)
|
||||
u.heartbeat(ROW, PAYLOAD)
|
||||
start(u)
|
||||
with pytest.raises(ValueError, match="переключения"):
|
||||
control.arm("board", {"standstill_confirmed": True, "current_a": 20, "max_erpm": 500})
|
||||
p = copy.deepcopy(PAYLOAD)
|
||||
p["uplink"]["operation"] = dict(id=OP, binding="pair:runtime", target=B, phase="rolled_back")
|
||||
u.heartbeat(ROW, p)
|
||||
assert "board" not in control.network_changes
|
||||
|
||||
|
||||
def test_unproved_vpn_path_cannot_receive_commit_ack(owner):
|
||||
u, _ = owner
|
||||
start(u)
|
||||
p = copy.deepcopy(PAYLOAD)
|
||||
p["uplink"]["operation"] = dict(
|
||||
id=OP,
|
||||
binding="pair:runtime",
|
||||
target=B,
|
||||
phase="verifying",
|
||||
nonce="f" * 32,
|
||||
path_verified=False,
|
||||
)
|
||||
assert "uplink_ack" not in u.heartbeat(ROW, p)
|
||||
|
||||
|
||||
def test_old_metric_only_node_cannot_admit_selection(owner):
|
||||
u, _ = owner
|
||||
p = copy.deepcopy(PAYLOAD)
|
||||
p["uplink"].pop("protocol")
|
||||
u.heartbeat(ROW, p)
|
||||
assert not u.view(ROW)["available"]
|
||||
Reference in New Issue
Block a user