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]