You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
1280 lines
57 KiB
Python
1280 lines
57 KiB
Python
"""HTTP and WebSocket boundary tests without a real remote libvirt host."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import stat
|
|
import sys
|
|
import threading
|
|
import time
|
|
import types
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from unittest.mock import AsyncMock, patch
|
|
|
|
import pytest
|
|
from fastapi.testclient import TestClient
|
|
from starlette.websockets import WebSocketDisconnect
|
|
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
|
|
|
|
|
|
# The API is injected with FakeVMService. Test machines need no native libvirt.
|
|
try:
|
|
import libvirt # noqa: F401
|
|
except ModuleNotFoundError:
|
|
stub = types.ModuleType("libvirt")
|
|
stub.libvirtError = type("libvirtError", (Exception,), {})
|
|
sys.modules["libvirt"] = stub
|
|
|
|
from virsh_panel.app import create_app # noqa: E402
|
|
from virsh_panel.cloud_templates import ( # noqa: E402
|
|
TemplateError, TemplateStore, template_id_for, template_scope,
|
|
template_volume_name,
|
|
)
|
|
from virsh_panel.config import Settings # noqa: E402
|
|
from virsh_panel.libvirt_service import VMError # noqa: E402
|
|
from virsh_panel.metrics import host_scope, query_interval_seconds # noqa: E402
|
|
from virsh_panel.panel_state import PanelState # noqa: E402
|
|
from virsh_panel.remote_host import RemoteHostError, validate_public_pool # noqa: E402
|
|
|
|
|
|
PASSWORD = "correct-horse-battery-staple"
|
|
GUEST_PASSWORD = "A-strong-guest-password-2026"
|
|
VM_ID = "00000000-0000-4000-8000-000000000001"
|
|
ORIGIN = "https://panel.example.test"
|
|
STATIC_DIR = Path(__file__).resolve().parents[1] / "static"
|
|
CREATE_BODY = {
|
|
"name": "alma-test", "vcpu": 2, "memory_mib": 2048, "disk_gib": 20,
|
|
"network": "default", "iso": "AlmaLinux-10.iso",
|
|
}
|
|
CLOUD_CREATE_BODY = {
|
|
"source": "cloud", "template_id": "alma10-template",
|
|
"name": "cloud-vm", "vcpu": 2, "memory_mib": 2048, "disk_gib": 20,
|
|
"network": "bridge:br0", "public_ip_cidr": "8.8.8.18/24",
|
|
"gateway": "8.8.8.1", "dns_servers": ["1.1.1.1"],
|
|
"guest_ssh_public_key": (
|
|
"ssh-ed25519 "
|
|
"AAAAC3NzaC1lZDI1NTE5AAAAIF7mFh4aYz3lRzNqjoFQasAQLpm7BdSULhe1iWuvj3y5 "
|
|
"panel-test"
|
|
),
|
|
}
|
|
OFFICIAL_CLOUD_URL = (
|
|
"https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/"
|
|
"AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2"
|
|
)
|
|
HOST_BODY = {
|
|
"host": "vmhost.example.test", "port": 2222,
|
|
"private_key": "-----BEGIN OPENSSH PRIVATE KEY-----\ntest\n-----END OPENSSH PRIVATE KEY-----",
|
|
"host_key": "vp-managed ssh-ed25519 AAAATEST",
|
|
"confirmed_fingerprint": "SHA256:example",
|
|
"storage_pool": "images", "iso_pool": "iso", "default_network": "default",
|
|
}
|
|
|
|
|
|
class FakeVMService:
|
|
def __init__(self) -> None:
|
|
self.calls: list[tuple] = []
|
|
self.resource_error = False
|
|
self.list_error = False
|
|
self.reinstall_gate: threading.Event | None = None
|
|
self.reinstall_started = threading.Event()
|
|
self.vm = {
|
|
"uuid": VM_ID, "name": "alma-test", "state": "running", "vcpu": 2,
|
|
"memory_mib": 2048, "disks": [], "autostart": False,
|
|
}
|
|
self.other_vms: list[dict] = []
|
|
|
|
def resources(self):
|
|
self.calls.append(("resources",))
|
|
if self.resource_error:
|
|
raise VMError("ISO 池尚未就绪", 409)
|
|
return {"networks": ["default"], "isos": ["AlmaLinux-10.iso"],
|
|
"storage_pool": "images"}
|
|
|
|
def ensure_storage_pools(self):
|
|
self.calls.append(("ensure_storage_pools",))
|
|
return {"storage_pool": "panel-dir-kvm", "iso_pool": "panel-dir-iso"}
|
|
|
|
def list_vms(self):
|
|
self.calls.append(("list_vms",))
|
|
if self.list_error:
|
|
raise VMError("libvirt API 不可用", 502)
|
|
return [self.vm, *self.other_vms]
|
|
|
|
def get_vm(self, vm_id):
|
|
self.calls.append(("get_vm", vm_id))
|
|
if vm_id != self.vm["uuid"]:
|
|
raise VMError("虚拟机不存在", 404)
|
|
return self.vm
|
|
|
|
def create_vm(self, spec):
|
|
self.calls.append(("create_vm", spec))
|
|
return self.vm
|
|
|
|
def create_cloud_vm(self, spec, template_volume_name):
|
|
self.calls.append(("create_cloud_vm", spec, template_volume_name))
|
|
if self.vm.get("os_source") == "cloud_template":
|
|
self.other_vms.append(self.vm.copy())
|
|
self.vm = {
|
|
**self.vm, "uuid": spec["vm_uuid"], "name": spec["name"],
|
|
"managed": True, "os_source": "cloud_template",
|
|
"public_ip_cidr": spec["public_ip_cidr"], "os_name": spec["os_name"],
|
|
"credential_generation": f"panel-seed-{spec['vm_uuid']}.iso",
|
|
}
|
|
return self.vm
|
|
|
|
def reinstall_cloud_vm(self, vm_id, template_volume_name, *,
|
|
os_name=None, ssh_public_key="", root_password_hash=None,
|
|
progress=None):
|
|
self.calls.append(("reinstall_cloud_vm", vm_id, template_volume_name,
|
|
ssh_public_key, root_password_hash, os_name))
|
|
self.reinstall_started.set()
|
|
if self.reinstall_gate is not None:
|
|
assert self.reinstall_gate.wait(timeout=5), "test did not release reinstall job"
|
|
if progress is not None:
|
|
progress("completed")
|
|
generation = f"panel-seed-reinstall-{len(self.calls)}.iso"
|
|
self.vm["credential_generation"] = generation
|
|
return {"vm": self.vm, "credential_generation": generation}
|
|
|
|
def import_template(self, image_path, volume_name, virtual_size):
|
|
self.calls.append(("import_template", volume_name, virtual_size))
|
|
return {"volume_name": volume_name, "virtual_size": virtual_size,
|
|
"image_bytes": image_path.stat().st_size}
|
|
|
|
def action(self, vm_id, action):
|
|
self.calls.append(("action", vm_id, action))
|
|
return self.vm
|
|
|
|
def delete_vm(self, vm_id, delete_disks):
|
|
self.calls.append(("delete_vm", vm_id, delete_disks))
|
|
return {"uuid": vm_id, "deleted": True, "deleted_disks": []}
|
|
|
|
def console_port(self, vm_id):
|
|
self.calls.append(("console_port", vm_id))
|
|
return 5907
|
|
|
|
|
|
class FakeRemoteManager:
|
|
def __init__(self) -> None:
|
|
self.calls: list[tuple] = []
|
|
self.profile: dict | None = None
|
|
self.staged_profiles: list = []
|
|
self.unlock_passphrase: str | None = None
|
|
|
|
def current(self):
|
|
return self.profile
|
|
|
|
def scan(self, host, port):
|
|
self.calls.append(("scan", host, port))
|
|
return {"host": host, "port": port, "key_type": "ssh-ed25519",
|
|
"fingerprint": "SHA256:example", "known_hosts_line": HOST_BODY["host_key"]}
|
|
|
|
def stage(self, profile, confirmed_fingerprint):
|
|
validate_public_pool(
|
|
profile.public_pool_cidr, profile.public_gateway,
|
|
profile.public_dns_servers, profile.public_reserved_ips, profile.host,
|
|
profile.public_vm_prefix,
|
|
)
|
|
self.calls.append(("stage", profile.host, profile.port, confirmed_fingerprint))
|
|
self.staged_profiles.append(profile)
|
|
return SimpleNamespace(
|
|
libvirt_uri="qemu+ssh://root@vp-managed/system?command=staged",
|
|
profile=profile,
|
|
)
|
|
|
|
def test(self, staged):
|
|
self.calls.append(("test", staged.libvirt_uri))
|
|
return {"ok": True, "ssh": "connected", "libvirt": "available"}
|
|
|
|
def abort(self, staged):
|
|
self.calls.append(("abort", staged.libvirt_uri))
|
|
|
|
def commit(self, staged):
|
|
self.calls.append(("commit", staged.libvirt_uri))
|
|
self.unlock_passphrase = staged.profile.private_key_passphrase or None
|
|
self.profile = {
|
|
"host": staged.profile.host, "port": staged.profile.port,
|
|
"key_type": "ssh-ed25519", "fingerprint": "SHA256:example",
|
|
"private_key_configured": True,
|
|
"private_key_encrypted": bool(self.unlock_passphrase), "key_locked": False,
|
|
"private_key_passphrase_saved": bool(self.unlock_passphrase),
|
|
"storage_pool": staged.profile.storage_pool,
|
|
"iso_pool": staged.profile.iso_pool,
|
|
"default_network": staged.profile.default_network,
|
|
"region": staged.profile.region,
|
|
"public_pool_cidr": getattr(staged.profile, "public_pool_cidr", ""),
|
|
"public_gateway": getattr(staged.profile, "public_gateway", ""),
|
|
"public_dns_servers": list(getattr(staged.profile, "public_dns_servers", [])),
|
|
"public_reserved_ips": list(getattr(staged.profile, "public_reserved_ips", [])),
|
|
"public_vm_prefix": getattr(staged.profile, "public_vm_prefix", None),
|
|
"libvirt_uri": "qemu+ssh://root@vp-managed/system?no_tty=1&command=/fake/ssh-wrapper",
|
|
"ssh_target": "vp-managed", "ssh_config_file": "/fake/config",
|
|
"ssh_known_hosts_file": "/fake/known_hosts",
|
|
}
|
|
return self.profile
|
|
|
|
def unlock_current(self, passphrase):
|
|
self.calls.append(("unlock_current", passphrase))
|
|
if passphrase != self.unlock_passphrase or self.profile is None:
|
|
raise RemoteHostError("私钥口令错误", 400)
|
|
self.profile["key_locked"] = False
|
|
return self.profile
|
|
|
|
|
|
@pytest.fixture
|
|
def web(tmp_path):
|
|
state = PanelState(tmp_path / "panel-data")
|
|
service = FakeVMService()
|
|
manager = FakeRemoteManager()
|
|
seen_profiles: list[dict] = []
|
|
|
|
def service_factory(profile):
|
|
seen_profiles.append(profile)
|
|
return service
|
|
|
|
settings = Settings(data_dir=state.data_dir, static_dir=STATIC_DIR)
|
|
app = create_app(settings, panel_state=state, remote_manager=manager,
|
|
service_factory=service_factory)
|
|
token = state.token_file.read_text(encoding="ascii").strip()
|
|
with TestClient(
|
|
app,
|
|
base_url=ORIGIN,
|
|
) as client:
|
|
yield client, state, token, service, manager, seen_profiles
|
|
|
|
|
|
def test_first_start_creates_token_and_restarts_reuse_it(tmp_path):
|
|
state = PanelState(tmp_path / "panel-data")
|
|
settings = Settings(data_dir=state.data_dir, static_dir=STATIC_DIR)
|
|
manager = FakeRemoteManager()
|
|
with patch("virsh_panel.app.STARTUP_LOG.warning") as warning:
|
|
create_app(settings, panel_state=state, remote_manager=manager)
|
|
token = state.token_file.read_text(encoding="ascii").strip()
|
|
assert warning.call_args.args == ("VIRSH_PANEL_SETUP_TOKEN=%s", token)
|
|
assert len(token) >= 32
|
|
|
|
create_app(settings, panel_state=PanelState(state.data_dir), remote_manager=manager)
|
|
assert state.token_file.read_text(encoding="ascii").strip() == token
|
|
assert warning.call_count == 2
|
|
|
|
state.create_admin(token, "admin", PASSWORD)
|
|
create_app(settings, panel_state=PanelState(state.data_dir), remote_manager=manager)
|
|
assert warning.call_count == 2
|
|
assert not state.token_file.exists()
|
|
|
|
|
|
def test_lifespan_closes_real_manager_interface(tmp_path):
|
|
state = PanelState(tmp_path / "panel-data")
|
|
settings = Settings(data_dir=state.data_dir, static_dir=STATIC_DIR)
|
|
manager = FakeRemoteManager()
|
|
closed: list[bool] = []
|
|
manager.close = lambda: closed.append(True)
|
|
app = create_app(settings, panel_state=state, remote_manager=manager)
|
|
|
|
with TestClient(app, base_url=ORIGIN) as client:
|
|
assert client.get("/api/v1/health").status_code == 200
|
|
assert closed == []
|
|
assert closed == [True]
|
|
|
|
|
|
def setup_admin(client: TestClient, token: str) -> str:
|
|
response = client.post("/api/v1/setup/admin", json={
|
|
"token": token, "username": "admin", "password": PASSWORD,
|
|
})
|
|
assert response.status_code == 200
|
|
return response.json()["csrf_token"]
|
|
|
|
|
|
def login(client: TestClient) -> str:
|
|
response = client.post("/api/v1/login", json={"username": "admin", "password": PASSWORD})
|
|
assert response.status_code == 200
|
|
return response.json()["csrf_token"]
|
|
|
|
|
|
def configure_host(client: TestClient, csrf: str) -> dict:
|
|
response = client.put("/api/v1/host", json=HOST_BODY, headers={"X-CSRF-Token": csrf})
|
|
assert response.status_code == 200
|
|
return response.json()
|
|
|
|
|
|
def wait_for_import_job(client: TestClient, job_id: str) -> dict:
|
|
for _ in range(100):
|
|
response = client.get(f"/api/v1/vm-templates/import-jobs/{job_id}")
|
|
assert response.status_code == 200
|
|
result = response.json()
|
|
if result["status"] != "running":
|
|
return result
|
|
time.sleep(0.01)
|
|
pytest.fail("云镜像导入任务未在测试等待时间内结束")
|
|
|
|
|
|
def wait_for_reinstall_job(client: TestClient, job_id: str, csrf: str) -> dict:
|
|
for _ in range(100):
|
|
response = client.get(
|
|
f"/api/v1/reinstall-jobs/{job_id}",
|
|
headers={"X-CSRF-Token": csrf},
|
|
)
|
|
assert response.status_code == 200
|
|
result = response.json()
|
|
if result["status"] not in ("queued", "running"):
|
|
return result
|
|
time.sleep(0.01)
|
|
pytest.fail("重装任务未在测试等待时间内结束")
|
|
|
|
|
|
def configure_reinstall_case(web):
|
|
client, state, token, service, manager, _ = web
|
|
csrf = setup_admin(client, token)
|
|
assert client.put(
|
|
"/api/v1/host", json={**HOST_BODY, "default_network": "bridge:br0"},
|
|
headers={"X-CSRF-Token": csrf},
|
|
).status_code == 200
|
|
scope = template_scope(manager.current())
|
|
template_id = template_id_for(scope, "d" * 64)
|
|
volume_name = template_volume_name(template_id)
|
|
TemplateStore(state.data_dir).add(
|
|
scope, {"id": template_id, "volume_name": volume_name, "name": "AlmaLinux 10"},
|
|
)
|
|
service.vm.update({
|
|
"name": "cloud-vm", "managed": True, "os_source": "cloud_template",
|
|
"public_ip_cidr": "8.8.8.18/24", "credential_generation": "legacy-seed.iso",
|
|
})
|
|
return csrf, template_id, volume_name
|
|
|
|
|
|
def test_setup_token_is_single_use_and_admin_survives_restart(web):
|
|
client, state, token, service, manager, _ = web
|
|
assert client.get("/api/v1/setup/status").json() == {"setup_required": True}
|
|
assert client.get("/api/v1/vms").status_code == 401
|
|
assert client.post("/api/v1/login", json={"username": "admin", "password": PASSWORD}).status_code == 409
|
|
wrong = client.post("/api/v1/setup/admin", json={
|
|
"token": "wrong", "username": "admin", "password": PASSWORD,
|
|
})
|
|
assert wrong.status_code == 403
|
|
csrf = setup_admin(client, token)
|
|
assert csrf
|
|
cookie = client.cookies.get("virsh_panel_session")
|
|
assert cookie
|
|
header = client.post("/api/v1/logout", headers={"X-CSRF-Token": csrf}).headers["set-cookie"]
|
|
assert "virsh_panel_session=" in header
|
|
assert client.get("/api/v1/setup/status").json() == {"setup_required": False}
|
|
assert not state.token_file.exists()
|
|
assert stat.S_IMODE(state.state_file.stat().st_mode) == 0o600
|
|
assert state.initialize_setup_token() is None
|
|
assert PanelState(state.data_dir).admin()[0] == "admin"
|
|
assert client.post("/api/v1/setup/admin", json={
|
|
"token": token, "username": "other", "password": PASSWORD,
|
|
}).status_code == 409
|
|
assert login(client)
|
|
assert service.calls == [] and manager.calls == []
|
|
|
|
|
|
def test_login_cookie_csrf_and_logout(web):
|
|
client, _, token, service, manager, _ = web
|
|
setup_admin(client, token)
|
|
assert client.post("/api/v1/login", json={"username": "admin", "password": "bad"}).status_code == 401
|
|
response = client.post("/api/v1/login", json={"username": "admin", "password": PASSWORD})
|
|
csrf = response.json()["csrf_token"]
|
|
cookie = response.headers["set-cookie"].lower()
|
|
assert "httponly" in cookie and "secure" in cookie and "samesite=strict" in cookie
|
|
assert client.get("/api/v1/session").json()["authenticated"] is True
|
|
assert client.post("/api/v1/logout").status_code == 403
|
|
assert client.post("/api/v1/logout", headers={"X-CSRF-Token": csrf}).status_code == 200
|
|
assert client.get("/api/v1/session").json()["authenticated"] is False
|
|
assert service.calls == [] and manager.calls == []
|
|
|
|
|
|
def test_raw_x_real_ip_cannot_reset_login_limit(web):
|
|
client, _, token, *_ = web
|
|
setup_admin(client, token)
|
|
for index in range(5):
|
|
response = client.post(
|
|
"/api/v1/login",
|
|
json={"username": "admin", "password": "wrong"},
|
|
headers={"X-Real-IP": f"198.51.100.{index + 1}"},
|
|
)
|
|
assert response.status_code == 401
|
|
blocked = client.post(
|
|
"/api/v1/login",
|
|
json={"username": "admin", "password": PASSWORD},
|
|
headers={"X-Real-IP": "203.0.113.99"},
|
|
)
|
|
assert blocked.status_code == 429
|
|
|
|
|
|
def test_host_scan_test_save_and_secret_is_never_returned(web):
|
|
client, _, token, service, manager, seen = web
|
|
csrf = setup_admin(client, token)
|
|
assert client.get("/api/v1/host").json() == {"configured": False}
|
|
assert client.get("/api/v1/vms").status_code == 409
|
|
assert client.post("/api/v1/host/scan", json={"host": HOST_BODY["host"], "port": 2222}).status_code == 403
|
|
headers = {"X-CSRF-Token": csrf}
|
|
scan = client.post("/api/v1/host/scan", json={"host": HOST_BODY["host"], "port": 2222}, headers=headers)
|
|
assert scan.json()["fingerprint"] == "SHA256:example"
|
|
tested = client.post("/api/v1/host/test", json=HOST_BODY, headers=headers)
|
|
assert tested.status_code == 200
|
|
assert tested.json()["resources"]["storage_pool"] == "images"
|
|
assert manager.current() is None
|
|
saved = configure_host(client, csrf)
|
|
assert saved["configured"] is True
|
|
assert saved["private_key_configured"] is True
|
|
assert "private_key" not in saved and "host_key" not in saved
|
|
assert "ssh_config_file" not in saved and "libvirt_uri" not in saved
|
|
assert saved["warnings"] == []
|
|
assert client.get("/api/v1/host").json() == {k: v for k, v in saved.items() if k != "warnings"}
|
|
assert seen[0]["libvirt_uri"].endswith("command=staged")
|
|
assert seen[-1]["libvirt_uri"].endswith("command=staged")
|
|
assert manager.calls.count(("commit", manager.calls[-1][1])) == 1
|
|
assert service.calls == [("list_vms",), ("resources",),
|
|
("list_vms",), ("resources",)]
|
|
|
|
|
|
def test_host_region_is_returned_with_host_and_vms(web):
|
|
client, _, token, _service, _manager, _ = web
|
|
csrf = setup_admin(client, token)
|
|
body = {**HOST_BODY, "region": "中国香港"}
|
|
headers = {"X-CSRF-Token": csrf}
|
|
assert client.put("/api/v1/host", json=body, headers=headers).json()["region"] == "中国香港"
|
|
assert client.get("/api/v1/host").json()["region"] == "中国香港"
|
|
assert client.get("/api/v1/vms").json()["items"][0]["region"] == "中国香港"
|
|
assert client.get(f"/api/v1/vms/{VM_ID}").json()["region"] == "中国香港"
|
|
assert client.post("/api/v1/vms", json=CREATE_BODY,
|
|
headers=headers).json()["region"] == "中国香港"
|
|
assert client.put("/api/v1/host", json={**body, "region": "a\nline"},
|
|
headers=headers).status_code == 422
|
|
|
|
|
|
def test_host_public_pool_round_trips_and_rejects_invalid_networks(web):
|
|
client, _, token, _service, manager, _ = web
|
|
csrf = setup_admin(client, token)
|
|
headers = {"X-CSRF-Token": csrf}
|
|
body = {
|
|
**HOST_BODY,
|
|
"host": "8.8.8.3",
|
|
"default_network": "bridge:br0",
|
|
"public_pool_cidr": "8.8.8.0/24",
|
|
"public_gateway": "8.8.8.1",
|
|
"public_dns_servers": ["1.1.1.1", "8.8.4.4"],
|
|
"public_reserved_ips": ["8.8.8.2", "8.8.8.5"],
|
|
}
|
|
tested = client.post("/api/v1/host/test", json=body, headers=headers)
|
|
assert tested.status_code == 200
|
|
saved = client.put("/api/v1/host", json=body, headers=headers)
|
|
assert saved.status_code == 200
|
|
current = client.get("/api/v1/host")
|
|
assert current.status_code == 200
|
|
for key in ("public_pool_cidr", "public_gateway", "public_dns_servers",
|
|
"public_reserved_ips"):
|
|
assert getattr(manager.staged_profiles[0], key) == body[key]
|
|
assert saved.json()[key] == current.json()[key] == body[key]
|
|
assert manager.current()[key] == body[key]
|
|
|
|
for changes in (
|
|
{"public_pool_cidr": "8.8.8.18/24"},
|
|
{"public_pool_cidr": "8.8.8.0/23"},
|
|
{"public_vm_prefix": 25},
|
|
{"public_vm_prefix": 23},
|
|
{"public_pool_cidr": "10.0.0.0/24", "public_gateway": "10.0.0.1"},
|
|
{"public_gateway": "9.9.9.1"},
|
|
{"public_dns_servers": ["invalid-dns"]},
|
|
{"public_reserved_ips": ["9.9.9.2"]},
|
|
):
|
|
rejected = client.put("/api/v1/host", json={**body, **changes}, headers=headers)
|
|
assert rejected.status_code in (400, 422)
|
|
assert manager.current()["public_pool_cidr"] == body["public_pool_cidr"]
|
|
|
|
|
|
def test_host_accepts_provider_28_and_gateway_address_form(web):
|
|
client, _, token, _service, manager, _ = web
|
|
csrf = setup_admin(client, token)
|
|
body = {
|
|
**HOST_BODY,
|
|
"host": "123.123.123.113",
|
|
"default_network": "bridge:br0",
|
|
"public_pool_cidr": "123.123.123.113/28",
|
|
"public_gateway": "123.123.123.113",
|
|
"public_dns_servers": ["1.1.1.1"],
|
|
"public_reserved_ips": ["123.123.123.114"],
|
|
"public_vm_prefix": 24,
|
|
}
|
|
headers = {"X-CSRF-Token": csrf}
|
|
assert client.post("/api/v1/host/test", json=body, headers=headers).status_code == 200
|
|
assert client.put("/api/v1/host", json=body, headers=headers).status_code == 200
|
|
assert manager.current()["public_pool_cidr"] == body["public_pool_cidr"]
|
|
assert manager.current()["public_vm_prefix"] == 24
|
|
|
|
|
|
def test_private_key_passphrase_reaches_host_profile_but_is_never_echoed(web):
|
|
client, _, token, _, manager, _ = web
|
|
csrf = setup_admin(client, token)
|
|
secret = "a strong SSH key passphrase"
|
|
body = {**HOST_BODY, "private_key_passphrase": secret}
|
|
headers = {"X-CSRF-Token": csrf}
|
|
|
|
tested = client.post("/api/v1/host/test", json=body, headers=headers)
|
|
saved = client.put("/api/v1/host", json=body, headers=headers)
|
|
current = client.get("/api/v1/host")
|
|
assert tested.status_code == saved.status_code == current.status_code == 200
|
|
assert len(manager.staged_profiles) == 2
|
|
assert all(profile.private_key_passphrase == secret
|
|
for profile in manager.staged_profiles)
|
|
assert all(secret not in response.text for response in (tested, saved, current))
|
|
assert saved.json()["private_key_encrypted"] is True
|
|
assert saved.json()["private_key_passphrase_saved"] is True
|
|
assert current.json()["private_key_passphrase_saved"] is True
|
|
assert "private_key_passphrase" not in manager.current()
|
|
|
|
|
|
def test_locked_host_returns_423_and_unlock_requires_csrf(web):
|
|
client, _, token, service, manager, _ = web
|
|
csrf = setup_admin(client, token)
|
|
secret = "only held in memory"
|
|
body = {**HOST_BODY, "private_key_passphrase": secret}
|
|
saved = client.put("/api/v1/host", json=body, headers={"X-CSRF-Token": csrf})
|
|
assert saved.status_code == 200
|
|
manager.profile["key_locked"] = True
|
|
service.calls.clear()
|
|
|
|
current = client.get("/api/v1/host")
|
|
locked_vms = client.get("/api/v1/vms")
|
|
assert current.status_code == 200
|
|
assert current.json()["key_locked"] is True
|
|
assert locked_vms.status_code == 423
|
|
assert locked_vms.json()["error_code"] == "key_locked"
|
|
assert service.calls == []
|
|
|
|
no_csrf = client.post("/api/v1/host/unlock", json={"passphrase": secret})
|
|
wrong = client.post("/api/v1/host/unlock", json={"passphrase": "wrong"},
|
|
headers={"X-CSRF-Token": csrf})
|
|
unlocked = client.post("/api/v1/host/unlock", json={"passphrase": secret},
|
|
headers={"X-CSRF-Token": csrf})
|
|
assert no_csrf.status_code == 403
|
|
assert wrong.status_code == 400
|
|
assert unlocked.status_code == 200
|
|
assert unlocked.json()["key_locked"] is False
|
|
assert secret not in unlocked.text
|
|
assert client.get("/api/v1/vms").status_code == 200
|
|
assert manager.calls[-1] == ("unlock_current", secret)
|
|
|
|
|
|
def test_unlock_limits_wrong_passphrase_attempts(web):
|
|
client, _, token, _, manager, _ = web
|
|
csrf = setup_admin(client, token)
|
|
secret = "only held in memory"
|
|
body = {**HOST_BODY, "private_key_passphrase": secret}
|
|
assert client.put("/api/v1/host", json=body, headers={"X-CSRF-Token": csrf}).status_code == 200
|
|
manager.profile["key_locked"] = True
|
|
headers = {"X-CSRF-Token": csrf}
|
|
|
|
for _ in range(5):
|
|
assert client.post("/api/v1/host/unlock", json={"passphrase": "wrong"},
|
|
headers=headers).status_code == 400
|
|
blocked = client.post("/api/v1/host/unlock", json={"passphrase": secret},
|
|
headers=headers)
|
|
assert blocked.status_code == 429
|
|
assert manager.profile["key_locked"] is True
|
|
|
|
|
|
def test_directory_pool_selectors_are_ensured_only_on_save(web):
|
|
client, _, token, service, manager, _ = web
|
|
csrf = setup_admin(client, token)
|
|
body = {**HOST_BODY, "storage_pool": "/home/kvm", "iso_pool": "/home/iso"}
|
|
headers = {"X-CSRF-Token": csrf}
|
|
|
|
tested = client.post("/api/v1/host/test", json=body, headers=headers)
|
|
assert tested.status_code == 200
|
|
assert service.calls == [("list_vms",), ("resources",)]
|
|
assert manager.current() is None
|
|
|
|
saved = client.put("/api/v1/host", json=body, headers=headers)
|
|
assert saved.status_code == 200
|
|
assert saved.json()["storage_pool"] == "/home/kvm"
|
|
assert saved.json()["iso_pool"] == "/home/iso"
|
|
assert service.calls == [
|
|
("list_vms",), ("resources",),
|
|
("list_vms",), ("ensure_storage_pools",), ("resources",),
|
|
]
|
|
|
|
|
|
def test_explicit_bridge_selector_round_trips_through_host_api(web):
|
|
client, _, token, _, manager, seen = web
|
|
csrf = setup_admin(client, token)
|
|
body = {**HOST_BODY, "default_network": "bridge:br0"}
|
|
headers = {"X-CSRF-Token": csrf}
|
|
|
|
tested = client.post("/api/v1/host/test", json=body, headers=headers)
|
|
saved = client.put("/api/v1/host", json=body, headers=headers)
|
|
assert tested.status_code == saved.status_code == 200
|
|
assert all(profile.default_network == "bridge:br0"
|
|
for profile in manager.staged_profiles)
|
|
assert seen[-1]["default_network"] == "bridge:br0"
|
|
assert saved.json()["default_network"] == "bridge:br0"
|
|
assert client.get("/api/v1/host").json()["default_network"] == "bridge:br0"
|
|
|
|
|
|
def test_missing_resource_pool_warns_but_allows_host_connection(web):
|
|
client, _, token, service, manager, _ = web
|
|
csrf = setup_admin(client, token)
|
|
service.resource_error = True
|
|
headers = {"X-CSRF-Token": csrf}
|
|
tested = client.post("/api/v1/host/test", json=HOST_BODY, headers=headers)
|
|
assert tested.status_code == 200
|
|
assert tested.json()["resources"] is None
|
|
assert tested.json()["warnings"] == ["ISO 池尚未就绪"]
|
|
assert manager.current() is None
|
|
saved = client.put("/api/v1/host", json=HOST_BODY, headers=headers)
|
|
assert saved.status_code == 200
|
|
assert saved.json()["configured"] is True
|
|
assert saved.json()["warnings"] == ["ISO 池尚未就绪"]
|
|
|
|
|
|
def test_failed_libvirt_api_check_preserves_existing_host(web):
|
|
client, _, token, service, manager, _ = web
|
|
csrf = setup_admin(client, token)
|
|
configure_host(client, csrf)
|
|
previous = manager.current()
|
|
commits = manager.calls.count(("commit", "qemu+ssh://root@vp-managed/system?command=staged"))
|
|
service.list_error = True
|
|
response = client.put("/api/v1/host", json=HOST_BODY, headers={"X-CSRF-Token": csrf})
|
|
assert response.status_code == 502
|
|
assert manager.current() is previous
|
|
assert manager.calls.count(("commit", "qemu+ssh://root@vp-managed/system?command=staged")) == commits
|
|
assert manager.calls[-1][0] == "abort"
|
|
|
|
|
|
def test_vm_crud_actions_and_error_mapping(web):
|
|
client, _, token, service, _, seen = web
|
|
csrf = setup_admin(client, token)
|
|
configure_host(client, csrf)
|
|
service.calls.clear()
|
|
seen.clear()
|
|
headers = {"X-CSRF-Token": csrf}
|
|
assert client.get("/api/v1/resources").json()["isos"] == ["AlmaLinux-10.iso"]
|
|
assert client.get("/api/v1/vms").json()["items"][0]["uuid"] == VM_ID
|
|
assert client.get(f"/api/v1/vms/{VM_ID}").json()["name"] == "alma-test"
|
|
missing = client.get("/api/v1/vms/missing")
|
|
assert missing.status_code == 404 and missing.json() == {"error": "虚拟机不存在"}
|
|
assert client.post("/api/v1/vms", json=CREATE_BODY).status_code == 403
|
|
assert client.post("/api/v1/vms", json={**CREATE_BODY, "vcpu": 0}, headers=headers).status_code == 422
|
|
created = client.post("/api/v1/vms", json=CREATE_BODY, headers=headers)
|
|
assert created.status_code == 201 and created.json()["uuid"] == VM_ID
|
|
action = client.post(f"/api/v1/vms/{VM_ID}/actions", json={"action": "reboot"}, headers=headers)
|
|
assert action.status_code == 200
|
|
deleted = client.delete(f"/api/v1/vms/{VM_ID}?delete_disks=true", headers=headers)
|
|
assert deleted.status_code == 200 and deleted.json()["deleted"] is True
|
|
assert service.calls == [
|
|
("resources",), ("list_vms",), ("get_vm", VM_ID), ("get_vm", "missing"),
|
|
("create_vm", CREATE_BODY), ("action", VM_ID, "reboot"),
|
|
("delete_vm", VM_ID, True),
|
|
]
|
|
assert all("command=/fake/ssh-wrapper" in p["libvirt_uri"] for p in seen)
|
|
|
|
|
|
def test_vm_create_uses_vcpu_without_a_separate_nic_queue_field(web):
|
|
client, _, token, service, _, _ = web
|
|
csrf = setup_admin(client, token)
|
|
configure_host(client, csrf)
|
|
headers = {"X-CSRF-Token": csrf}
|
|
body = {**CREATE_BODY, "vcpu": 8}
|
|
|
|
created = client.post("/api/v1/vms", json=body, headers=headers)
|
|
assert created.status_code == 201
|
|
assert ("create_vm", body) in service.calls
|
|
assert client.post("/api/v1/vms", json={**body, "nic_queues": 8},
|
|
headers=headers).status_code == 422
|
|
|
|
|
|
def test_cloud_template_and_creation_routes_enforce_auth_csrf_and_fields(web):
|
|
client, _, token, service, _, _ = web
|
|
import_body = {
|
|
"name": "AlmaLinux 10 Generic Cloud",
|
|
"url": "https://example.invalid/AlmaLinux-10-GenericCloud.qcow2",
|
|
"sha256": "a" * 64,
|
|
}
|
|
assert client.get("/api/v1/vm-templates").status_code == 401
|
|
assert client.post("/api/v1/vm-templates/import", json=import_body).status_code == 401
|
|
assert client.post("/api/v1/vms", json=CLOUD_CREATE_BODY).status_code == 401
|
|
|
|
csrf = setup_admin(client, token)
|
|
configure_host(client, csrf)
|
|
assert client.get("/api/v1/vm-templates").json() == {"templates": []}
|
|
assert client.post("/api/v1/vm-templates/import", json=import_body).status_code == 403
|
|
assert client.post("/api/v1/vms", json=CLOUD_CREATE_BODY).status_code == 403
|
|
headers = {"X-CSRF-Token": csrf}
|
|
assert client.post("/api/v1/vm-templates/import", json={**import_body, "sha256": "bad"},
|
|
headers=headers).status_code == 422
|
|
assert client.post("/api/v1/vms", json={**CLOUD_CREATE_BODY, "source": "unknown"},
|
|
headers=headers).status_code == 422
|
|
assert client.post("/api/v1/vms", json={k: v for k, v in CLOUD_CREATE_BODY.items()
|
|
if k != "public_ip_cidr"},
|
|
headers=headers).status_code == 422
|
|
assert client.post("/api/v1/vms", json=CLOUD_CREATE_BODY,
|
|
headers=headers).status_code == 404
|
|
assert not any(call[0] == "create_cloud_vm" for call in service.calls)
|
|
|
|
|
|
def test_cloud_template_import_job_and_create_dispatch(web):
|
|
client, state, token, service, manager, _ = web
|
|
csrf = setup_admin(client, token)
|
|
host_body = {**HOST_BODY, "default_network": "bridge:br0"}
|
|
assert client.put("/api/v1/host", json=host_body,
|
|
headers={"X-CSRF-Token": csrf}).status_code == 200
|
|
service.calls.clear()
|
|
headers = {"X-CSRF-Token": csrf}
|
|
digest = "a" * 64
|
|
image = state.data_dir / "verified-cloud.qcow2"
|
|
image.write_bytes(b"QFI\xfbverified test image")
|
|
with patch("virsh_panel.app.download_verified_image",
|
|
return_value=(image, 2 * 1024**3)):
|
|
queued = client.post("/api/v1/vm-templates/import", json={
|
|
"name": "AlmaLinux 10", "url": OFFICIAL_CLOUD_URL, "sha256": digest,
|
|
}, headers=headers)
|
|
assert queued.status_code == 202
|
|
job_id = queued.json()["job_id"]
|
|
assert queued.json()["status"] == "running"
|
|
job = wait_for_import_job(client, job_id)
|
|
|
|
assert job["status"] == "completed"
|
|
scope = template_scope(manager.current())
|
|
template_id = template_id_for(scope, digest)
|
|
volume_name = template_volume_name(template_id)
|
|
assert job["template"]["id"] == template_id
|
|
assert ("import_template", volume_name, 2 * 1024**3) in service.calls
|
|
for _ in range(100):
|
|
if not image.exists():
|
|
break
|
|
time.sleep(0.01)
|
|
assert not image.exists()
|
|
listed = client.get("/api/v1/vm-templates")
|
|
assert listed.status_code == 200
|
|
assert listed.json()["templates"][0]["id"] == template_id
|
|
assert "scope" not in listed.text
|
|
|
|
cloud_body = {**CLOUD_CREATE_BODY, "template_id": template_id}
|
|
created = client.post("/api/v1/vms", json=cloud_body, headers=headers)
|
|
assert created.status_code == 201
|
|
assert created.json()["name"] == "cloud-vm"
|
|
expected_spec = {key: value for key, value in cloud_body.items()
|
|
if key not in {"source", "template_id"}}
|
|
expected_spec["os_name"] = "AlmaLinux 10"
|
|
expected_spec["vm_uuid"] = created.json()["uuid"]
|
|
created_cloud_calls = [call for call in service.calls
|
|
if call[0] == "create_cloud_vm"]
|
|
assert len(created_cloud_calls) == 1
|
|
_operation, actual_spec, actual_volume = created_cloud_calls[0]
|
|
assert actual_volume == volume_name
|
|
assert "root_password_hash" not in actual_spec
|
|
assert actual_spec == expected_spec
|
|
assert ("create_vm", expected_spec) not in service.calls
|
|
|
|
|
|
def test_cloud_vm_root_login_supports_key_and_hashed_initial_password(web):
|
|
client, state, token, service, manager, _ = web
|
|
csrf = setup_admin(client, token)
|
|
host_body = {**HOST_BODY, "default_network": "bridge:br0"}
|
|
assert client.put("/api/v1/host", json=host_body,
|
|
headers={"X-CSRF-Token": csrf}).status_code == 200
|
|
scope = template_scope(manager.current())
|
|
template_id = template_id_for(scope, "c" * 64)
|
|
volume_name = template_volume_name(template_id)
|
|
TemplateStore(state.data_dir).add(
|
|
scope, {"id": template_id, "volume_name": volume_name},
|
|
)
|
|
headers = {"X-CSRF-Token": csrf}
|
|
service.calls.clear()
|
|
|
|
key_body = {**CLOUD_CREATE_BODY, "template_id": template_id}
|
|
key_response = client.post("/api/v1/vms", json=key_body, headers=headers)
|
|
assert key_response.status_code == 201
|
|
key_spec = service.calls[-1][1]
|
|
assert service.calls[-1][0] == "create_cloud_vm"
|
|
assert key_spec["guest_ssh_public_key"] == CLOUD_CREATE_BODY["guest_ssh_public_key"]
|
|
assert "root_password" not in key_spec
|
|
assert not key_spec.get("root_password_hash")
|
|
assert key_response.json()["login_name"] == "root"
|
|
assert key_response.json()["auth_mode"] == "ssh_key"
|
|
assert not key_response.json()["password_available"]
|
|
key_uuid = key_response.json()["uuid"]
|
|
key_credential = client.post(
|
|
f"/api/v1/vms/{key_uuid}/credential", headers=headers,
|
|
)
|
|
assert key_credential.headers["Cache-Control"] == "no-store"
|
|
assert key_credential.json() == {
|
|
"login_name": "root", "auth_mode": "ssh_key", "password": None,
|
|
}
|
|
|
|
both_body = {**key_body, "name": "key-password-vm",
|
|
"root_password": GUEST_PASSWORD}
|
|
both_response = client.post("/api/v1/vms", json=both_body, headers=headers)
|
|
assert both_response.status_code == 201
|
|
both_spec = service.calls[-1][1]
|
|
assert both_spec["guest_ssh_public_key"] == CLOUD_CREATE_BODY["guest_ssh_public_key"]
|
|
assert both_spec["root_password_hash"].startswith("$6$")
|
|
assert GUEST_PASSWORD not in repr(service.calls)
|
|
assert both_response.json()["auth_mode"] == "ssh_key_password"
|
|
assert client.post(
|
|
f"/api/v1/vms/{both_response.json()['uuid']}/credential", headers=headers,
|
|
).json()["password"] == GUEST_PASSWORD
|
|
|
|
password_body = {
|
|
**key_body, "guest_ssh_public_key": "", "root_password": GUEST_PASSWORD,
|
|
}
|
|
password_response = client.post("/api/v1/vms", json=password_body,
|
|
headers=headers)
|
|
assert password_response.status_code == 201
|
|
password_spec = service.calls[-1][1]
|
|
assert service.calls[-1][0] == "create_cloud_vm"
|
|
assert password_spec["guest_ssh_public_key"] == ""
|
|
assert password_spec["root_password_hash"].startswith("$6$")
|
|
assert "root_password" not in password_spec
|
|
assert GUEST_PASSWORD not in password_response.text
|
|
assert GUEST_PASSWORD not in repr(service.calls)
|
|
password_uuid = password_response.json()["uuid"]
|
|
assert password_response.json()["password_available"]
|
|
assert GUEST_PASSWORD not in client.get("/api/v1/vms").text
|
|
assert GUEST_PASSWORD not in client.get(f"/api/v1/vms/{password_uuid}").text
|
|
assert client.post(f"/api/v1/vms/{password_uuid}/credential").status_code == 403
|
|
assert client.post(
|
|
f"/api/v1/vms/{password_uuid}/credential", headers=headers,
|
|
).json() == {
|
|
"login_name": "root", "auth_mode": "password", "password": GUEST_PASSWORD,
|
|
}
|
|
original_generation = service.vm["credential_generation"]
|
|
service.vm["credential_generation"] = "new-system-seed.iso"
|
|
assert not client.get(f"/api/v1/vms/{password_uuid}").json()["password_available"]
|
|
assert client.post(f"/api/v1/vms/{password_uuid}/credential",
|
|
headers=headers).json()["password"] is None
|
|
service.vm["credential_generation"] = original_generation
|
|
|
|
for invalid_body in (
|
|
{**password_body, "root_password": "too-short"},
|
|
{**password_body, "root_password": "X" * 129},
|
|
{**key_body, "root_password": "alllowercase123!"},
|
|
{**key_body, "root_password": "ALLUPPERCASE123!"},
|
|
{**key_body, "root_password": "NoSymbolPassword123"},
|
|
):
|
|
rejected = client.post("/api/v1/vms", json=invalid_body,
|
|
headers=headers)
|
|
assert rejected.status_code == 422
|
|
assert len([call for call in service.calls
|
|
if call[0] == "create_cloud_vm"]) == 3
|
|
|
|
no_credential = {**key_body, "guest_ssh_public_key": ""}
|
|
generated = client.post("/api/v1/vms", json=no_credential,
|
|
headers=headers)
|
|
assert generated.status_code == 201
|
|
assert generated.json()["password_available"]
|
|
generated_password = client.post(
|
|
f"/api/v1/vms/{generated.json()['uuid']}/credential", headers=headers,
|
|
).json()["password"]
|
|
assert len(generated_password) >= 24
|
|
assert generated_password not in generated.text
|
|
assert generated_password not in client.get("/api/v1/vms").text
|
|
assert generated_password not in repr(service.calls)
|
|
assert len([call for call in service.calls
|
|
if call[0] == "create_cloud_vm"]) == 4
|
|
assert client.delete(
|
|
f"/api/v1/vms/{generated.json()['uuid']}", headers=headers,
|
|
).status_code == 200
|
|
assert not client.get(f"/api/v1/vms/{generated.json()['uuid']}").json()["password_available"]
|
|
|
|
|
|
def test_unknown_vm_has_no_recoverable_password(web):
|
|
client, _state, token, service, _manager, _ = web
|
|
csrf = setup_admin(client, token)
|
|
configure_host(client, csrf)
|
|
listed = client.get("/api/v1/vms")
|
|
assert listed.status_code == 200
|
|
assert listed.json()["items"][0]["login_name"] is None
|
|
assert listed.json()["items"][0]["auth_mode"] == "unknown"
|
|
assert not listed.json()["items"][0]["password_available"]
|
|
assert client.post(
|
|
f"/api/v1/vms/{VM_ID}/credential", headers={"X-CSRF-Token": csrf},
|
|
).json()["password"] is None
|
|
service.vm.update({"managed": True, "os_source": "cloud_template"})
|
|
old_cloud = client.get(f"/api/v1/vms/{VM_ID}").json()
|
|
assert old_cloud["login_name"] == "root"
|
|
assert old_cloud["auth_mode"] == "unknown"
|
|
assert not old_cloud["password_available"]
|
|
|
|
|
|
def test_reinstall_key_without_password_removes_old_password(web):
|
|
client, _state, _token, _service, _manager, _ = web
|
|
csrf, template_id, _volume_name = configure_reinstall_case(web)
|
|
headers = {"X-CSRF-Token": csrf}
|
|
password_job = client.post(
|
|
f"/api/v1/vms/{VM_ID}/reinstall",
|
|
json={"template_id": template_id, "confirmation_name": "cloud-vm",
|
|
"root_password": GUEST_PASSWORD}, headers=headers,
|
|
)
|
|
assert password_job.status_code == 202
|
|
assert wait_for_reinstall_job(client, password_job.json()["job_id"], csrf)["status"] == "succeeded"
|
|
assert client.post(f"/api/v1/vms/{VM_ID}/credential",
|
|
headers=headers).json()["password"] == GUEST_PASSWORD
|
|
key_job = client.post(
|
|
f"/api/v1/vms/{VM_ID}/reinstall",
|
|
json={"template_id": template_id, "confirmation_name": "cloud-vm",
|
|
"ssh_public_key": CLOUD_CREATE_BODY["guest_ssh_public_key"]}, headers=headers,
|
|
)
|
|
assert key_job.status_code == 202
|
|
completed = wait_for_reinstall_job(client, key_job.json()["job_id"], csrf)
|
|
assert completed["status"] == "succeeded"
|
|
assert "generated_password" not in completed
|
|
assert client.post(f"/api/v1/vms/{VM_ID}/credential",
|
|
headers=headers).json()["password"] is None
|
|
assert client.get(f"/api/v1/vms/{VM_ID}").json()["auth_mode"] == "ssh_key"
|
|
deleted = client.delete(f"/api/v1/vms/{VM_ID}", headers=headers)
|
|
assert deleted.status_code == 200
|
|
assert client.get(f"/api/v1/vms/{VM_ID}").json()["auth_mode"] == "unknown"
|
|
|
|
|
|
def test_reinstall_auto_password_job_ack_keeps_vm_credential(web):
|
|
client, state, _token, service, _manager, _ = web
|
|
csrf, template_id, volume_name = configure_reinstall_case(web)
|
|
headers = {"X-CSRF-Token": csrf}
|
|
body = {"template_id": template_id, "confirmation_name": "cloud-vm"}
|
|
|
|
assert client.post(f"/api/v1/vms/{VM_ID}/reinstall", json=body).status_code == 403
|
|
queued = client.post(
|
|
f"/api/v1/vms/{VM_ID}/reinstall", json=body, headers=headers,
|
|
)
|
|
assert queued.status_code == 202
|
|
assert queued.json()["status"] == "queued"
|
|
assert "generated_password" not in queued.json()
|
|
job_id = queued.json()["job_id"]
|
|
assert client.get(f"/api/v1/reinstall-jobs/{job_id}").status_code == 403
|
|
|
|
completed = wait_for_reinstall_job(client, job_id, csrf)
|
|
assert completed["status"] == "succeeded"
|
|
generated_password = completed["generated_password"]
|
|
assert len(generated_password) >= 24
|
|
assert completed["vm_id"] == VM_ID
|
|
service_calls = [call for call in service.calls if call[0] == "reinstall_cloud_vm"]
|
|
assert len(service_calls) == 1
|
|
assert service_calls[0][1:4] == (VM_ID, volume_name, "")
|
|
assert service_calls[0][4].startswith("$6$")
|
|
assert service_calls[0][5] == "AlmaLinux 10"
|
|
assert generated_password not in repr(service.calls)
|
|
|
|
second = client.get(f"/api/v1/reinstall-jobs/{job_id}", headers=headers)
|
|
assert second.status_code == 200
|
|
assert second.json()["status"] == "succeeded"
|
|
assert second.json()["generated_password"] == generated_password
|
|
ack_url = f"/api/v1/reinstall-jobs/{job_id}/ack-password"
|
|
assert client.post(ack_url).status_code == 403
|
|
ack = client.post(ack_url, headers=headers)
|
|
assert ack.status_code == 200
|
|
assert ack.json() == {"acknowledged": True}
|
|
assert client.post(ack_url, headers=headers).json() == {"acknowledged": True}
|
|
after_ack = client.get(f"/api/v1/reinstall-jobs/{job_id}", headers=headers)
|
|
assert after_ack.status_code == 200
|
|
assert "generated_password" not in after_ack.json()
|
|
assert generated_password not in after_ack.text
|
|
assert client.get(f"/api/v1/vms/{VM_ID}").json()["password_available"]
|
|
revealed = client.post(f"/api/v1/vms/{VM_ID}/credential", headers=headers)
|
|
assert revealed.json()["password"] == generated_password
|
|
for path in state.data_dir.rglob("*"):
|
|
if path.is_file():
|
|
assert generated_password.encode() not in path.read_bytes()
|
|
|
|
assert client.post("/api/v1/logout", headers=headers).status_code == 200
|
|
assert client.get(f"/api/v1/reinstall-jobs/{job_id}", headers=headers).status_code == 401
|
|
assert client.post(ack_url, headers=headers).status_code == 401
|
|
|
|
|
|
def test_reinstall_key_and_manual_password_has_no_generated_password(web):
|
|
client, _state, _token, service, _manager, _ = web
|
|
csrf, template_id, volume_name = configure_reinstall_case(web)
|
|
public_key = CLOUD_CREATE_BODY["guest_ssh_public_key"]
|
|
queued = client.post(
|
|
f"/api/v1/vms/{VM_ID}/reinstall",
|
|
json={"template_id": template_id, "confirmation_name": "cloud-vm",
|
|
"ssh_public_key": public_key, "root_password": GUEST_PASSWORD},
|
|
headers={"X-CSRF-Token": csrf},
|
|
)
|
|
assert queued.status_code == 202
|
|
completed = wait_for_reinstall_job(client, queued.json()["job_id"], csrf)
|
|
assert completed["status"] == "succeeded"
|
|
assert "generated_password" not in completed
|
|
assert client.get(f"/api/v1/vms/{VM_ID}").json()["auth_mode"] == "ssh_key_password"
|
|
assert client.post(f"/api/v1/vms/{VM_ID}/credential",
|
|
headers={"X-CSRF-Token": csrf}).json()["password"] == GUEST_PASSWORD
|
|
reinstall_call = next(call for call in service.calls
|
|
if call[0] == "reinstall_cloud_vm")
|
|
assert reinstall_call[1:4] == (VM_ID, volume_name, public_key)
|
|
assert reinstall_call[4].startswith("$6$")
|
|
assert reinstall_call[5] == "AlmaLinux 10"
|
|
|
|
|
|
@pytest.mark.parametrize("weak_password", [
|
|
"short-A!", "alllowercase123!", "ALLUPPERCASE123!", "NoSymbolPassword123",
|
|
])
|
|
def test_reinstall_rejects_weak_manual_root_password(web, weak_password):
|
|
client, _state, _token, service, _manager, _ = web
|
|
csrf, template_id, _volume_name = configure_reinstall_case(web)
|
|
response = client.post(
|
|
f"/api/v1/vms/{VM_ID}/reinstall",
|
|
json={"template_id": template_id, "confirmation_name": "cloud-vm",
|
|
"ssh_public_key": CLOUD_CREATE_BODY["guest_ssh_public_key"],
|
|
"root_password": weak_password},
|
|
headers={"X-CSRF-Token": csrf},
|
|
)
|
|
assert response.status_code == 422
|
|
assert "初始 root 密码" in response.json()["detail"]
|
|
assert not any(call[0] == "reinstall_cloud_vm" for call in service.calls)
|
|
|
|
|
|
def test_reinstall_requires_exact_name_and_blocks_duplicate_or_lifecycle_actions(web):
|
|
client, _state, _token, service, _manager, _ = web
|
|
csrf, template_id, _volume_name = configure_reinstall_case(web)
|
|
headers = {"X-CSRF-Token": csrf}
|
|
body = {"template_id": template_id, "confirmation_name": "cloud-vm"}
|
|
wrong = client.post(
|
|
f"/api/v1/vms/{VM_ID}/reinstall",
|
|
json={**body, "confirmation_name": "wrong-vm"}, headers=headers,
|
|
)
|
|
assert wrong.status_code == 422
|
|
assert not any(call[0] == "reinstall_cloud_vm" for call in service.calls)
|
|
|
|
service.reinstall_gate = threading.Event()
|
|
try:
|
|
queued = client.post(f"/api/v1/vms/{VM_ID}/reinstall",
|
|
json=body, headers=headers)
|
|
assert queued.status_code == 202
|
|
assert service.reinstall_started.wait(timeout=2)
|
|
duplicate = client.post(f"/api/v1/vms/{VM_ID}/reinstall",
|
|
json=body, headers=headers)
|
|
assert duplicate.status_code == 409
|
|
action = client.post(f"/api/v1/vms/{VM_ID}/actions",
|
|
json={"action": "shutdown"}, headers=headers)
|
|
assert action.status_code == 409
|
|
deletion = client.delete(f"/api/v1/vms/{VM_ID}?delete_disks=true",
|
|
headers=headers)
|
|
assert deletion.status_code == 409
|
|
finally:
|
|
service.reinstall_gate.set()
|
|
|
|
completed = wait_for_reinstall_job(client, queued.json()["job_id"], csrf)
|
|
assert completed["status"] == "succeeded"
|
|
assert len([call for call in service.calls
|
|
if call[0] == "reinstall_cloud_vm"]) == 1
|
|
|
|
|
|
def test_cloud_template_import_job_reports_failure_without_registering_template(web):
|
|
client, _, token, service, _, _ = web
|
|
csrf = setup_admin(client, token)
|
|
configure_host(client, csrf)
|
|
headers = {"X-CSRF-Token": csrf}
|
|
with patch("virsh_panel.app.download_verified_image",
|
|
side_effect=TemplateError("云镜像 SHA-256 不匹配", 422)):
|
|
queued = client.post("/api/v1/vm-templates/import", json={
|
|
"name": "AlmaLinux 10", "url": OFFICIAL_CLOUD_URL,
|
|
"sha256": "b" * 64,
|
|
}, headers=headers)
|
|
assert queued.status_code == 202
|
|
job = wait_for_import_job(client, queued.json()["job_id"])
|
|
|
|
assert job["status"] == "failed"
|
|
assert "SHA-256" in job["error"]
|
|
assert client.get("/api/v1/vm-templates").json() == {"templates": []}
|
|
assert not any(call[0] == "import_template" for call in service.calls)
|
|
|
|
|
|
def test_static_assets_and_security_headers(web):
|
|
client, _, _, service, _, _ = web
|
|
page = client.get("/")
|
|
assert page.status_code == 200 and "text/html" in page.headers["content-type"]
|
|
assert page.headers["cache-control"] == "no-store"
|
|
assert "frame-ancestors 'none'" in page.headers["content-security-policy"]
|
|
script_url = re.search(r'src="(/static/app\.js\?v=[^"]+)"', page.text)
|
|
style_url = re.search(r'href="(/static/styles\.css\?v=[^"]+)"', page.text)
|
|
assert script_url is not None and style_url is not None
|
|
script = client.get(script_url.group(1))
|
|
style = client.get(style_url.group(1))
|
|
assert script.status_code == 200 and script.headers["cache-control"] == "no-store"
|
|
assert style.status_code == 200 and style.headers["cache-control"] == "no-store"
|
|
assert "function updateCreateSource()" in script.text
|
|
assert ".create-source-picker" in style.text
|
|
assert client.get("/vendor/novnc/core/rfb.js").status_code == 200
|
|
assert service.calls == []
|
|
|
|
|
|
def test_non_loopback_plain_http_is_rejected(web):
|
|
client, *_ = web
|
|
with TestClient(client.app, base_url="http://panel.example.test") as insecure:
|
|
response = insecure.get("/api/v1/health")
|
|
assert response.status_code == 400
|
|
assert response.json() == {"error": "请使用 HTTPS 访问面板"}
|
|
|
|
|
|
def test_plain_loopback_only_exposes_health(web):
|
|
client, _, token, *_ = web
|
|
with TestClient(client.app, base_url="http://127.0.0.1:8000",
|
|
client=("127.0.0.1", 50000)) as local:
|
|
assert local.get("/api/v1/health").json() == {"status": "ok"}
|
|
assert local.get("/").status_code == 400
|
|
assert local.get("/api/v1/setup/status").status_code == 400
|
|
assert local.post("/api/v1/setup/admin", json={
|
|
"token": token, "username": "admin", "password": PASSWORD,
|
|
}).status_code == 400
|
|
|
|
|
|
def test_trusted_local_reverse_proxy_https_and_websocket(web):
|
|
client, _, token, service, manager, _ = web
|
|
app = ProxyHeadersMiddleware(client.app, trusted_hosts=["127.0.0.1"])
|
|
proxy_headers = {
|
|
"host": "panel.example.test",
|
|
"x-forwarded-proto": "https",
|
|
"x-forwarded-for": "198.51.100.100",
|
|
}
|
|
with TestClient(app, base_url="http://panel.example.test",
|
|
client=("127.0.0.1", 50000)) as proxy:
|
|
assert proxy.get("/api/v1/health", headers=proxy_headers).status_code == 200
|
|
assert proxy.get("/api/v1/health", headers={"host": "panel.example.test"}).status_code == 400
|
|
setup = proxy.post("/api/v1/setup/admin", json={
|
|
"token": token, "username": "admin", "password": PASSWORD,
|
|
}, headers=proxy_headers)
|
|
assert setup.status_code == 200
|
|
assert "secure" in setup.headers["set-cookie"].lower()
|
|
csrf = setup.json()["csrf_token"]
|
|
cookie = f"virsh_panel_session={proxy.cookies['virsh_panel_session']}"
|
|
save = proxy.put("/api/v1/host", json=HOST_BODY, headers={
|
|
**proxy_headers, "X-CSRF-Token": csrf, "cookie": cookie,
|
|
})
|
|
assert save.status_code == 200
|
|
assert save.json()["configured"] is True
|
|
service.calls.clear()
|
|
with patch("virsh_panel.app.relay_console", new_callable=AsyncMock) as relay:
|
|
with proxy.websocket_connect(
|
|
f"ws://panel.example.test/api/v1/vms/{VM_ID}/console",
|
|
headers={**proxy_headers, "origin": ORIGIN, "cookie": cookie},
|
|
):
|
|
pass
|
|
assert service.calls == [("console_port", VM_ID)]
|
|
relay.assert_awaited_once()
|
|
with pytest.raises(WebSocketDisconnect) as plain_ws:
|
|
with proxy.websocket_connect(
|
|
f"ws://panel.example.test/api/v1/vms/{VM_ID}/console",
|
|
headers={"host": "panel.example.test", "origin": ORIGIN, "cookie": cookie},
|
|
):
|
|
pass
|
|
assert plain_ws.value.code == 4403
|
|
assert manager.current() is not None
|
|
|
|
|
|
def test_untrusted_forwarded_proto_and_spoofed_local_host_are_rejected(web):
|
|
client, *_ = web
|
|
app = ProxyHeadersMiddleware(client.app, trusted_hosts=["127.0.0.1"])
|
|
with TestClient(app, base_url="http://panel.example.test",
|
|
client=("198.51.100.10", 50000)) as direct:
|
|
spoofed_https = direct.get("/api/v1/health", headers={
|
|
"host": "panel.example.test", "x-forwarded-proto": "https",
|
|
})
|
|
spoofed_local_host = direct.get("/api/v1/health", headers={
|
|
"host": "localhost", "x-forwarded-proto": "http",
|
|
})
|
|
with pytest.raises(WebSocketDisconnect) as spoofed_ws:
|
|
with direct.websocket_connect(
|
|
f"ws://panel.example.test/api/v1/vms/{VM_ID}/console",
|
|
headers={"host": "panel.example.test", "origin": ORIGIN,
|
|
"x-forwarded-proto": "https"},
|
|
):
|
|
pass
|
|
assert spoofed_https.status_code == 400
|
|
assert spoofed_local_host.status_code == 400
|
|
assert spoofed_ws.value.code == 4403
|
|
|
|
|
|
def test_websocket_origin_auth_and_console_relay(web):
|
|
client, _, token, service, _, _ = web
|
|
with pytest.raises(WebSocketDisconnect) as unauthenticated:
|
|
with client.websocket_connect(
|
|
f"wss://panel.example.test/api/v1/vms/{VM_ID}/console",
|
|
headers={"origin": ORIGIN, "host": "panel.example.test"},
|
|
):
|
|
pass
|
|
assert unauthenticated.value.code == 4401
|
|
|
|
csrf = setup_admin(client, token)
|
|
configure_host(client, csrf)
|
|
service.calls.clear()
|
|
cookie = f"virsh_panel_session={client.cookies['virsh_panel_session']}"
|
|
with pytest.raises(WebSocketDisconnect) as wrong_origin:
|
|
with client.websocket_connect(
|
|
f"wss://panel.example.test/api/v1/vms/{VM_ID}/console",
|
|
headers={"origin": "https://attacker.example", "cookie": cookie,
|
|
"host": "panel.example.test"},
|
|
):
|
|
pass
|
|
assert wrong_origin.value.code == 4403
|
|
with patch("virsh_panel.app.relay_console", new_callable=AsyncMock) as relay:
|
|
with client.websocket_connect(
|
|
f"wss://panel.example.test/api/v1/vms/{VM_ID}/console",
|
|
headers={"origin": ORIGIN, "cookie": cookie, "host": "panel.example.test"},
|
|
):
|
|
pass
|
|
assert service.calls == [("console_port", VM_ID)]
|
|
relay.assert_awaited_once()
|
|
assert relay.await_args.kwargs["port"] == 5907
|
|
assert relay.await_args.kwargs["ssh_target"] == "vp-managed"
|
|
assert relay.await_args.kwargs["ssh_config_file"] == "/fake/config"
|
|
|
|
|
|
def test_vm_metrics_requires_auth_validates_vm_and_isolates_host(tmp_path):
|
|
state = PanelState(tmp_path / "panel-data")
|
|
manager = FakeRemoteManager()
|
|
service = FakeVMService()
|
|
|
|
class FakeMetricStore:
|
|
def __init__(self):
|
|
self.calls = []
|
|
self.allowed_scope = None
|
|
|
|
def query_metric_samples(self, scope, vm_id, **kwargs):
|
|
self.calls.append((scope, vm_id, kwargs))
|
|
if scope != self.allowed_scope:
|
|
return []
|
|
return [{"timestamp": 2_999_900, "cpu_percent": 25,
|
|
"memory_used_mib": None, "memory_total_mib": None,
|
|
"disk_read_bps": 128, "disk_write_bps": 0,
|
|
"network_rx_bps": 4096, "network_tx_bps": 1024}]
|
|
|
|
metric_store = FakeMetricStore()
|
|
app = create_app(Settings(data_dir=state.data_dir, static_dir=STATIC_DIR),
|
|
panel_state=state, remote_manager=manager,
|
|
service_factory=lambda _profile: service,
|
|
metric_store=metric_store)
|
|
with TestClient(app, base_url=ORIGIN) as client:
|
|
endpoint = f"/api/v1/vms/{VM_ID}/metrics"
|
|
assert client.get(endpoint).status_code == 401
|
|
token = state.token_file.read_text(encoding="ascii").strip()
|
|
csrf = setup_admin(client, token)
|
|
configure_host(client, csrf)
|
|
metric_store.allowed_scope = host_scope(manager.current())
|
|
with patch("virsh_panel.app.time.time", return_value=3_000_000):
|
|
response = client.get(endpoint + "?range=30d")
|
|
assert response.status_code == 200
|
|
body = response.json()
|
|
assert body["vm_id"] == VM_ID
|
|
assert body["range"] == "30d"
|
|
assert body["interval_seconds"] == query_interval_seconds(30 * 24 * 3600)
|
|
assert len(body["points"]) == 1
|
|
scope, vm_id, args = metric_store.calls[-1]
|
|
assert scope == metric_store.allowed_scope and vm_id == VM_ID
|
|
assert args["since"] == 3_000_000 - 30 * 24 * 3600
|
|
assert args["until"] == 3_000_000 and args["limit"] == 600
|
|
|
|
assert client.get(endpoint + "?range=60d").status_code == 422
|
|
assert client.get("/api/v1/vms/not-a-uuid/metrics").status_code == 400
|
|
assert client.get(
|
|
"/api/v1/vms/00000000-0000-4000-8000-000000000002/metrics"
|
|
).status_code == 404
|
|
before = len(metric_store.calls)
|
|
manager.profile["fingerprint"] = "SHA256:another-host"
|
|
with patch("virsh_panel.app.time.time", return_value=3_000_000):
|
|
changed_host = client.get(endpoint)
|
|
assert changed_host.status_code == 200
|
|
assert changed_host.json()["points"] == []
|
|
assert len(metric_store.calls) == before + 1
|