"""Host connection probes use the same execution identity as saved services. Keep the real VMService constructor, resource methods, local admission guard and RPC connection adapter. Fake SSH staging, remote objects, the RPC runtime and durable admission in focused tests; the final signed HTTP boundary test uses the real EngineApplication coordinator with in-memory persistence. """ from contextlib import contextmanager from types import SimpleNamespace import pytest from fastapi.testclient import TestClient from test_app import FakeRemoteManager, HOST_BODY, ORIGIN, setup_admin from test_engine_boundary import MemoryStore, SUPER, boundary, call from virsh_panel.app import HostBody, create_app from virsh_panel.config import Settings from virsh_panel.database import DatabaseTemplateStore from virsh_panel.engine_context import ( EngineComponents, ExternalOwnership, HostStore, TRUSTED_ACTOR, ) from virsh_panel.libvirt_service import ( GIB, LIBVIRT_MUTATION_BUDGET, LIBVIRT_READ_BUDGET, VMError, VMService, ) from virsh_panel.metrics import MetricsCollector, host_scope from virsh_panel.panel_state import PanelState class StagedManager(FakeRemoteManager): """Model StableHostManager's trusted identity independently of the body.""" def stage(self, profile, confirmed_fingerprint): staged = super().stage(profile, confirmed_fingerprint) staged.libvirt_uri += str(len(self.staged_profiles)) # An unexpected metadata field must not become an execution identity. staged.metadata["host_id"] = "untrusted-metadata-id" return staged def commit(self, staged): profile = super().commit(staged) if hasattr(self, "host_id"): profile["host_id"] = self.host_id return profile @pytest.fixture def host_app(tmp_path, monkeypatch): opened = [] locks = [] closed = [] services = [] connection = SimpleNamespace( networkLookupByName=lambda _name: SimpleNamespace(isActive=lambda: True), ) def open_session(uri, scope, *, timeout): opened.append((uri, scope, timeout)) return SimpleNamespace(connection=connection, failure=None, close=lambda: closed.append(uri)) runtime = SimpleNamespace(open=open_session, queue_timeout=1) monkeypatch.setattr("virsh_panel.app.get_runtime", lambda: runtime) monkeypatch.setattr("virsh_panel.libvirt_service.get_runtime", lambda: runtime) monkeypatch.setattr(MetricsCollector, "start", lambda _self: None) @contextmanager def resource_guard(resources, *, timeout, connection_failure_safe, tracked_mutations): assert connection_failure_safe is True locks.append(tuple(resources)) yield monkeypatch.setattr("virsh_panel.coordination.resource_guard", resource_guard) def pool(service, _connection, name, *_args): services.append(service) return SimpleNamespace(name=lambda: name, listVolumes=lambda: [], info=lambda: (0, 100 * GIB, 0, 100 * GIB)) monkeypatch.setattr(VMService, "_active_pool", pool) monkeypatch.setattr(VMService, "_ensure_pool", pool) monkeypatch.setattr(VMService, "_refresh_directory_pool", lambda *_args: None) monkeypatch.setattr(VMService, "_same_pool_location", lambda *_args: False) @contextmanager def build(*, internal=True, host_id="7", existing=False): directory = tmp_path / str(len(opened)) directory.mkdir(mode=0o700, exist_ok=True) manager = StagedManager() if internal: manager.host_id = host_id if existing: staged = manager.stage( HostBody(**HOST_BODY).profile(), HOST_BODY["confirmed_fingerprint"], ) manager.commit(staged) manager.calls.clear() settings = Settings(data_dir=directory) if internal: store = HostStore(MemoryStore(), "7") components = EngineComponents( SimpleNamespace(users=ExternalOwnership(store)), manager, DatabaseTemplateStore(store), store, MemoryStore(), ) app = create_app(settings, engine_components=components) @app.middleware("http") async def trusted_actor(request, call_next): token = TRUSTED_ACTOR.set(SUPER) try: return await call_next(request) finally: TRUSTED_ACTOR.reset(token) else: state = PanelState(directory) app = create_app(settings, panel_state=state, remote_manager=manager) with TestClient(app, base_url=ORIGIN) as client: headers = {} if not internal: token = state.token_file.read_text().strip() headers["X-CSRF-Token"] = setup_admin(client, token) yield SimpleNamespace(client=client, manager=manager, headers=headers, opened=opened, locks=locks, closed=closed, services=services) return build @pytest.mark.parametrize("existing", [False, True], ids=["add", "edit"]) @pytest.mark.parametrize("method,path,ensure", [ ("POST", "/api/v1/host/test", False), ("PUT", "/api/v1/host", True), ]) def test_internal_probe_and_save_use_trusted_stable_host_scope( host_app, existing, method, path, ensure): with host_app(existing=existing) as app: response = app.client.request(method, path, json=HOST_BODY) assert response.status_code == 200, response.text assert [call[1:] for call in app.opened] == ( [("7", LIBVIRT_MUTATION_BUDGET), ("7", LIBVIRT_READ_BUDGET)] if ensure else [("7", LIBVIRT_READ_BUDGET)] ) assert app.locks == ([("storage:7",)] if ensure else []) assert all(type(service) is VMService for service in app.services) assert all(service.execution_scope == "7" for service in app.services) assert all(service._resource_scope == "7" for service in app.services) assert len(app.closed) == len(app.opened) actions = [call[0] for call in app.manager.calls] assert ("commit" in actions) is ensure assert ("abort" in actions) is not ensure def test_staged_uri_changes_and_saved_service_share_execution_scope(host_app): with host_app() as app: for method, path in (("POST", "/api/v1/host/test"), ("PUT", "/api/v1/host")): response = app.client.request(method, path, json=HOST_BODY) assert response.status_code == 200, response.text response = app.client.get("/api/v1/resources") assert response.status_code == 200, response.text assert len({uri for uri, _scope, _timeout in app.opened}) == 3 assert {scope for _uri, scope, _timeout in app.opened} == {"7"} assert app.locks == [("storage:7",)] @pytest.mark.parametrize("host_id", [None, "", "bad/id", "a" * 65, 7, True]) @pytest.mark.parametrize("method,path", [ ("POST", "/api/v1/host/test"), ("PUT", "/api/v1/host"), ]) def test_internal_invalid_identity_fails_closed_before_libvirt( host_app, host_id, method, path): with host_app(host_id=host_id) as app: response = app.client.request(method, path, json=HOST_BODY) assert response.status_code == 409, response.text assert app.opened == [] assert app.services == [] assert app.manager.current() is None assert [call[0] for call in app.manager.calls] == ["stage", "test", "abort"] @pytest.mark.parametrize("ensure", [False, True]) def test_standalone_probe_uses_verified_identity_hash(host_app, ensure): with host_app(internal=False) as app: method, path = (("PUT", "/api/v1/host") if ensure else ("POST", "/api/v1/host/test")) response = app.client.request(method, path, json=HOST_BODY, headers=app.headers) assert response.status_code == 200, response.text scope = host_scope({"host": HOST_BODY["host"], "port": HOST_BODY["port"], "fingerprint": HOST_BODY["confirmed_fingerprint"]}) assert {call[1] for call in app.opened} == {scope} assert app.locks == ([(f"storage:{scope}",)] if ensure else []) @pytest.mark.parametrize("method,path", [ ("POST", "/api/v1/host/test"), ("PUT", "/api/v1/host"), ]) def test_request_cannot_choose_execution_host_id(host_app, method, path): with host_app() as app: response = app.client.request(method, path, json={ **HOST_BODY, "host_id": "another-host", }) assert response.status_code == 422, response.text assert app.opened == [] assert app.manager.calls == [] def test_named_pools_without_rescue_skip_ensure_paths(host_app): with host_app() as app: response = app.client.put("/api/v1/host", json={**HOST_BODY, "rescue_iso_pool": ""}) assert response.status_code == 200, response.text assert [call[1:] for call in app.opened] == [("7", LIBVIRT_READ_BUDGET)] assert app.locks == [] @pytest.mark.parametrize("existing", [False, True], ids=["add", "edit"]) def test_storage_validation_failure_aborts_without_replacing_profile( host_app, monkeypatch, existing): def unavailable(*_args): raise VMError("storage unavailable", 502) monkeypatch.setattr(VMService, "_ensure_pool", unavailable) with host_app(existing=existing) as app: original = app.manager.current() response = app.client.put("/api/v1/host", json=HOST_BODY) assert response.status_code == 502, response.text assert app.manager.current() is original assert [call[0] for call in app.manager.calls] == ["stage", "test", "abort"] assert [call[1:] for call in app.opened] == [("7", LIBVIRT_MUTATION_BUDGET)] assert len(app.closed) == 1 def test_signed_save_with_missing_identity_releases_durable_claim(boundary, monkeypatch): client, engine, _store, _logs, services = boundary path = "/internal/v1/hosts/hk/host" assert call(client, "GET", path, SUPER).status_code == 200 manager = engine.registry.components["hk"].manager manager.host_id = None manager.profile = None services["hk"].calls.clear() assert engine.coordinator.snapshot() == {} observed_claims = [] remote_test = manager.test def inspect_admission(staged): observed_claims.extend(engine.coordinator.snapshot().values()) return remote_test(staged) monkeypatch.setattr(manager, "test", inspect_admission) response = call(client, "PUT", path, SUPER, HOST_BODY) assert response.status_code == 409, response.text assert [entry[0] for entry in manager.calls] == ["stage", "test", "abort"] assert manager.current() is None assert services["hk"].calls == [] assert len(observed_claims) == 1 assert observed_claims[0]["state"] == "active" assert observed_claims[0]["kind"] == "request" assert engine.coordinator.snapshot() == {}