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.
1971 lines
90 KiB
Python
1971 lines
90 KiB
Python
"""HTTP and WebSocket boundary tests without a real remote libvirt host."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
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"
|
|
)
|
|
OFFICIAL_ALMA9_URL = (
|
|
"https://repo.almalinux.org/almalinux/9/cloud/x86_64/images/"
|
|
"AlmaLinux-9-GenericCloud-latest.x86_64.qcow2"
|
|
)
|
|
OFFICIAL_DEBIAN12_URL = (
|
|
"https://cloud.debian.org/images/cloud/bookworm/latest/"
|
|
"debian-12-generic-amd64.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",
|
|
"rescue_iso_pool": "rescue", "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.rescue_enter_error: VMError | None = None
|
|
self.rescue_pending_manual_restart = False
|
|
self.user_iso_storage_error: VMError | None = None
|
|
self.user_iso_storage_available = 90 * 1024**3
|
|
self.user_iso_import_error: VMError | None = None
|
|
self.user_iso_delete_error: VMError | None = None
|
|
self.user_iso_delete_started = threading.Event()
|
|
self.user_iso_delete_release: threading.Event | None = None
|
|
self.user_iso_volumes: set[tuple[int, str]] = set()
|
|
self.user_iso_cache_started = threading.Event()
|
|
self.user_iso_cache_release: threading.Event | None = None
|
|
self.user_iso_create_started = threading.Event()
|
|
self.user_iso_create_release: threading.Event | None = None
|
|
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 list_vm_states(self):
|
|
self.calls.append(("list_vm_states",))
|
|
if self.list_error:
|
|
raise VMError("libvirt API 不可用", 502)
|
|
return [
|
|
{"uuid": vm["uuid"], "name": vm["name"], "state": vm["state"]}
|
|
for vm in [self.vm, *self.other_vms]
|
|
]
|
|
|
|
def list_vm_metadata(self, vm_ids):
|
|
self.calls.append(("list_vm_metadata", tuple(vm_ids)))
|
|
if self.list_error:
|
|
raise VMError("libvirt API 不可用", 502)
|
|
by_id = {vm["uuid"]: vm for vm in [self.vm, *self.other_vms]}
|
|
rows = []
|
|
for vm_id in vm_ids:
|
|
if vm_id not in by_id:
|
|
continue
|
|
vm = by_id[vm_id]
|
|
source = vm.get("os_source", "unknown")
|
|
disks = [
|
|
{"capacity_gib": disk.get("capacity_gib")}
|
|
for disk in vm.get("disks", [])
|
|
]
|
|
capacities = [
|
|
disk["capacity_gib"] for disk in disks
|
|
if isinstance(disk.get("capacity_gib"), (int, float))
|
|
and disk["capacity_gib"] > 0
|
|
]
|
|
rows.append({
|
|
"uuid": vm["uuid"], "name": vm["name"],
|
|
"vcpu": vm.get("vcpu"), "memory_mib": vm.get("memory_mib"),
|
|
"disks": disks,
|
|
"disk_gib": round(sum(capacities), 2) if capacities else None,
|
|
"autostart": vm.get("autostart", False),
|
|
"managed": vm.get("managed", False),
|
|
"public_ip_cidr": vm.get("public_ip_cidr"),
|
|
"created_at": vm.get("created_at"), "os_name": vm.get("os_name"),
|
|
"os_source": source, "install_iso": vm.get("install_iso"),
|
|
"login_name": "root" if source == "cloud_template" else None,
|
|
})
|
|
return rows
|
|
|
|
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 get_vm_state(self, vm_id):
|
|
self.calls.append(("get_vm_state", vm_id))
|
|
if vm_id != self.vm["uuid"]:
|
|
raise VMError("虚拟机不存在", 404)
|
|
return {"uuid": self.vm["uuid"], "name": self.vm["name"],
|
|
"state": self.vm["state"]}
|
|
|
|
def create_vm(self, spec):
|
|
self.calls.append(("create_vm", spec))
|
|
return self.vm
|
|
|
|
def create_user_iso_vm(self, spec, user_id, volume_name, iso_id, display_name):
|
|
self.calls.append(("create_user_iso_vm", spec, user_id, volume_name,
|
|
iso_id, display_name))
|
|
if (user_id, volume_name) not in self.user_iso_volumes:
|
|
raise VMError("用户 ISO 不存在", 404)
|
|
self.user_iso_create_started.set()
|
|
if self.user_iso_create_release is not None:
|
|
assert self.user_iso_create_release.wait(timeout=5)
|
|
self.vm = {
|
|
**self.vm, "uuid": spec.get("vm_uuid", self.vm["uuid"]),
|
|
"name": spec["name"], "managed": True, "os_source": "iso",
|
|
}
|
|
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 cache_template(self, image_path, volume_name, virtual_size, *,
|
|
trusted_replica_volume_name=None,
|
|
trusted_replica_identity=None):
|
|
self.calls.append(("cache_template", volume_name, virtual_size,
|
|
image_path.stat().st_size,
|
|
trusted_replica_volume_name,
|
|
trusted_replica_identity))
|
|
cached_volume_name = trusted_replica_volume_name or volume_name
|
|
replica_identity = trusted_replica_identity or hashlib.sha256(
|
|
f"{cached_volume_name}:{virtual_size}".encode("ascii")
|
|
).hexdigest()
|
|
return {"volume_name": cached_volume_name, "virtual_size": virtual_size,
|
|
"image_bytes": image_path.stat().st_size,
|
|
"already_cached": trusted_replica_volume_name is not None,
|
|
"replica_identity": replica_identity}
|
|
|
|
def import_rescue_iso(self, image_path, volume_name):
|
|
self.calls.append(("import_rescue_iso", volume_name, image_path.stat().st_size))
|
|
return {"volume_name": volume_name, "image_bytes": image_path.stat().st_size}
|
|
|
|
def import_user_iso(self, image_path, user_id, volume_name):
|
|
self.calls.append(("import_user_iso", user_id, volume_name,
|
|
image_path.stat().st_size))
|
|
if self.user_iso_import_error is not None:
|
|
raise self.user_iso_import_error
|
|
self.user_iso_volumes.add((user_id, volume_name))
|
|
return {"volume_name": volume_name, "image_bytes": image_path.stat().st_size}
|
|
|
|
def cache_user_iso(self, image_path, user_id, volume_name,
|
|
active_volume_names=None, *, trusted_existing=False):
|
|
self.calls.append(("cache_user_iso", user_id, volume_name,
|
|
image_path.stat().st_size, trusted_existing,
|
|
set(active_volume_names or ())))
|
|
self.user_iso_cache_started.set()
|
|
if self.user_iso_cache_release is not None:
|
|
assert self.user_iso_cache_release.wait(timeout=5)
|
|
if self.user_iso_import_error is not None:
|
|
raise self.user_iso_import_error
|
|
already_cached = (user_id, volume_name) in self.user_iso_volumes
|
|
self.user_iso_volumes.add((user_id, volume_name))
|
|
return {"volume_name": volume_name,
|
|
"image_bytes": image_path.stat().st_size,
|
|
"already_cached": already_cached}
|
|
|
|
def check_user_iso_storage(self, user_id):
|
|
self.calls.append(("check_user_iso_storage", user_id))
|
|
if self.user_iso_storage_error is not None:
|
|
raise self.user_iso_storage_error
|
|
return {"available_bytes": self.user_iso_storage_available}
|
|
|
|
def delete_user_iso(self, user_id, volume_name):
|
|
self.calls.append(("delete_user_iso", user_id, volume_name))
|
|
self.user_iso_delete_started.set()
|
|
if self.user_iso_delete_release is not None:
|
|
assert self.user_iso_delete_release.wait(timeout=5)
|
|
if self.user_iso_delete_error is not None:
|
|
raise self.user_iso_delete_error
|
|
if (user_id, volume_name) not in self.user_iso_volumes:
|
|
raise VMError("用户 ISO 不存在", 404)
|
|
self.user_iso_volumes.remove((user_id, volume_name))
|
|
return {"volume_name": volume_name, "deleted": True}
|
|
|
|
def delete_rescue_iso(self, volume_name):
|
|
self.calls.append(("delete_rescue_iso", volume_name))
|
|
return {"volume_name": volume_name, "deleted": True}
|
|
|
|
def prepare_rescue_vm(self, vm_id, volume_name):
|
|
self.calls.append(("prepare_rescue_vm", vm_id, volume_name))
|
|
if self.vm.get("rescue_mode") or self.vm.get("rescue_staged"):
|
|
raise VMError("已经处于救援模式", 409)
|
|
return f'<domain><name>{self.vm["name"]}</name></domain>'
|
|
|
|
def enter_rescue_vm(self, vm_id, volume_name, original_xml):
|
|
self.calls.append(("enter_rescue_vm", vm_id, volume_name, original_xml))
|
|
if self.rescue_enter_error is not None:
|
|
raise self.rescue_enter_error
|
|
if self.rescue_pending_manual_restart:
|
|
self.vm["rescue_staged"] = True
|
|
self.vm["rescue_mode"] = False
|
|
return {"vm": self.vm, "pending_manual_restart": True,
|
|
"warning": "救援 ISO 已配置为下次冷启动;请手动强制断电后开机"}
|
|
self.vm["rescue_mode"] = True
|
|
self.vm["rescue_staged"] = False
|
|
self.vm["rescue_volume_name"] = volume_name
|
|
return {"vm": self.vm}
|
|
|
|
def exit_rescue_vm(self, vm_id, original_xml, *, network_suspended=False):
|
|
self.calls.append(("exit_rescue_vm", vm_id, original_xml,
|
|
network_suspended))
|
|
self.vm["rescue_mode"] = False
|
|
self.vm["rescue_staged"] = False
|
|
self.vm["rescue_volume_name"] = None
|
|
self.vm["network_suspended"] = network_suspended
|
|
self.vm["state"] = "running"
|
|
return {"vm": self.vm}
|
|
|
|
def force_start_staged_rescue_vm(self, vm_id, original_xml):
|
|
self.calls.append(("force_start_staged_rescue_vm", vm_id, original_xml))
|
|
if not self.vm.get("rescue_staged"):
|
|
raise VMError("救援 ISO 尚未预挂载", 409)
|
|
self.vm["state"] = "running"
|
|
self.vm["rescue_staged"] = False
|
|
self.vm["rescue_mode"] = True
|
|
return {"vm": self.vm}
|
|
|
|
def action(self, vm_id, action):
|
|
self.calls.append(("action", vm_id, action))
|
|
if self.vm.get("rescue_staged") and action == "poweroff":
|
|
self.vm["state"] = "shutoff"
|
|
self.vm["rescue_mode"] = True
|
|
elif self.vm.get("rescue_staged") and action == "start":
|
|
self.vm["state"] = "running"
|
|
self.vm["rescue_mode"] = True
|
|
self.vm["rescue_staged"] = False
|
|
return self.vm
|
|
|
|
def service_suspend(self, vm_id):
|
|
self.calls.append(("service_suspend", vm_id))
|
|
was_running = self.vm["state"] == "running"
|
|
self.vm["state"] = "shutoff"
|
|
self.vm["autostart"] = False
|
|
return {**self.vm, "service_was_running": was_running}
|
|
|
|
def service_resume(self, vm_id, *, start_if_suspended=False):
|
|
self.calls.append(("service_resume", vm_id, start_if_suspended))
|
|
self.vm["autostart"] = True
|
|
if start_if_suspended:
|
|
self.vm["state"] = "running"
|
|
return self.vm
|
|
|
|
def network_suspend(self, vm_id):
|
|
self.calls.append(("network_suspend", vm_id))
|
|
self.vm["network_suspended"] = True
|
|
return self.vm
|
|
|
|
def network_resume(self, vm_id):
|
|
self.calls.append(("network_resume", vm_id))
|
|
self.vm["network_suspended"] = False
|
|
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,
|
|
"rescue_iso_pool": staged.profile.rescue_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()
|
|
|
|
|
|
@pytest.mark.parametrize("operation", [
|
|
"service-suspend", "service-resume", "network-suspend", "network-resume",
|
|
])
|
|
def test_service_target_routes_are_not_exposed_by_browser_panel(web, operation):
|
|
client, *_ = web
|
|
response = client.post(f"/api/v1/vms/{VM_ID}/{operation}")
|
|
assert response.status_code == 404
|
|
|
|
|
|
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",), ("ensure_storage_pools",),
|
|
("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",
|
|
"rescue_iso_pool": "/home/rescue-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 saved.json()["rescue_iso_pool"] == "/home/rescue-iso"
|
|
assert service.calls == [
|
|
("list_vms",), ("resources",),
|
|
("list_vms",), ("ensure_storage_pools",), ("resources",),
|
|
]
|
|
|
|
|
|
def test_rescue_template_upload_requires_separate_host_pool(web):
|
|
client, _, token, _, _, _ = web
|
|
csrf = setup_admin(client, token)
|
|
headers = {"X-CSRF-Token": csrf}
|
|
saved = client.put("/api/v1/host", json={**HOST_BODY, "rescue_iso_pool": ""},
|
|
headers=headers)
|
|
assert saved.status_code == 200, saved.text
|
|
assert saved.json()["rescue_iso_pool"] == ""
|
|
assert client.get("/api/v1/resources").status_code == 200
|
|
assert client.post("/api/v1/vms", json=CREATE_BODY, headers=headers).status_code == 201
|
|
response = client.get("/api/v1/rescue-templates")
|
|
assert response.status_code == 409
|
|
assert "救援 ISO 目录" in response.json()["error"]
|
|
response = client.post("/api/v1/rescue-templates?name=Rescue",
|
|
content=b"not an iso", headers=headers)
|
|
assert response.status_code == 409
|
|
|
|
|
|
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("/api/v1/vm-states").json() == {"items": [{
|
|
"uuid": VM_ID, "name": "alma-test", "state": "running",
|
|
}]}
|
|
assert client.get(f"/api/v1/vms/{VM_ID}/state").json() == {
|
|
"uuid": VM_ID, "name": "alma-test", "state": "running",
|
|
}
|
|
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",), ("list_vm_states",),
|
|
("get_vm_state", VM_ID), ("get_vm", VM_ID), ("get_vm", "missing"),
|
|
("create_vm", CREATE_BODY), ("get_vm", VM_ID),
|
|
("action", VM_ID, "reboot"), ("get_vm", VM_ID),
|
|
("delete_vm", VM_ID, True),
|
|
]
|
|
assert all("command=/fake/ssh-wrapper" in p["libvirt_uri"] for p in seen)
|
|
|
|
|
|
def test_vm_metadata_reads_only_selected_ids_and_has_no_credentials(web):
|
|
client, _, token, service, _, _ = web
|
|
csrf = setup_admin(client, token)
|
|
configure_host(client, csrf)
|
|
service.calls.clear()
|
|
service.vm.update({
|
|
"managed": True, "os_source": "cloud_template", "os_name": "AlmaLinux 10",
|
|
"public_ip_cidr": "192.0.2.10/24", "created_at": "2026-09-28T00:00:00Z",
|
|
})
|
|
|
|
response = client.get(f"/api/v1/vm-metadata?ids={VM_ID}")
|
|
assert response.status_code == 200, response.text
|
|
assert response.json() == {"items": [{
|
|
"uuid": VM_ID, "name": "alma-test", "vcpu": 2, "memory_mib": 2048,
|
|
"disks": [], "disk_gib": None, "autostart": False, "managed": True,
|
|
"public_ip_cidr": "192.0.2.10/24", "created_at": "2026-09-28T00:00:00Z",
|
|
"os_name": "AlmaLinux 10", "os_source": "cloud_template",
|
|
"install_iso": None, "login_name": "root",
|
|
}]}
|
|
assert service.calls == [("list_vm_metadata", (VM_ID,))]
|
|
assert "credential" not in response.text and "password" not in response.text
|
|
assert "console" not in response.text
|
|
assert all(set(disk) == {"capacity_gib"}
|
|
for disk in response.json()["items"][0]["disks"])
|
|
|
|
stale_id = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
|
|
mixed = client.get(f"/api/v1/vm-metadata?ids={stale_id},{VM_ID}")
|
|
assert mixed.status_code == 200, mixed.text
|
|
assert [item["uuid"] for item in mixed.json()["items"]] == [VM_ID]
|
|
|
|
invalid = client.get("/api/v1/vm-metadata?ids=not-a-uuid")
|
|
assert invalid.status_code == 400
|
|
too_many = client.get("/api/v1/vm-metadata?ids=" + ",".join([VM_ID] * 101))
|
|
assert too_many.status_code == 400
|
|
|
|
|
|
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_rescue_iso_upload_enter_exit_and_safe_lifecycle(web):
|
|
client, _state, token, service, _manager, _seen = web
|
|
csrf = setup_admin(client, token)
|
|
configure_host(client, csrf)
|
|
headers = {"X-CSRF-Token": csrf, "Content-Type": "application/octet-stream"}
|
|
json_headers = {"X-CSRF-Token": csrf}
|
|
assert client.get("/api/v1/rescue-templates").json() == {"templates": []}
|
|
|
|
iso = bytearray(1024 * 1024)
|
|
for sector, kind in ((16, 1), (17, 0), (18, 255)):
|
|
offset = sector * 2048
|
|
iso[offset] = kind
|
|
iso[offset + 1:offset + 6] = b"CD001"
|
|
iso[offset + 6] = 1
|
|
iso[17 * 2048 + 7:17 * 2048 + 30] = b"EL TORITO SPECIFICATION"
|
|
iso[17 * 2048 + 71:17 * 2048 + 75] = (20).to_bytes(4, "little")
|
|
assert client.post("/api/v1/rescue-templates?name=Rescue", content=iso).status_code == 403
|
|
invalid = client.post("/api/v1/rescue-templates?name=Invalid",
|
|
content=b"invalid", headers=headers)
|
|
assert invalid.status_code in (413, 422)
|
|
queued = client.post("/api/v1/rescue-templates?name=Rescue",
|
|
content=bytes(iso), headers=headers)
|
|
assert queued.status_code == 202, queued.text
|
|
import_job_id = queued.json()["job_id"]
|
|
for _ in range(100):
|
|
job = client.get(f"/api/v1/rescue-templates/import-jobs/{import_job_id}").json()
|
|
if job["status"] in {"completed", "failed"}:
|
|
break
|
|
time.sleep(0.01)
|
|
assert job["status"] == "completed", job
|
|
template = client.get("/api/v1/rescue-templates").json()["templates"][0]
|
|
assert template["name"] == "Rescue"
|
|
assert ("import_rescue_iso", template["volume_name"], len(iso)) in service.calls
|
|
|
|
rescue_url = f"/api/v1/vms/{VM_ID}/rescue"
|
|
wrong = client.post(rescue_url, json={"template_id": template["id"],
|
|
"confirmation_name": "wrong"}, headers=json_headers)
|
|
assert wrong.status_code == 422
|
|
started = client.post(rescue_url, json={"template_id": template["id"],
|
|
"confirmation_name": "alma-test"}, headers=json_headers)
|
|
assert started.status_code == 202, started.text
|
|
for _ in range(100):
|
|
rescue_job = client.get(
|
|
f"/api/v1/rescue-jobs/{started.json()['job_id']}").json()
|
|
if rescue_job["status"] in {"completed", "failed"}:
|
|
break
|
|
time.sleep(0.01)
|
|
assert rescue_job["status"] == "completed", rescue_job
|
|
assert client.get(rescue_url).json()["active"] is True
|
|
assert client.post(f"/api/v1/vms/{VM_ID}/actions", json={"action": "reboot"},
|
|
headers=json_headers).status_code == 409
|
|
assert client.delete(f"/api/v1/rescue-templates/{template['id']}",
|
|
headers=headers).status_code == 409
|
|
|
|
exited = client.post(f"{rescue_url}/exit",
|
|
json={"confirmation_name": "alma-test",
|
|
"network_suspended": True}, headers=json_headers)
|
|
assert exited.status_code == 202, exited.text
|
|
for _ in range(100):
|
|
exit_job = client.get(f"/api/v1/rescue-jobs/{exited.json()['job_id']}").json()
|
|
if exit_job["status"] in {"completed", "failed"}:
|
|
break
|
|
time.sleep(0.01)
|
|
assert exit_job["status"] == "completed", exit_job
|
|
assert client.get(rescue_url).json()["active"] is False
|
|
assert service.vm["network_suspended"] is True
|
|
assert any(call[0] == "exit_rescue_vm" and call[3] is True
|
|
for call in service.calls)
|
|
|
|
# If a worker dies after saving its recovery record but the original
|
|
# persistent definition is still present, reading status safely clears
|
|
# the stale record and allows ordinary VM operations again.
|
|
restarted = client.post(rescue_url, json={"template_id": template["id"],
|
|
"confirmation_name": "alma-test"},
|
|
headers=json_headers)
|
|
assert restarted.status_code == 202, restarted.text
|
|
for _ in range(100):
|
|
rescue_job = client.get(
|
|
f"/api/v1/rescue-jobs/{restarted.json()['job_id']}").json()
|
|
if rescue_job["status"] in {"completed", "failed"}:
|
|
break
|
|
time.sleep(0.01)
|
|
assert rescue_job["status"] == "completed", rescue_job
|
|
service.vm["rescue_mode"] = False
|
|
service.vm["rescue_volume_name"] = None
|
|
assert client.get(rescue_url).json()["status"] is None
|
|
assert client.post(f"/api/v1/vms/{VM_ID}/actions", json={"action": "reboot"},
|
|
headers=json_headers).status_code == 200
|
|
|
|
# A staged rescue definition survives a graceful-shutdown timeout. The
|
|
# owner can power off and cold-start it, while reset/reboot stay blocked.
|
|
service.rescue_pending_manual_restart = True
|
|
staged_request = client.post(rescue_url, json={"template_id": template["id"],
|
|
"confirmation_name": "alma-test"},
|
|
headers=json_headers)
|
|
assert staged_request.status_code == 202, staged_request.text
|
|
for _ in range(100):
|
|
staged_job = client.get(
|
|
f"/api/v1/rescue-jobs/{staged_request.json()['job_id']}").json()
|
|
if staged_job["status"] in {"completed", "failed"}:
|
|
break
|
|
time.sleep(0.01)
|
|
assert staged_job["status"] == "completed", staged_job
|
|
assert staged_job["pending_manual_restart"] is True
|
|
staged_state = client.get(rescue_url).json()
|
|
assert staged_state["staged"] is True and staged_state["active"] is False
|
|
assert staged_state["can_exit"] is True
|
|
assert client.post(f"/api/v1/vms/{VM_ID}/actions", json={"action": "reset"},
|
|
headers=json_headers).status_code == 409
|
|
assert client.post(f"/api/v1/vms/{VM_ID}/actions", json={"action": "poweroff"},
|
|
headers=json_headers).status_code == 200
|
|
assert client.get(rescue_url).json()["staged"] is True
|
|
assert client.post(f"/api/v1/vms/{VM_ID}/actions", json={"action": "start"},
|
|
headers=json_headers).status_code == 200
|
|
assert client.get(rescue_url).json()["active"] is True
|
|
assert client.get(rescue_url).json()["staged"] is False
|
|
restored = client.post(f"{rescue_url}/exit",
|
|
json={"confirmation_name": "alma-test"}, headers=json_headers)
|
|
assert restored.status_code == 202, restored.text
|
|
for _ in range(100):
|
|
restored_job = client.get(
|
|
f"/api/v1/rescue-jobs/{restored.json()['job_id']}").json()
|
|
if restored_job["status"] in {"completed", "failed"}:
|
|
break
|
|
time.sleep(0.01)
|
|
assert restored_job["status"] == "completed", restored_job
|
|
|
|
staged_request = client.post(rescue_url, json={"template_id": template["id"],
|
|
"confirmation_name": "alma-test"},
|
|
headers=json_headers)
|
|
assert staged_request.status_code == 202, staged_request.text
|
|
for _ in range(100):
|
|
staged_job = client.get(
|
|
f"/api/v1/rescue-jobs/{staged_request.json()['job_id']}").json()
|
|
if staged_job["status"] in {"completed", "failed"}:
|
|
break
|
|
time.sleep(0.01)
|
|
assert staged_job["status"] == "completed", staged_job
|
|
force_url = f"{rescue_url}/force-start"
|
|
assert client.post(force_url, json={"confirmation_name": "alma-test"},
|
|
headers=json_headers).status_code == 422
|
|
assert client.post(force_url,
|
|
json={"confirmation_name": "wrong", "ack_data_loss": True},
|
|
headers=json_headers).status_code == 422
|
|
forced = client.post(force_url,
|
|
json={"confirmation_name": "alma-test", "ack_data_loss": True},
|
|
headers=json_headers)
|
|
assert forced.status_code == 202, forced.text
|
|
for _ in range(100):
|
|
force_job = client.get(
|
|
f"/api/v1/rescue-jobs/{forced.json()['job_id']}").json()
|
|
if force_job["status"] in {"completed", "failed"}:
|
|
break
|
|
time.sleep(0.01)
|
|
assert force_job["status"] == "completed", force_job
|
|
assert force_job["operation"] == "force"
|
|
assert client.get(rescue_url).json()["active"] is True
|
|
assert client.post(force_url,
|
|
json={"confirmation_name": "alma-test", "ack_data_loss": True},
|
|
headers=json_headers).status_code == 409
|
|
restored = client.post(f"{rescue_url}/exit",
|
|
json={"confirmation_name": "alma-test"}, headers=json_headers)
|
|
assert restored.status_code == 202, restored.text
|
|
for _ in range(100):
|
|
restored_job = client.get(
|
|
f"/api/v1/rescue-jobs/{restored.json()['job_id']}").json()
|
|
if restored_job["status"] in {"completed", "failed"}:
|
|
break
|
|
time.sleep(0.01)
|
|
assert restored_job["status"] == "completed", restored_job
|
|
assert client.delete(f"/api/v1/rescue-templates/{template['id']}",
|
|
headers=headers).json() == {"deleted": True}
|
|
|
|
|
|
def test_orphan_rescue_marker_blocks_vm_actions_even_without_database_record(web):
|
|
client, _state, token, service, _manager, _seen = web
|
|
csrf = setup_admin(client, token)
|
|
configure_host(client, csrf)
|
|
service.vm["rescue_mode"] = True
|
|
headers = {"X-CSRF-Token": csrf}
|
|
assert client.post(f"/api/v1/vms/{VM_ID}/actions", json={"action": "reboot"},
|
|
headers=headers).status_code == 409
|
|
assert client.delete(f"/api/v1/vms/{VM_ID}", headers=headers).status_code == 409
|
|
service.vm["rescue_mode"] = False
|
|
service.vm["rescue_staged"] = True
|
|
assert client.post(f"/api/v1/vms/{VM_ID}/actions", json={"action": "reboot"},
|
|
headers=headers).status_code == 409
|
|
assert client.delete(f"/api/v1/vms/{VM_ID}", headers=headers).status_code == 409
|
|
|
|
|
|
def test_orphan_staged_rescue_marker_blocks_reinstall(web):
|
|
client, _state, _token, service, _manager, _seen = web
|
|
csrf, template_id, _volume_name = configure_reinstall_case(web)
|
|
service.vm["rescue_staged"] = True
|
|
response = client.post(
|
|
f"/api/v1/vms/{VM_ID}/reinstall",
|
|
json={"template_id": template_id, "confirmation_name": "cloud-vm",
|
|
"root_password": GUEST_PASSWORD},
|
|
headers={"X-CSRF-Token": csrf},
|
|
)
|
|
assert response.status_code == 409, response.text
|
|
|
|
|
|
def test_rescue_premount_failure_does_not_enable_force_restart(web):
|
|
client, _state, token, service, _manager, _seen = web
|
|
csrf = setup_admin(client, token)
|
|
configure_host(client, csrf)
|
|
headers = {"X-CSRF-Token": csrf}
|
|
iso = bytearray(1024 * 1024)
|
|
for sector, kind in ((16, 1), (17, 0), (18, 255)):
|
|
offset = sector * 2048
|
|
iso[offset] = kind
|
|
iso[offset + 1:offset + 6] = b"CD001"
|
|
iso[offset + 6] = 1
|
|
iso[17 * 2048 + 7:17 * 2048 + 30] = b"EL TORITO SPECIFICATION"
|
|
iso[17 * 2048 + 71:17 * 2048 + 75] = (20).to_bytes(4, "little")
|
|
imported = client.post("/api/v1/rescue-templates?name=Rescue",
|
|
content=bytes(iso), headers=headers)
|
|
assert imported.status_code == 202, imported.text
|
|
for _ in range(100):
|
|
import_job = client.get(
|
|
f"/api/v1/rescue-templates/import-jobs/{imported.json()['job_id']}").json()
|
|
if import_job["status"] in {"completed", "failed"}:
|
|
break
|
|
time.sleep(0.01)
|
|
assert import_job["status"] == "completed", import_job
|
|
template = client.get("/api/v1/rescue-templates").json()["templates"][0]
|
|
service.rescue_enter_error = VMError(
|
|
"救援 ISO 预挂载失败,原虚拟机未受影响", 502)
|
|
started = client.post(f"/api/v1/vms/{VM_ID}/rescue",
|
|
json={"template_id": template["id"],
|
|
"confirmation_name": "alma-test"}, headers=headers)
|
|
assert started.status_code == 202, started.text
|
|
for _ in range(100):
|
|
job = client.get(f"/api/v1/rescue-jobs/{started.json()['job_id']}").json()
|
|
if job["status"] in {"completed", "failed"}:
|
|
break
|
|
time.sleep(0.01)
|
|
assert job["status"] == "failed", job
|
|
assert "救援 ISO 预挂载失败" in job["error"]
|
|
assert client.get(f"/api/v1/vms/{VM_ID}/rescue").json()["status"] is None
|
|
assert client.post(f"/api/v1/vms/{VM_ID}/rescue/force-start",
|
|
json={"confirmation_name": "alma-test", "ack_data_loss": True},
|
|
headers=headers).status_code == 409
|
|
assert client.post(f"/api/v1/vms/{VM_ID}/actions",
|
|
json={"action": "poweroff"}, headers=headers).status_code == 200
|
|
|
|
|
|
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, digest)):
|
|
queued = client.post("/api/v1/vm-templates/import", json={
|
|
"name": "AlmaLinux 10", "url": OFFICIAL_CLOUD_URL,
|
|
}, 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 actual_spec["root_password_hash"].startswith("$6$")
|
|
assert {key: value for key, value in actual_spec.items()
|
|
if key != "root_password_hash"} == expected_spec
|
|
assert ("create_vm", expected_spec) not in service.calls
|
|
|
|
|
|
def test_almalinux_9_template_import_exposes_stable_version_and_prevents_duplicate_name(web):
|
|
client, state, token, service, manager, _ = web
|
|
csrf = setup_admin(client, token)
|
|
configure_host(client, csrf)
|
|
headers = {"X-CSRF-Token": csrf}
|
|
image = state.data_dir / "alma9-verified.qcow2"
|
|
image.write_bytes(b"QFI\xfbverified test image")
|
|
digest = "b" * 64
|
|
with patch("virsh_panel.app.download_verified_image",
|
|
return_value=(image, 2 * 1024**3, digest)):
|
|
queued = client.post("/api/v1/vm-templates/import", json={
|
|
"name": "AlmaLinux 9", "url": OFFICIAL_ALMA9_URL, "sha256": digest,
|
|
}, headers=headers)
|
|
assert queued.status_code == 202
|
|
job = wait_for_import_job(client, queued.json()["job_id"])
|
|
|
|
assert job["status"] == "completed"
|
|
template_id = template_id_for(template_scope(manager.current()), digest, "9")
|
|
volume_name = template_volume_name(template_id)
|
|
template = job["template"]
|
|
assert template["id"] == template_id
|
|
assert template["volume_name"] == volume_name
|
|
assert template["os_family"] == "AlmaLinux"
|
|
assert template["os_version"] == "9"
|
|
assert ("import_template", volume_name, 2 * 1024**3) in service.calls
|
|
assert client.get("/api/v1/vm-templates").json()["templates"] == [template]
|
|
|
|
duplicate = client.post("/api/v1/vm-templates/import", json={
|
|
"name": "ALMALINUX 9", "url": OFFICIAL_ALMA9_URL, "sha256": "c" * 64,
|
|
}, headers=headers)
|
|
assert duplicate.status_code == 409
|
|
assert len([call for call in service.calls if call[0] == "import_template"]) == 1
|
|
|
|
|
|
def test_debian_template_import_persists_detected_family_and_version(web):
|
|
client, state, token, service, manager, _ = web
|
|
csrf = setup_admin(client, token)
|
|
configure_host(client, csrf)
|
|
headers = {"X-CSRF-Token": csrf}
|
|
image = state.data_dir / "debian12-verified.qcow2"
|
|
image.write_bytes(b"QFI\xfbverified test image")
|
|
digest = "d" * 64
|
|
with patch("virsh_panel.app.download_verified_image",
|
|
return_value=(image, 2 * 1024**3, digest)):
|
|
queued = client.post("/api/v1/vm-templates/import", json={
|
|
"name": "Debian 12", "url": OFFICIAL_DEBIAN12_URL,
|
|
}, headers=headers)
|
|
assert queued.status_code == 202
|
|
job = wait_for_import_job(client, queued.json()["job_id"])
|
|
|
|
assert job["status"] == "completed"
|
|
template_id = template_id_for(
|
|
template_scope(manager.current()), digest, "12", "Debian"
|
|
)
|
|
template = job["template"]
|
|
assert template["id"] == template_id
|
|
assert template["os_family"] == "Debian"
|
|
assert template["os_version"] == "12"
|
|
assert (
|
|
"import_template", template_volume_name(template_id), 2 * 1024**3
|
|
) 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 key_spec["root_password_hash"].startswith("$6$")
|
|
assert key_response.json()["login_name"] == "root"
|
|
assert key_response.json()["auth_mode"] == "ssh_key_password"
|
|
assert 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"
|
|
generated_key_password = key_credential.json()["password"]
|
|
assert key_credential.json()["login_name"] == "root"
|
|
assert key_credential.json()["auth_mode"] == "ssh_key_password"
|
|
assert len(generated_key_password) == 32
|
|
assert re.search(r"[A-Z]", generated_key_password)
|
|
assert re.search(r"[a-z]", generated_key_password)
|
|
assert re.search(r"[0-9]", generated_key_password)
|
|
assert re.search(r"[^A-Za-z0-9]", generated_key_password)
|
|
assert set(generated_key_password) <= set(
|
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
|
"0123456789!@#$%*-_=+?"
|
|
)
|
|
from passlib.hash import sha512_crypt
|
|
assert sha512_crypt.verify(generated_key_password, key_spec["root_password_hash"])
|
|
assert generated_key_password not in key_response.text
|
|
assert generated_key_password not in client.get("/api/v1/vms").text
|
|
assert generated_key_password not in repr(service.calls)
|
|
|
|
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": "NoDigitsPassword!"},
|
|
{**key_body, "root_password": "NoSymbolPassword123"},
|
|
{**key_body, "root_password": "Password WithSpace1!"},
|
|
):
|
|
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) == 32
|
|
assert re.search(r"[A-Z]", generated_password)
|
|
assert re.search(r"[a-z]", generated_password)
|
|
assert re.search(r"[0-9]", generated_password)
|
|
assert re.search(r"[^A-Za-z0-9]", generated_password)
|
|
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) == 32
|
|
assert re.search(r"[A-Z]", generated_password)
|
|
assert re.search(r"[a-z]", generated_password)
|
|
assert re.search(r"[0-9]", generated_password)
|
|
assert re.search(r"[^A-Za-z0-9]", generated_password)
|
|
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!", "NoDigitsPassword!",
|
|
"NoSymbolPassword123", "Password WithSpace1!",
|
|
])
|
|
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
|
|
|
|
|
|
def test_vm_daily_traffic_uses_utc_days_and_validates_access_and_range(tmp_path):
|
|
state = PanelState(tmp_path / "panel-data")
|
|
manager = FakeRemoteManager()
|
|
service = FakeVMService()
|
|
|
|
class FakeMetricStore:
|
|
def __init__(self):
|
|
self.calls = []
|
|
|
|
def query_daily_traffic(self, scope, vm_id, **kwargs):
|
|
self.calls.append((scope, vm_id, kwargs))
|
|
return [{"day_start": 2_937_600, "download_bytes": 2048,
|
|
"upload_bytes": 1024, "total_bytes": 3072}]
|
|
|
|
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}/traffic/daily"
|
|
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)
|
|
scope = host_scope(manager.current())
|
|
|
|
with patch("virsh_panel.app.time.time", return_value=3_000_000):
|
|
response = client.get(endpoint + "?days=2")
|
|
assert response.status_code == 200
|
|
body = response.json()
|
|
assert body == {
|
|
"vm_id": VM_ID, "days": 2, "timezone": "UTC",
|
|
"from": 2_851_200, "until": 3_000_000,
|
|
"points": [
|
|
{"date": "1970-02-03", "day_start": 2_851_200,
|
|
"download_bytes": None, "upload_bytes": None,
|
|
"total_bytes": None},
|
|
{"date": "1970-02-04", "day_start": 2_937_600,
|
|
"download_bytes": 2048, "upload_bytes": 1024,
|
|
"total_bytes": 3072},
|
|
],
|
|
}
|
|
assert metric_store.calls == [(scope, VM_ID, {
|
|
"host_id": None, "user_id": None,
|
|
"since": 2_851_200, "until": 3_000_000, "limit": 2,
|
|
})]
|
|
|
|
assert client.get(endpoint + "?days=0").status_code == 422
|
|
assert client.get(endpoint + "?days=31").status_code == 422
|
|
assert client.get("/api/v1/vms/not-a-uuid/traffic/daily").status_code == 400
|
|
assert client.get(
|
|
"/api/v1/vms/00000000-0000-4000-8000-000000000002/traffic/daily"
|
|
).status_code == 404
|