PANEL UPDATE网站更新
从当前项目的私有 Gitea 仓库检查并安装新版本。
diff --git a/static/styles.css b/static/styles.css
index 28ec6e21..3e586718 100644
--- a/static/styles.css
+++ b/static/styles.css
@@ -142,7 +142,7 @@ tbody tr:hover{background:#fcfefe}
.workspace-form-page{width:min(100%,900px);margin:0 auto 48px}.workspace-form-back{padding-left:0;margin-bottom:15px;min-height:34px}.workspace-form-heading{margin-bottom:22px}.workspace-form-heading h1{margin-top:8px}.workspace-form-card{overflow:hidden}.workspace-form-body{padding:28px clamp(22px,3vw,36px) 32px}.workspace-form-actions{display:flex;justify-content:flex-end;flex-wrap:wrap;gap:10px;padding:18px clamp(22px,3vw,36px);border-top:1px solid #edf1f5;background:#fbfdfe}.workspace-form-actions .button{min-width:120px}.workspace-form-body>.form-error{margin:18px 0 0}
.form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px 17px}.field.full{grid-column:1/-1}.field label{display:block}.field label span{color:#dc5965}.field small{display:block;color:#a1adbb;font-size:10px;margin-top:7px;line-height:1.5}.field select{appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 24 24' fill='none' stroke='%2393a1ae' stroke-width='2'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 12px center;padding-right:35px}
.create-source-picker{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;border:0;padding:0;margin:0 0 23px;min-width:0}.create-source-picker legend{color:#34445a;font-size:13px;font-weight:700;padding:0;margin-bottom:10px}.create-source-picker label{position:relative;display:block;cursor:pointer}.create-source-picker input{position:absolute;opacity:0;width:1px;height:1px}.create-source-picker label span{display:block;border:1px solid #dce4eb;border-radius:9px;padding:12px 14px;min-height:65px;background:#fff}.create-source-picker input:checked+span{border-color:#3bb5bc;background:#effafa;box-shadow:0 0 0 2px rgba(20,166,175,.08)}.create-source-picker input:focus-visible+span{outline:3px solid rgba(18,166,176,.22);outline-offset:2px}.create-source-picker strong{display:block;color:#334a5f;font-size:12px}.create-source-picker small{display:block;color:#8999a8;font-size:10px;margin-top:5px}
-.template-import{border:1px solid #e0e9ee;border-radius:9px;margin-top:12px;background:#fbfdfd}.template-import summary{cursor:pointer;padding:11px 13px;color:#148c98;font-size:11px;font-weight:700}.template-import-fields{display:grid;gap:13px;padding:2px 13px 14px}.template-import-fields .field input{height:42px}.template-import-fields .form-error{margin:0}.template-import-fields .button{justify-self:start}.template-import-status{margin:0;color:#317c85;font-size:11px;line-height:1.6}
+.template-field-label{display:block;color:#34445a;font-size:13px;font-weight:700;margin-bottom:10px}.template-field-label span{color:#dc5965}.template-catalog{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:14px}.template-catalog-empty{grid-column:1/-1;margin:0;padding:17px;border:1px dashed #cbdbe3;border-radius:10px;background:#f8fbfc;color:#698094;font-size:12px}.template-family-card{min-width:0;border:1px solid #dce7ec;border-radius:12px;background:#fff;overflow:hidden}.template-family-card[open]{border-color:#46b6ba;box-shadow:0 0 0 2px rgba(20,166,175,.07)}.template-family-summary{display:flex;align-items:center;flex-direction:column;gap:9px;min-height:153px;padding:20px 13px 13px;cursor:pointer;text-align:center;list-style:none}.template-family-summary::-webkit-details-marker{display:none}.template-family-summary:focus-visible{outline:3px solid rgba(18,166,176,.22);outline-offset:-3px}.template-family-summary strong{color:#30465a;font-size:13px}.template-family-icon{display:flex;align-items:center;justify-content:center;width:65px;height:65px;border-radius:17px;background:linear-gradient(145deg,#2a6385,#173d58);color:#fff;font-size:31px;font-weight:800;box-shadow:0 6px 16px rgba(24,68,90,.15)}.template-family-icon.alma{background:conic-gradient(from 35deg,#32bac4 0 28%,#5277cb 28% 51%,#e7ad54 51% 72%,#3ea67b 72% 100%);border:5px solid #f5faf9;color:#fff;text-shadow:0 1px 4px rgba(8,45,65,.35)}.template-family-arrow{color:#258f9b;font-size:20px;line-height:1;transition:transform .2s}.template-family-card[open] .template-family-arrow{transform:rotate(180deg)}.template-versions{display:grid;gap:7px;padding:12px;border-top:1px solid #e7edf2;background:#fbfdfd}.template-version-option{width:100%;display:grid;gap:3px;padding:11px 12px;border:1px solid #dee8ed;border-radius:8px;background:#fff;text-align:left;color:#344e60}.template-version-option strong{font-size:12px}.template-version-option small{margin:0;color:#899cac;font-size:10px;overflow-wrap:anywhere}.template-version-option[aria-pressed="true"]{border-color:#35afb7;background:#eaf8f8;box-shadow:0 0 0 2px rgba(20,166,175,.09)}.template-version-option:hover{border-color:#48b6bd}.template-admin-grid{display:grid;grid-template-columns:minmax(0,.9fr) minmax(0,1.1fr);align-items:start;gap:19px}.template-admin-grid .host-card{min-width:0}.template-admin-grid .form-stack .button{align-self:flex-start}.template-field-help{display:block;margin:-16px 0 19px;color:#8b9bab;font-size:11px;line-height:1.55}.template-import-status{margin:0 0 14px;padding:10px 12px;border-radius:8px;background:#edf8f8;color:#317c85;font-size:11px;line-height:1.6}.template-admin-list{display:grid;gap:10px}.template-admin-list>.muted{margin:0}.template-admin-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:9px 11px;align-items:end;padding:14px;border:1px solid #e0e9ee;border-radius:10px;background:#fbfdfd}.template-admin-row-heading{grid-column:1/-1;display:flex;align-items:center;gap:9px;margin-bottom:3px;color:#34495c;font-size:12px}.template-admin-icon{display:flex;align-items:center;justify-content:center;width:27px;height:27px;border-radius:7px;background:#e3f6f3;color:#138d8f;font-weight:800}.template-admin-row label{grid-column:1/-1;margin:0;color:#75899b;font-size:11px;font-weight:700}.template-admin-row input{width:100%;min-width:0;height:37px;padding:0 10px;border:1px solid #dce4eb;border-radius:7px;background:#fff;color:#20364a;font-size:12px}.template-admin-row .button{min-height:37px}.template-admin-row .form-error{grid-column:1/-1;margin:0}
.cloud-fields{grid-column:1/-1;border-top:1px solid #e7edf2;padding-top:18px}.cloud-fields-heading{margin-bottom:17px}.cloud-fields-heading strong{display:block;color:#34445a;font-size:13px}.cloud-fields-heading small{display:block;color:#8798a7;font-size:10px;line-height:1.6;margin-top:6px}
.vm-auto-public-pool{display:grid;gap:5px;margin:0 0 18px;padding:13px 15px;border:1px solid #cce9e0;border-radius:9px;background:#f0fbf8}.vm-auto-public-pool strong{font-size:12px;color:#217d6e}.vm-auto-public-pool span{font-size:11px;line-height:1.6;color:#5b837a}.vm-cloud-auth-fields{margin-top:18px}
.input-suffix{position:relative}.input-suffix input{padding-right:48px}.input-suffix span{position:absolute;right:13px;top:13px;color:#97a4b2;font-size:12px}
@@ -158,6 +158,7 @@ tbody tr:hover{background:#fcfefe}
@media(max-width:960px){.dashboard{display:block}.sidebar{position:relative;width:100%;height:65px;min-height:65px;padding:12px 24px}.sidebar-brand{padding:0}.sidebar-section-label,.sidebar-link,.sidebar-bottom{display:none}.admin-menu{display:block}.topbar{height:60px;padding:0 24px}.content{padding:30px 24px}.page-heading{margin-bottom:24px}}
@media(max-width:960px){.host-columns{grid-template-columns:1fr}.host-side-stack{grid-template-columns:repeat(2,minmax(0,1fr));align-items:start}.setup-layout{grid-template-columns:minmax(280px,36%) 1fr}}
@media(max-width:960px){.update-grid{grid-template-columns:1fr}}
+@media(max-width:960px){.template-admin-grid{grid-template-columns:1fr}}
@media(max-width:960px){.ssh-keys-grid{grid-template-columns:1fr}}
@media(max-width:960px){.vm-detail-grid{grid-template-columns:1fr}}
@media(max-width:740px){.vm-metrics-grid{grid-template-columns:1fr}.vm-metrics-heading{align-items:flex-start;flex-direction:column}.vm-metric-plot{height:190px}}
@@ -167,6 +168,7 @@ tbody tr:hover{background:#fcfefe}
@media(max-width:510px){.topbar{padding:0 17px}.content{padding:25px 14px}.page-heading{padding:0 3px}.overview-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.stat-card{padding:13px 11px;min-height:112px}.stat-card>strong{font-size:23px}.stat-icon{display:none}.topbar-right{gap:4px}.topbar-user{font-size:11px}.breadcrumb{font-size:11px}.modal-backdrop{padding:10px}.modal-header,.modal-body{padding-left:19px;padding-right:19px}.modal-footer{padding:14px 19px}.form-grid{gap:15px 10px}.console-backdrop{padding:0}.console-modal{height:100vh;max-height:100vh;border-radius:0}.console-stage{flex:1;height:auto}.console-tools .button{display:none}.console-password{flex-wrap:wrap}.console-password input{flex:1;min-width:130px}}
@media(max-width:510px){.topbar-right{flex-wrap:nowrap;justify-content:flex-end;gap:5px;min-width:0}.topbar-user{min-width:0}.topbar-user #current-username{display:block;max-width:90px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.topbar-user .avatar{display:none}.topbar-right #logout-button{font-size:10px;padding:5px;min-height:28px}.breadcrumb{white-space:nowrap}.breadcrumb span{padding:0 5px}.update-versions{grid-template-columns:1fr}}
@media(max-width:510px){.create-source-picker,.cloud-fields>.form-grid{grid-template-columns:1fr}}
+@media(max-width:510px){.template-catalog{grid-template-columns:repeat(2,minmax(0,1fr));gap:9px}.template-family-summary{min-height:137px;padding:16px 9px 11px}.template-family-icon{width:55px;height:55px;font-size:27px}.template-versions{padding:8px}.template-version-option{padding:9px 8px}.template-admin-row{grid-template-columns:1fr}.template-admin-row .button{justify-self:start}}
@media(max-width:510px){.workspace-form-body{padding:22px 19px 25px}.workspace-form-actions{padding:15px 19px}.workspace-form-actions .button{flex:1 1 100%}.workspace-form-back{margin-bottom:10px}}
@media(max-width:510px){.host-public-pool>.form-grid{grid-template-columns:1fr}}
@media(max-width:510px){.register-code-row{flex-wrap:wrap}.register-code-row input{flex-basis:100%}.register-code-row .button{width:100%}.pending-user-row{align-items:flex-start;flex-direction:column}.pending-user-row .button{width:100%}.smtp-card .form-grid{grid-template-columns:1fr}}
diff --git a/tests/test_app.py b/tests/test_app.py
index 5622bbd0..f3ec13df 100644
--- a/tests/test_app.py
+++ b/tests/test_app.py
@@ -62,6 +62,10 @@ 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"
+)
HOST_BODY = {
"host": "vmhost.example.test", "port": 2222,
"private_key": "-----BEGIN OPENSSH PRIVATE KEY-----\ntest\n-----END OPENSSH PRIVATE KEY-----",
@@ -770,6 +774,40 @@ def test_cloud_template_import_job_and_create_dispatch(web):
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)):
+ 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_cloud_vm_root_login_supports_key_and_hashed_initial_password(web):
client, state, token, service, manager, _ = web
csrf = setup_admin(client, token)
diff --git a/tests/test_cloud_templates.py b/tests/test_cloud_templates.py
index 33d8d363..9b060298 100644
--- a/tests/test_cloud_templates.py
+++ b/tests/test_cloud_templates.py
@@ -16,7 +16,10 @@ from virsh_panel.cloud_templates import (
TemplateStore,
_RejectRedirects,
download_verified_image,
+ image_version_for,
+ template_id_for,
template_scope,
+ template_volume_name,
validate_image_url,
)
@@ -25,6 +28,29 @@ 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:
@@ -120,3 +146,36 @@ def test_template_catalog_is_private_and_scoped_to_host_and_disk_pool(tmp_path):
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
diff --git a/tests/test_database.py b/tests/test_database.py
index 0cff4aba..e0590eb6 100644
--- a/tests/test_database.py
+++ b/tests/test_database.py
@@ -153,6 +153,36 @@ def test_templates_are_isolated_by_host_scope_and_atomic_insert():
assert duplicate.value.status == 409
+def test_database_template_rename_persists_only_name_and_rejects_duplicate():
+ store = MemoryStore()
+ templates = DatabaseTemplateStore(store)
+ scope = "a" * 64
+ other_scope = "b" * 64
+ record = {
+ "id": "alma9-12345678-abcdef0123456789", "name": "AlmaLinux 9",
+ "os_family": "AlmaLinux", "os_version": "9", "sha256": "f" * 64,
+ "volume_name": "panel-template-alma9-12345678-abcdef0123456789.qcow2",
+ }
+ templates.add(scope, record)
+ templates.add(scope, {**record, "id": "second", "name": "Second"})
+ templates.add(other_scope, {**record, "name": "Other host"})
+
+ with pytest.raises(TemplateError) as duplicate_import:
+ templates.add(scope, {**record, "id": "third", "name": "ALMALINUX 9"})
+ assert duplicate_import.value.status == 409
+ with pytest.raises(TemplateError) as wrong_host:
+ templates.rename(other_scope, "second", "Missing")
+ assert wrong_host.value.status == 404
+ with pytest.raises(TemplateError) as duplicate_rename:
+ templates.rename(scope, record["id"], "second")
+ assert duplicate_rename.value.status == 409
+
+ updated = templates.rename(scope, record["id"], " 自定义名称 ")
+ assert updated == {**record, "name": "自定义名称"}
+ assert DatabaseTemplateStore(store).get(scope, record["id"]) == updated
+ assert templates.get(other_scope, record["id"])["name"] == "Other host"
+
+
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")
diff --git a/tests/test_libvirt_service.py b/tests/test_libvirt_service.py
index 262cc55e..edc351b3 100644
--- a/tests/test_libvirt_service.py
+++ b/tests/test_libvirt_service.py
@@ -1253,6 +1253,21 @@ class VMServiceTests(unittest.TestCase):
f"panel-seed-{reserved_uuid}.iso")
self.assertEqual(created["disks"][0]["capacity_gib"], 20)
+ def test_cloud_vm_accepts_almalinux_9_panel_template_volume(self):
+ service = self.cloud_service()
+ alma9_volume = "panel-template-alma9-12345678-0123456789abcdef.qcow2"
+ self.backend.pools["images"].volumes[alma9_volume] = FakeVolume(
+ self.backend.pools["images"], alma9_volume, capacity=2 * 1024**3,
+ )
+ with patch.object(self.service_module, "build_seed_iso", return_value=b"SEED",
+ create=True):
+ created = service.create_cloud_vm(
+ self.cloud_spec(os_name="AlmaLinux 9"), alma9_volume,
+ )
+ self.assertEqual(created["os_name"], "AlmaLinux 9")
+ self.assertEqual(self.backend.pools["images"].volumes["cloud-vm.qcow2"].cloned_from,
+ alma9_volume)
+
def test_cloud_vm_clones_template_and_uses_nonboot_seed_iso(self):
service = self.cloud_service()
created = self.create_cloud_vm(service, self.cloud_spec(os_name="AlmaLinux 10"))
diff --git a/tests/test_registration_http.py b/tests/test_registration_http.py
index 3b259377..0b6dbb81 100644
--- a/tests/test_registration_http.py
+++ b/tests/test_registration_http.py
@@ -24,6 +24,7 @@ except ModuleNotFoundError:
from tests.test_database_http import MemoryStore # noqa: E402
from virsh_panel import app as app_module # noqa: E402
+from virsh_panel.auth import hash_password # noqa: E402
from virsh_panel.config import Settings # noqa: E402
from virsh_panel.database import DatabasePanelState, DatabaseTemplateStore # noqa: E402
from virsh_panel.libvirt_service import VMError # noqa: E402
@@ -195,6 +196,84 @@ def _register(client: TestClient, address: str, username: str):
assert response.json() == {"registered": True, "approved": False}
+def test_template_rename_is_admin_only_and_ordinary_users_can_list(monkeypatch, tmp_path):
+ store = MemoryStore()
+ service = _Service()
+ monkeypatch.setattr(app_module, "make_components", lambda directory, *_: (
+ DatabasePanelState(directory, store, store.users), _Manager(),
+ DatabaseTemplateStore(store), store,
+ ))
+ monkeypatch.setattr(app_module, "MetricsCollector", _NoMetrics)
+ settings = Settings(
+ data_dir=tmp_path / "data",
+ static_dir=Path(__file__).resolve().parents[1] / "static",
+ )
+ app = app_module.create_app(settings, service_factory=lambda _profile: service)
+ token = (settings.data_dir / "setup-token").read_text(encoding="ascii").strip()
+ scope = template_scope(_Manager.profile)
+ template_id = "alma9-12345678-abcdef0123456789"
+ record = {
+ "id": template_id, "name": "AlmaLinux 9", "os_family": "AlmaLinux",
+ "os_version": "9", "sha256": "f" * 64,
+ "volume_name": "panel-template-alma9-12345678-abcdef0123456789.qcow2",
+ }
+ endpoint = f"/api/v1/vm-templates/{template_id}"
+
+ with TestClient(app, base_url=ORIGIN) as admin:
+ assert admin.patch(endpoint, json={"name": "Rename"}).status_code == 401
+ configured = admin.post("/api/v1/database/setup", json={
+ "host": "127.0.0.1", "port": 3306, "database": "virsh_panel",
+ "username": "panel", "password": "database-password", "setup_token": token,
+ })
+ assert configured.status_code == 200
+ created = admin.post("/api/v1/setup/admin", json={
+ "token": token, "username": "initial", "password": PASSWORD,
+ })
+ assert created.status_code == 200
+ admin_headers = {"X-CSRF-Token": created.json()["csrf_token"]}
+ templates = DatabaseTemplateStore(store)
+ templates.add(scope, record)
+ templates.add(scope, {**record, "id": "another", "name": "Other template"})
+ templates.add("b" * 64, {**record, "name": "Different host"})
+ assert admin.patch(endpoint, json={"name": "Rename"},
+ headers=admin_headers).status_code == 403
+ store.users.promote("initial")
+
+ store.set("test_user", "tenant", json.dumps({
+ "id": 2, "username": "tenant", "email": "tenant@example.test",
+ "password_hash": hash_password(PASSWORD), "admin": False,
+ "approved": True, "email_verified": True, "created_at": 100,
+ }))
+ with TestClient(app, base_url=ORIGIN) as tenant:
+ tenant_headers = _login(tenant, "tenant@example.test")
+ listed = tenant.get("/api/v1/vm-templates")
+ assert listed.status_code == 200
+ assert [row["id"] for row in listed.json()["templates"]] == [
+ template_id, "another",
+ ]
+ assert tenant.patch(endpoint, json={"name": "Hijack"},
+ headers=tenant_headers).status_code == 403
+ assert tenant.post("/api/v1/vm-templates/import", json={
+ "name": "Extra", "url": "https://invalid.example/image.qcow2",
+ "sha256": "a" * 64,
+ }, headers=tenant_headers).status_code == 403
+
+ assert admin.patch(endpoint, json={"name": "Rename"}).status_code == 403
+ assert admin.patch(endpoint, json={"name": "Other TEMPLATE"},
+ headers=admin_headers).status_code == 409
+ assert admin.patch(endpoint, json={"name": " "},
+ headers=admin_headers).status_code == 400
+ missing = admin.patch("/api/v1/vm-templates/missing", json={"name": "Missing"},
+ headers=admin_headers)
+ assert missing.status_code == 404
+ renamed = admin.patch(endpoint, json={"name": " AlmaLinux 9 Gold "},
+ headers=admin_headers)
+ assert renamed.status_code == 200
+ assert renamed.json()["template"] == {**record, "name": "AlmaLinux 9 Gold"}
+ assert DatabaseTemplateStore(store).get(scope, template_id) == renamed.json()["template"]
+ assert templates.get("b" * 64, template_id)["name"] == "Different host"
+
+
def test_registration_smtp_approval_and_per_user_vm_isolation(monkeypatch, tmp_path):
store = MemoryStore()
service = _Service()
diff --git a/tests/test_template_frontend.py b/tests/test_template_frontend.py
new file mode 100644
index 00000000..a7b42945
--- /dev/null
+++ b/tests/test_template_frontend.py
@@ -0,0 +1,134 @@
+"""Guard the administrator-only image catalog and card-based VM image picker."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from html.parser import HTMLParser
+from pathlib import Path
+
+import pytest
+
+
+STATIC = Path(__file__).resolve().parents[1] / "static"
+VOID_TAGS = {
+ "area", "base", "br", "col", "embed", "hr", "img", "input",
+ "link", "meta", "param", "source", "track", "wbr",
+}
+
+
+@dataclass(frozen=True)
+class Element:
+ tag: str
+ attrs: dict[str, str | None]
+ ancestor_ids: tuple[str, ...]
+
+
+class CatalogPageParser(HTMLParser):
+ def __init__(self) -> None:
+ super().__init__(convert_charrefs=True)
+ self.elements: list[Element] = []
+ self.stack: list[Element] = []
+
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ element = Element(
+ tag,
+ dict(attrs),
+ tuple(item.attrs["id"] for item in self.stack if item.attrs.get("id")),
+ )
+ self.elements.append(element)
+ if tag not in VOID_TAGS:
+ self.stack.append(element)
+
+ def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ self.handle_starttag(tag, attrs)
+ if tag not in VOID_TAGS:
+ self.stack.pop()
+
+ def handle_endtag(self, tag: str) -> None:
+ for index in range(len(self.stack) - 1, -1, -1):
+ if self.stack[index].tag == tag:
+ del self.stack[index:]
+ return
+
+
+@pytest.fixture(scope="module")
+def page() -> tuple[list[Element], dict[str, Element]]:
+ parser = CatalogPageParser()
+ parser.feed((STATIC / "index.html").read_text(encoding="utf-8"))
+ assert not parser.stack, "Unclosed HTML element in the dashboard page"
+ by_id = {element.attrs["id"]: element for element in parser.elements if element.attrs.get("id")}
+ assert len(by_id) == sum(bool(element.attrs.get("id")) for element in parser.elements)
+ return parser.elements, by_id
+
+
+def test_image_import_is_on_a_dedicated_admin_page(page) -> None:
+ _, by_id = page
+ workspace = by_id["template-workspace"]
+ assert "hidden" in workspace.attrs
+ assert "dashboard-view" in workspace.ancestor_ids
+
+ form = by_id["template-import-form"]
+ assert form.tag == "form"
+ assert "template-workspace" in form.ancestor_ids
+ for element_id in ("template-name", "template-url", "template-sha256", "template-import-button"):
+ assert "template-import-form" in by_id[element_id].ancestor_ids
+ assert "create-view" not in by_id[element_id].ancestor_ids
+ assert "reinstall-view" not in by_id[element_id].ancestor_ids
+
+ assert "template-workspace" in by_id["template-admin-list"].ancestor_ids
+ assert "template-import" not in by_id, "The old inline import details must be removed"
+
+
+@pytest.mark.parametrize(
+ ("form_id", "field_id", "catalog_id"),
+ [
+ ("create-form", "vm-template", "vm-template-catalog"),
+ ("reinstall-form", "reinstall-template", "reinstall-template-catalog"),
+ ],
+)
+def test_vm_image_selection_uses_cards_not_selects(
+ page, form_id: str, field_id: str, catalog_id: str
+) -> None:
+ elements, by_id = page
+ field = by_id[field_id]
+ catalog = by_id[catalog_id]
+ assert field.tag == "input"
+ assert field.attrs.get("type") == "hidden"
+ assert field.attrs.get("name") == "template_id"
+ assert form_id in field.ancestor_ids
+ assert catalog.tag == "div"
+ assert "template-catalog" in (catalog.attrs.get("class") or "").split()
+ assert form_id in catalog.ancestor_ids
+ assert not any(
+ element.tag == "select"
+ and element.attrs.get("name") == "template_id"
+ and form_id in element.ancestor_ids
+ for element in elements
+ )
+
+
+def test_catalog_renders_expandable_family_and_version_cards() -> None:
+ script = (STATIC / "app.js").read_text(encoding="utf-8")
+ assert 'makeElement("details", "template-family-card")' in script
+ assert 'makeElement("button", "template-version-option")' in script
+ assert 'option.dataset.templateId = id;' in script
+ assert 'option.setAttribute("aria-pressed"' in script
+ assert 'input.value = id;' in script
+
+
+def test_admin_only_catalog_navigation_and_rename_control() -> None:
+ script = (STATIC / "app.js").read_text(encoding="utf-8")
+ session_code = script.split("function applySession(session) {", 1)[1].split(
+ "async function continueAfterLogin", 1
+ )[0]
+ for element_id in ("template-settings-button", "template-settings-mobile-button"):
+ assert f'"{element_id}"' in session_code
+ assert 'byId(id).hidden = !state.admin;' in session_code
+
+ rename_code = script.split("function renderTemplateAdminList() {", 1)[1].split(
+ "function fillTemplateViews", 1
+ )[0]
+ assert 'makeElement("form", "template-admin-row")' in rename_code
+ assert 'name.type = "text";' in rename_code
+ assert 'method: "PATCH"' in rename_code
+ assert 'encodeURIComponent(id)' in rename_code
diff --git a/virsh_panel/app.py b/virsh_panel/app.py
index ae8c8c39..f3e551ef 100644
--- a/virsh_panel/app.py
+++ b/virsh_panel/app.py
@@ -24,8 +24,8 @@ from pydantic import BaseModel, ConfigDict, Field, SecretStr
from .auth import DatabaseSessionStore, LoginLimiter, Session, SessionStore, verify_password
from .cloud_init import _validate_guest_auth, generate_root_password, hash_root_password
from .cloud_templates import (
- TemplateError, TemplateStore, download_verified_image, template_id_for,
- template_scope, template_volume_name, validate_image_url, validate_template_name,
+ TemplateError, TemplateStore, download_verified_image, image_version_for, template_id_for,
+ template_scope, template_volume_name, validate_template_name,
)
from .config import Settings
from .console import ConsoleRelayError, relay_console
@@ -208,6 +208,12 @@ class ImportTemplateBody(BaseModel):
name: str = Field(min_length=1, max_length=64)
+class RenameTemplateBody(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ name: str = Field(min_length=1, max_length=64)
+
+
class ReinstallBody(BaseModel):
model_config = ConfigDict(extra="forbid")
@@ -1296,6 +1302,8 @@ def create_app(
record = {
"id": template_id,
"name": body.name,
+ "os_family": "AlmaLinux",
+ "os_version": image_version_for(body.url),
"sha256": body.sha256.lower(),
"volume_name": volume_name,
"virtual_size": virtual_size,
@@ -1326,17 +1334,21 @@ def create_app(
@app.post("/api/v1/vm-templates/import", status_code=202)
def import_template(body: ImportTemplateBody, _session: Session = Depends(require_admin_write)):
profile = current_profile()
- validate_image_url(body.url)
+ version = image_version_for(body.url)
name = validate_template_name(body.name)
body = body.model_copy(update={"name": name})
if not all(char in "0123456789abcdefABCDEF" for char in body.sha256):
raise TemplateError("SHA-256 校验值必须是十六进制")
scope = template_scope(profile)
- template_id = template_id_for(scope, body.sha256.lower())
+ template_id = template_id_for(scope, body.sha256.lower(), version)
with import_lock:
forbid_long_job_during_update()
- if any(row["id"] == template_id for row in templates.list(scope)):
+ existing_templates = templates.list(scope)
+ if any(row["id"] == template_id for row in existing_templates):
raise TemplateError("此云镜像已经导入", 409)
+ if any(row["name"].casefold() == name.casefold()
+ for row in existing_templates):
+ raise TemplateError("当前宿主机已有同名云镜像模板", 409)
if (scope, template_id) in pending_templates:
raise TemplateError("该云镜像正在导入", 409)
if pending_templates:
@@ -1356,6 +1368,15 @@ def create_app(
LOG.info("cloud template import queued: job=%s admin=%s", job_id, _session.username)
return {"job_id": job_id, "status": "running"}
+ @app.patch("/api/v1/vm-templates/{template_id}")
+ def rename_template(template_id: str, body: RenameTemplateBody,
+ _session: Session = Depends(require_admin_write)):
+ scope = template_scope(current_profile())
+ with import_lock:
+ if pending_templates:
+ raise TemplateError("云镜像正在导入,请稍后修改模板名称", 409)
+ return {"template": templates.rename(scope, template_id, body.name)}
+
@app.get("/api/v1/vm-templates/import-jobs/{job_id}")
def import_job(job_id: str, _session: Session = Depends(require_admin)):
scope = template_scope(current_profile())
diff --git a/virsh_panel/cloud_templates.py b/virsh_panel/cloud_templates.py
index 195f8880..63be707c 100644
--- a/virsh_panel/cloud_templates.py
+++ b/virsh_panel/cloud_templates.py
@@ -24,8 +24,8 @@ MAX_VIRTUAL_BYTES = 4096 * 1024**3
MAX_DOWNLOAD_SECONDS = 3600
GIB = 1024**3
IMAGE_PATH = re.compile(
- r"/almalinux/10/cloud/x86_64/images/"
- r"AlmaLinux-10-GenericCloud-[A-Za-z0-9._-]+\.x86_64\.qcow2\Z"
+ r"/almalinux/(?P9|10)/cloud/x86_64/images/"
+ r"AlmaLinux-(?P=version)-GenericCloud-[A-Za-z0-9._-]+\.x86_64\.qcow2\Z"
)
SHA256_RE = re.compile(r"[0-9a-fA-F]{64}\Z")
@@ -67,24 +67,34 @@ def validate_image_url(url: str) -> str:
if (parsed.scheme != "https" or parsed.hostname != "repo.almalinux.org"
or port not in (None, 443) or parsed.username or parsed.password
or parsed.query or parsed.fragment or not IMAGE_PATH.fullmatch(parsed.path)):
- raise TemplateError("仅支持 AlmaLinux 官方仓库的 10 x86_64 GenericCloud qcow2 镜像")
+ raise TemplateError("仅支持 AlmaLinux 官方仓库的 9/10 x86_64 GenericCloud qcow2 镜像")
return url
+def image_version_for(url: str) -> str:
+ """Derive the OS major version from an already restricted official URL."""
+ validate_image_url(url)
+ match = IMAGE_PATH.fullmatch(urlsplit(url).path)
+ assert match is not None
+ return match.group("version")
+
+
def validate_template_name(name: str) -> str:
if not isinstance(name, str) or not 1 <= len(name.strip()) <= 64:
raise TemplateError("模板名称应为 1 至 64 个字符")
- if any(ord(char) < 32 for char in name):
+ if any(ord(char) < 32 or ord(char) == 127 for char in name):
raise TemplateError("模板名称不能包含控制字符")
return name.strip()
-def template_id_for(scope: str, digest: str) -> str:
- return f"alma10-{scope[:8]}-{digest[:16]}"
+def template_id_for(scope: str, digest: str, version: str = "10") -> str:
+ if version not in ("9", "10"):
+ raise TemplateError("云镜像系统版本无效")
+ return f"alma{version}-{scope[:8]}-{digest[:16]}"
def template_volume_name(template_id: str) -> str:
- if not re.fullmatch(r"alma10-[0-9a-f]{8}-[0-9a-f]{16}", template_id):
+ if not re.fullmatch(r"alma(?:9|10)-[0-9a-f]{8}-[0-9a-f]{16}", template_id):
raise TemplateError("模板标识无效")
return f"panel-template-{template_id}.qcow2"
@@ -234,6 +244,27 @@ class TemplateStore:
if any(item.get("scope") == scope and item.get("id") == record["id"]
for item in data["templates"]):
raise TemplateError("此云镜像已导入", 409)
+ if any(item.get("scope") == scope
+ and item.get("name", "").casefold() == record["name"].casefold()
+ for item in data["templates"]):
+ raise TemplateError("当前宿主机已有同名云镜像模板", 409)
data["templates"].append({**record, "scope": scope})
self._write(data)
return record
+
+ def rename(self, scope: str, template_id: str, name: str) -> dict:
+ name = validate_template_name(name)
+ with self._locked():
+ data = self._read()
+ target = next((record for record in data["templates"]
+ if record.get("scope") == scope and record.get("id") == template_id),
+ None)
+ if target is None:
+ raise TemplateError("模板不存在或不属于当前宿主机", 404)
+ if any(record.get("scope") == scope and record.get("id") != template_id
+ and record.get("name", "").casefold() == name.casefold()
+ for record in data["templates"]):
+ raise TemplateError("当前宿主机已有同名云镜像模板", 409)
+ target["name"] = name
+ self._write(data)
+ return {key: value for key, value in target.items() if key != "scope"}
diff --git a/virsh_panel/database.py b/virsh_panel/database.py
index 4d0c13ac..6561f0bd 100644
--- a/virsh_panel/database.py
+++ b/virsh_panel/database.py
@@ -33,7 +33,7 @@ try:
except ImportError: # Allows package tooling to import without optional DB extras.
pymysql = None
-from .cloud_templates import TemplateError
+from .cloud_templates import TemplateError, validate_template_name
from .panel_state import PanelState, SetupError, _USERNAME
from .remote_host import (
LIBVIRT_URI,
@@ -543,11 +543,27 @@ class DatabaseTemplateStore:
if not isinstance(record, dict) or not isinstance(record.get("id"), str):
raise TemplateError("模板记录无效")
key = f"{scope}:{record['id']}"
+ if any(row.get("id") != record["id"]
+ and row.get("name", "").casefold() == record["name"].casefold()
+ for row in self.list(scope)):
+ raise TemplateError("当前宿主机已有同名云镜像模板", 409)
if not self.store.insert("template", key, json.dumps(
record, ensure_ascii=False, separators=(",", ":"))):
raise TemplateError("此云镜像已导入", 409)
return record
+ def rename(self, scope: str, template_id: str, name: str) -> dict:
+ name = validate_template_name(name)
+ record = self.get(scope, template_id)
+ if any(row.get("id") != template_id
+ and row.get("name", "").casefold() == name.casefold()
+ for row in self.list(scope)):
+ raise TemplateError("当前宿主机已有同名云镜像模板", 409)
+ updated = {**record, "name": name}
+ self.store.set("template", f"{scope}:{template_id}", json.dumps(
+ updated, ensure_ascii=False, separators=(",", ":")))
+ return updated
+
class DatabaseStagedHost(StagedHost):
def __init__(self, staged: StagedHost, wrapper_path: Path,
diff --git a/virsh_panel/libvirt_service.py b/virsh_panel/libvirt_service.py
index b18a7ae6..80633bb4 100644
--- a/virsh_panel/libvirt_service.py
+++ b/virsh_panel/libvirt_service.py
@@ -32,7 +32,7 @@ GIB = 1024**3
PANEL_NS = "urn:virsh-panel:1"
NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,62}\Z")
BRIDGE_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,14}\Z")
-TEMPLATE_VOLUME_RE = re.compile(r"panel-template-alma10-[0-9a-f]{8}-[0-9a-f]{16}\.qcow2\Z")
+TEMPLATE_VOLUME_RE = re.compile(r"panel-template-alma(?:9|10)-[0-9a-f]{8}-[0-9a-f]{16}\.qcow2\Z")
_CREATE_LOCK = threading.RLock()
REINSTALL_SHUTDOWN_TIMEOUT = 120
REINSTALL_SHUTDOWN_POLL_INTERVAL = 1