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.
virt/tests/test_cloud_templates.py

182 lines
7.1 KiB
Python

"""Official-image import restrictions and private template catalog tests."""
from __future__ import annotations
import hashlib
import io
import stat
import struct
from types import SimpleNamespace
from unittest.mock import patch
import pytest
from virsh_panel.cloud_templates import (
TemplateError,
TemplateStore,
_RejectRedirects,
download_verified_image,
image_version_for,
template_id_for,
template_scope,
template_volume_name,
validate_image_url,
)
OFFICIAL = (
"https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/"
"AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2"
)
OFFICIAL_9 = (
"https://repo.almalinux.org/almalinux/9/cloud/x86_64/images/"
"AlmaLinux-9-GenericCloud-latest.x86_64.qcow2"
)
def test_official_almalinux_9_and_10_are_distinct_supported_versions():
assert validate_image_url(OFFICIAL_9) == OFFICIAL_9
assert image_version_for(OFFICIAL_9) == "9"
assert image_version_for(OFFICIAL) == "10"
scope = "a" * 64
digest = "b" * 64
assert template_id_for(scope, digest, "9").startswith("alma9-")
assert template_id_for(scope, digest, "10").startswith("alma10-")
assert template_volume_name(template_id_for(scope, digest, "9")).startswith(
"panel-template-alma9-"
)
with pytest.raises(TemplateError):
validate_image_url(OFFICIAL_9.replace("/almalinux/9/", "/almalinux/10/"))
with pytest.raises(TemplateError):
validate_image_url(OFFICIAL_9.replace("AlmaLinux-9-", "AlmaLinux-8-"))
with pytest.raises(TemplateError):
template_id_for(scope, digest, "8")
def qcow2_fixture(virtual_size=2 * 1024**3) -> bytes:
header = bytearray(104)
header[:4] = b"QFI\xfb"
header[4:8] = struct.pack(">I", 3)
header[20:24] = struct.pack(">I", 16)
header[24:32] = struct.pack(">Q", virtual_size)
header[100:104] = struct.pack(">I", 104)
return bytes(header) + b"fake qcow2 content for controlled import test"
@pytest.mark.parametrize(
"url",
[
"http://repo.almalinux.org/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2",
"https://evil.example/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2",
"https://repo.almalinux.org.evil.example/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2",
"https://user:pass@repo.almalinux.org/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2",
"https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/../../etc/passwd",
"https://repo.almalinux.org/almalinux/10/cloud/x86_64/images/AlmaLinux-10-GenericCloud-10.1-20260101.x86_64.qcow2?token=secret",
],
)
def test_import_url_rejects_nonofficial_and_ambiguous_targets(url):
with pytest.raises(TemplateError):
validate_image_url(url)
def test_verified_image_is_private_and_has_expected_virtual_size(tmp_path):
body = qcow2_fixture()
digest = hashlib.sha256(body).hexdigest()
opener = SimpleNamespace(open=lambda *_args, **_kwargs: io.BytesIO(body))
with patch("virsh_panel.cloud_templates.urllib.request.build_opener",
return_value=opener):
downloaded, virtual_size = download_verified_image(OFFICIAL, digest, tmp_path)
try:
assert downloaded.read_bytes() == body
assert virtual_size == 2 * 1024**3
assert stat.S_IMODE(downloaded.stat().st_mode) == 0o600
finally:
downloaded.unlink()
def test_failed_hash_never_leaves_unverified_template_file(tmp_path):
body = qcow2_fixture()
opener = SimpleNamespace(open=lambda *_args, **_kwargs: io.BytesIO(body))
with patch("virsh_panel.cloud_templates.urllib.request.build_opener",
return_value=opener):
with pytest.raises(TemplateError, match="SHA-256"):
download_verified_image(OFFICIAL, "0" * 64, tmp_path)
assert list(tmp_path.iterdir()) == []
def test_redirect_to_nonofficial_target_is_rejected_before_following():
handler = _RejectRedirects()
with pytest.raises(TemplateError, match="重定向"):
handler.redirect_request(None, None, 302, "Found", {},
"http://127.0.0.1/private")
def test_external_data_file_feature_is_rejected(tmp_path):
body = bytearray(qcow2_fixture())
body[72:80] = struct.pack(">Q", 4)
digest = hashlib.sha256(body).hexdigest()
opener = SimpleNamespace(open=lambda *_args, **_kwargs: io.BytesIO(body))
with patch("virsh_panel.cloud_templates.urllib.request.build_opener",
return_value=opener):
with pytest.raises(TemplateError, match="外部依赖"):
download_verified_image(OFFICIAL, digest, tmp_path)
assert list(tmp_path.iterdir()) == []
def test_template_catalog_is_private_and_scoped_to_host_and_disk_pool(tmp_path):
data_dir = tmp_path / "data"
data_dir.mkdir(mode=0o700)
store = TemplateStore(data_dir)
profile = {
"host": "hypervisor.example", "port": 2222,
"fingerprint": "SHA256:fixture", "storage_pool": "/home/kvm",
}
scope = template_scope(profile)
other_scope = template_scope({**profile, "storage_pool": "/other/pool"})
record = {
"id": "alma10-example", "name": "AlmaLinux 10", "sha256": "a" * 64,
"volume_name": "alma10-cloud.qcow2", "virtual_size": 2 * 1024**3,
}
assert store.add(scope, record) == record
assert store.list(scope) == [record]
assert store.list(other_scope) == []
assert TemplateStore(data_dir).get(scope, record["id"]) == record
assert stat.S_IMODE(store.file.stat().st_mode) == 0o600
with pytest.raises(TemplateError):
store.get(other_scope, record["id"])
with pytest.raises(TemplateError):
store.add(scope, record)
def test_template_rename_preserves_image_record_and_host_scope(tmp_path):
data_dir = tmp_path / "data"
data_dir.mkdir(mode=0o700)
store = TemplateStore(data_dir)
scope = "a" * 64
other_scope = "b" * 64
template_id = template_id_for(scope, "c" * 64, "9")
record = {
"id": template_id, "name": "AlmaLinux 9", "os_family": "AlmaLinux",
"os_version": "9", "sha256": "c" * 64,
"volume_name": template_volume_name(template_id), "virtual_size": 2 * 1024**3,
}
store.add(scope, record)
store.add(scope, {**record, "id": "other", "name": "Another name"})
store.add(other_scope, {**record, "name": "Other host"})
with pytest.raises(TemplateError) as inaccessible:
store.rename(other_scope, "other", "Missing")
assert inaccessible.value.status == 404
with pytest.raises(TemplateError) as duplicate:
store.rename(scope, template_id, "another NAME")
assert duplicate.value.status == 409
for invalid in ("", "x" * 65, "bad\x7fentry"):
with pytest.raises(TemplateError):
store.rename(scope, template_id, invalid)
updated = store.rename(scope, template_id, " 新名称 ")
assert updated == {**record, "name": "新名称"}
assert TemplateStore(data_dir).get(scope, template_id) == updated
assert store.get(other_scope, template_id)["name"] == "Other host"
assert stat.S_IMODE(store.file.stat().st_mode) == 0o600