feat(network): measure Core and onboard links against registered LibreSpeed servers

This commit is contained in:
DCCONSTRUCTIONS
2026-11-21 20:58:24 +03:00
parent 22f262ca59
commit 1635299252
17 changed files with 1027 additions and 10 deletions
+114
View File
@@ -0,0 +1,114 @@
import hashlib
import socket
import ssl
import threading
import time
from contextlib import contextmanager
from unittest.mock import Mock
import pytest
from k1link.network.speed_measure import transfer
from k1link.network.speed_transport import SpeedTransport, Stopped
def test_wrong_tls_pin_never_sends_http_credentials(monkeypatch):
grant = dict(
endpoint="https://example.com:19445",
address="93.184.215.14",
fingerprint="f" * 64,
token="private-lease",
)
sock = Mock(spec=socket.socket)
secure = Mock(spec=ssl.SSLSocket)
secure.getpeercert = Mock(return_value=b"certificate")
context = Mock()
context.wrap_socket.return_value = secure
monkeypatch.setattr("k1link.network.speed_transport.socket.socket", lambda *args: sock)
client = SpeedTransport(grant)
client.context = context
request = Mock()
monkeypatch.setattr("http.client.HTTPConnection.request", request)
with pytest.raises(ValueError, match="certificate_rejected"), client.response("ping"):
pass
request.assert_not_called()
sock.bind.assert_not_called()
sock.setsockopt.assert_not_called()
sock.connect.assert_called_once_with(("93.184.215.14", 19445))
assert not client.sockets
grant["fingerprint"] = hashlib.sha256(b"certificate").hexdigest()
response = Mock(status=200)
monkeypatch.setattr("http.client.HTTPConnection.getresponse", lambda _: response)
with client.response("ping"):
pass
assert request.call_args.args[3]["Authorization"] == "Bearer private-lease"
client.stop()
with pytest.raises(Stopped), client.response("ping"):
pass
class FakeTransport:
def __init__(self, bad=False):
self.stopped = threading.Event()
self.bad = bad
self.active = 0
self.peak = 0
self.uploaded = 0
self.downloaded = 0
def check(self):
if self.stopped.is_set():
raise Stopped()
def close_streams(self):
pass
@contextmanager
def response(self, path, body, end):
if self.bad:
raise OSError("broken")
self.active += 1
self.peak = max(self.active, self.peak)
size = len(body) if body is not None else 1024
read = False
def receive(_):
nonlocal read
time.sleep(0.005)
if read or path == "upload":
if not read:
self.uploaded += size
read = True
return b""
read = True
self.downloaded += size
return b"x" * size
try:
yield Mock(read=receive)
finally:
self.active -= 1
def test_transfer_uses_measured_bytes_has_three_streams_and_joins():
for upload in (False, True):
client = FakeTransport()
speed = transfer(client, upload, lambda _: None, duration=0.1)
assert speed > 0 and client.peak == 3 and client.active == 0
assert (client.uploaded if upload else client.downloaded) > 0
client = FakeTransport(bad=True)
with pytest.raises(ValueError, match="transfer_failed"):
transfer(client, False, lambda _: None, duration=0.1)
assert client.active == 0
def test_cancel_interrupts_and_joins_all_streams():
client = FakeTransport()
timer = threading.Timer(0.05, client.stopped.set)
timer.start()
try:
with pytest.raises(Stopped):
transfer(client, False, lambda _: None, duration=2)
assert client.active == 0
finally:
timer.join()
+192
View File
@@ -0,0 +1,192 @@
import json
import threading
import time
from types import SimpleNamespace
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from k1link.fleet.librespeed import LibreSpeed
from k1link.network.speedtest import CoreSpeedtest
from k1link.web.network_speedtest_api import router
SERVER = "ls_" + "a" * 32
OP = "op_" + "b" * 32
@pytest.fixture
def service(tmp_path, monkeypatch):
store = LibreSpeed(tmp_path)
store.save(
dict(
id=SERVER,
state="connected",
endpoint="https://example.com:19445",
fingerprint="c" * 64,
token="private-controller",
network_interface="en0",
)
)
calls = []
def request(row, method, path, body):
calls.append((path, row.get("network_interface")))
return dict(operation_id=body["operation_id"], token="t" * 43, expires_at=time.time() + 90)
monkeypatch.setattr("k1link.fleet.vps_transport.request", request)
monkeypatch.setattr(
"k1link.fleet.vps_transport.destination", lambda _: ("example.com", 19445, "93.184.215.14")
)
return calls
def finish(worker):
worker.worker.join(3)
assert not worker.worker.is_alive()
return worker.snapshot()["receipt"]
def test_completed_test_has_real_values_redacts_secrets_and_expires(tmp_path, monkeypatch, service):
def measure(client, report):
report(dict(phase="download", sampled_at=100, current_bps=80))
assert client.grant["token"] == "t" * 43
return dict(download_bps=123, upload_bps=45, latency_ms=3, jitter_ms=1)
monkeypatch.setattr("k1link.network.speedtest.measure", measure)
worker = CoreSpeedtest(tmp_path)
try:
worker.start(OP, SERVER, "Example")
receipt = finish(worker)
assert receipt["measurement"]["download_bps"] == 123
assert receipt["measurement"]["phase"] == "complete"
assert receipt["server_name"] == "Example"
assert "token" not in json.dumps(receipt) and "private-controller" not in json.dumps(
receipt
)
assert service == [("/v1/tests", None), ("/v1/tests/cancel", None)]
assert LibreSpeed(tmp_path).find(SERVER)["network_interface"] == "en0"
worker.start(OP, SERVER, "Renamed") # Lost-reply retry must not rerun.
assert len(service) == 2
worker.receipts[OP]["expires_at"] = 0
worker.expire()
assert worker.snapshot() == {"receipt": None}
finally:
worker.close()
def test_cancel_closes_streams_before_lease_release_and_refuses_concurrent_start(
tmp_path, monkeypatch, service
):
entered = threading.Event()
stopped = threading.Event()
def measure(client, report):
entered.set()
client.stopped.wait(3)
stopped.set()
client.check()
monkeypatch.setattr("k1link.network.speedtest.measure", measure)
worker = CoreSpeedtest(tmp_path)
try:
worker.start(OP, SERVER, "Example")
assert entered.wait(2)
with pytest.raises(ValueError):
worker.start("op_" + "d" * 32, SERVER, "Example")
with pytest.raises(ValueError):
worker.start(OP, "ls_" + "e" * 32, "Other")
assert worker.cancel(OP)["state"] == "cancelling"
assert stopped.wait(1)
assert finish(worker)["measurement"]["phase"] == "cancelled"
assert service[-1][0] == "/v1/tests/cancel"
worker.cancel(OP) # Terminal cancellation is idempotent.
finally:
worker.close()
def test_lost_lease_reply_is_released_and_does_not_fabricate_a_result(
tmp_path, monkeypatch, service
):
monkeypatch.setattr(
LibreSpeed, "lease", lambda *a, **kw: (_ for _ in ()).throw(OSError("secret"))
)
worker = CoreSpeedtest(tmp_path)
try:
worker.start(OP, SERVER, "Example")
receipt = finish(worker)
assert receipt["state"] == "error"
assert "secret" not in json.dumps(receipt)
assert service == [("/v1/tests/cancel", None)]
finally:
worker.close()
def test_api_is_operator_only_rejects_urls_and_uses_catalog_identity(
tmp_path, monkeypatch, service
):
app = FastAPI()
app.state.fleet = SimpleNamespace(root=tmp_path)
app.include_router(router)
public = dict(
kind="librespeed", id=SERVER, endpoint="https://example.com:19445", state="connected"
)
monkeypatch.setattr("k1link.web.network_speedtest_api.services", lambda _: [public])
monkeypatch.setattr(
"k1link.network.speedtest.measure", lambda *args: dict(download_bps=10, upload_bps=20)
)
with TestClient(app, base_url="http://127.0.0.1:8000", client=("127.0.0.1", 1234)) as client:
path = "/api/v1/system/network/speedtest"
try:
assert client.get(path, headers={"Origin": "https://evil.example"}).status_code == 403
assert (
client.post(
path, json=dict(operation_id=OP, server_id=SERVER, endpoint="http://127.0.0.1")
).status_code
== 422
)
assert (
client.post(
path, json=dict(operation_id=OP, server_id="ls_" + "f" * 32)
).status_code
== 409
)
response = client.post(path, json=dict(operation_id=OP, server_id=SERVER))
assert response.status_code == 200
assert response.json()["server_name"] == "example.com"
finish(app.state.core_speedtest)
result = client.get(path)
assert result.headers["cache-control"] == "no-store"
assert result.json()["receipt"]["measurement"]["phase"] == "complete"
finally:
if getattr(app.state, "core_speedtest", None):
app.state.core_speedtest.close()
def test_server_lease_deadline_interrupts_executor(tmp_path, monkeypatch, service):
monkeypatch.setattr(
LibreSpeed,
"lease",
lambda *a, **kw: dict(
endpoint="https://example.com:19445",
address="93.184.215.14",
fingerprint="c" * 64,
token="t" * 43,
expires_at=time.time() + 0.1,
),
)
def measure(client, report):
client.stopped.wait(2)
client.check()
monkeypatch.setattr("k1link.network.speedtest.measure", measure)
worker = CoreSpeedtest(tmp_path)
try:
worker.start(OP, SERVER, "Example")
receipt = finish(worker)
assert receipt["measurement"]["phase"] == "error"
assert receipt["measurement"]["error"] == "deadline_exceeded"
assert worker.client is None
finally:
worker.close()