"""Database-backed state behavior without requiring a live MariaDB server.""" from __future__ import annotations import base64 import os import stat import struct import subprocess from pathlib import Path from types import SimpleNamespace import pytest from cryptography.hazmat.primitives.ciphers.aead import AESGCM from virsh_panel.auth import verify_password from virsh_panel.cloud_templates import TemplateError from virsh_panel.database import ( DatabasePanelState, DatabaseRemoteHostManager, DatabaseStore, DatabaseTemplateStore, ) from virsh_panel.remote_host import HostProfile, RemoteHostError PRIVATE_KEY = "-----BEGIN OPENSSH PRIVATE KEY-----\nZmFrZQ==\n-----END OPENSSH PRIVATE KEY-----\n" class MemoryStore: def __init__(self) -> None: self.records: dict[tuple[str, str], str] = {} def get(self, kind: str, key: str) -> str | None: return self.records.get((kind, key)) def set(self, kind: str, key: str, value: str) -> None: self.records[(kind, key)] = value def insert(self, kind: str, key: str, value: str) -> bool: if (kind, key) in self.records: return False self.records[(kind, key)] = value return True def delete(self, kind: str, key: str) -> None: self.records.pop((kind, key), None) def list(self, kind: str) -> dict[str, str]: return {key: value for (record_type, key), value in self.records.items() if record_type == kind} def test_database_ciphertext_is_randomized_and_bound_to_record_key(): store = DatabaseStore.__new__(DatabaseStore) store._cipher = AESGCM(b"a" * 32) first = store._encrypt("secret", "gitea_token", "private-token") second = store._encrypt("secret", "gitea_token", "private-token") assert first != second assert b"private-token" not in first assert store._decrypt("secret", "gitea_token", first) == "private-token" with pytest.raises(Exception, match="密文"): store._decrypt("secret", "different_name", first) with pytest.raises(Exception, match="密文"): store._decrypt("secret", "gitea_token", first[:-1] + b"0") def test_linux_tmpfs_agent_socket_path_fits_openssh_limit(): # Linux pid_max cannot exceed 4,194,304; the runtime name is deliberately # short so SSHAgentSession's <100-byte socket guard accepts it. longest = ( "/dev/shm/v4194304-abcd/generations/gen-" + "f" * 32 + "/agent-" + "f" * 16 + ".sock" ) assert len(longest.encode()) < 100 def test_non_linux_rejects_disk_backed_private_key_fallback(tmp_path, monkeypatch): monkeypatch.setattr("virsh_panel.database.sys", SimpleNamespace(platform="darwin")) data_dir = tmp_path / "panel" with pytest.raises(RemoteHostError, match="仅支持 Linux"): DatabaseRemoteHostManager(MemoryStore(), data_dir) assert not list(data_dir.rglob("id_private")) def test_admin_hash_is_database_only_and_bootstrap_token_is_consumed(tmp_path: Path): store = MemoryStore() data_dir = tmp_path / "panel" state = DatabasePanelState(data_dir, store) token = state.initialize_setup_token() assert token state.create_admin(token, "admin", "a-valid-very-long-password") assert not (data_dir / "state.json").exists() assert not (data_dir / "setup-token").exists() assert stat.S_IMODE(data_dir.stat().st_mode) == 0o700 reopened = DatabasePanelState(data_dir, store) username, hashed = reopened.admin() assert username == "admin" assert verify_password("a-valid-very-long-password", hashed) assert reopened.initialize_setup_token() is None def test_templates_are_isolated_by_host_scope_and_atomic_insert(): store = MemoryStore() templates = DatabaseTemplateStore(store) record = {"id": "alma10-12345678-abcdef0123456789", "name": "AlmaLinux"} assert templates.add("a" * 64, record) == record assert templates.list("a" * 64) == [record] assert templates.list("b" * 64) == [] with pytest.raises(TemplateError) as duplicate: templates.add("a" * 64, record) assert duplicate.value.status == 409 def _host_key() -> str: blob = struct.pack("!I", 11) + b"ssh-ed25519" + struct.pack("!I", 32) + b"a" * 32 return "ssh-ed25519 " + base64.b64encode(blob).decode("ascii") def _fake_ssh(argv, **_kwargs): if argv[0] == "ssh-keyscan": return subprocess.CompletedProcess(argv, 0, "host.example " + _host_key() + "\n", "") if argv[0] == "ssh-keygen": return subprocess.CompletedProcess(argv, 0, "ssh-ed25519 fake-public-key\n", "") if argv[0] == "ssh": return subprocess.CompletedProcess(argv, 0, "ok", "") raise AssertionError(argv) def _encrypted_ssh(argv, **kwargs): if argv[0] == "ssh-keygen": return subprocess.CompletedProcess(argv, 255, "", "passphrase required") return _fake_ssh(argv, **kwargs) class FakeAgent: def __init__(self, generation: Path, _key_path: Path, passphrase: str) -> None: if passphrase != "open-sesame": raise RuntimeError("bad passphrase") self.socket_path = generation / "fake-agent.sock" self.public_key = _host_key() self.alive = True def close(self) -> None: self.alive = False def test_remote_host_is_rebuilt_from_database_without_durable_private_key(tmp_path: Path): store = MemoryStore() runtime_parent = tmp_path / "simulated-tmpfs" runtime_parent.mkdir() data_dir = tmp_path / "panel" first = DatabaseRemoteHostManager( store, data_dir, runtime_parent=runtime_parent, runner=_fake_ssh, ) scan = first.scan("host.example", 22) profile = HostProfile( host="host.example", port=22, private_key=PRIVATE_KEY, host_key=scan["known_hosts_line"], storage_pool="/home/kvm", iso_pool="/home/iso", default_network="bridge:br0", ) staged = first.stage(profile, scan["fingerprint"]) assert first.test(staged)["libvirt"] == "available" current = first.commit(staged) assert current["host"] == "host.example" assert current["libvirt_uri"].find("runtime-wrappers") >= 0 assert ("host", "current") in store.records assert not list(data_dir.rglob("id_private")) assert not list(data_dir.rglob("profile.json")) first.close() second = DatabaseRemoteHostManager( store, data_dir, runtime_parent=runtime_parent, runner=_fake_ssh, ) assert second.current()["storage_pool"] == "/home/kvm" assert second.current()["default_network"] == "bridge:br0" assert (second._current_generation() / "id_private").read_text() == PRIVATE_KEY assert not list(data_dir.rglob("id_private")) second.close() assert not list(runtime_parent.rglob("id_private")) def test_encrypted_host_key_is_locked_again_after_process_restart(tmp_path: Path): store = MemoryStore() runtime_parent = tmp_path / "simulated-tmpfs" runtime_parent.mkdir() data_dir = tmp_path / "panel" first = DatabaseRemoteHostManager( store, data_dir, runtime_parent=runtime_parent, runner=_encrypted_ssh, agent_factory=FakeAgent, ) scan = first.scan("host.example", 22) staged = first.stage(HostProfile( host="host.example", port=22, private_key=PRIVATE_KEY, host_key=scan["known_hosts_line"], private_key_passphrase="open-sesame", ), scan["fingerprint"]) first.test(staged) assert first.commit(staged)["key_locked"] is False first.close() second = DatabaseRemoteHostManager( store, data_dir, runtime_parent=runtime_parent, runner=_encrypted_ssh, agent_factory=FakeAgent, ) assert second.current()["key_locked"] is True assert second.unlock_current("open-sesame")["key_locked"] is False second.close() def test_startup_prunes_only_marked_runtime_of_dead_process(tmp_path: Path, monkeypatch): dead = tmp_path / "v99999999-dead" live = tmp_path / f"v{os.getpid()}-abcd" dead.mkdir(mode=0o700) live.mkdir(mode=0o700) (dead / ".owner").write_text("99999999:123\n") (live / ".owner").write_text(f"{os.getpid()}:456\n") (dead / ".owner").chmod(0o600) (live / ".owner").chmod(0o600) monkeypatch.setattr( DatabaseRemoteHostManager, "_process_start_ticks", staticmethod(lambda pid: "456" if pid == os.getpid() else None), ) DatabaseRemoteHostManager._clean_stale_runtime(tmp_path) assert not dead.exists() assert live.exists()