1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 17:06:09 +00:00

fix(instances): an owner is shown no host files, in the API or on the delete page

The VM page shows an owner who is not a superuser no host files, but
the REST API gave them each disk's and CD-ROM's path, image and pool,
backing files, the firmware loader and the NVRAM path, and the delete
confirmation listed the disks' paths. Both now give an owner a disk's
device, size and settings only, as the VM page does.
This commit is contained in:
catborise 2026-11-12 16:34:59 +03:00
parent f18be7c33e
commit 45196d7911
6 changed files with 62 additions and 9 deletions

View file

@ -12,6 +12,10 @@ class InstanceSerializer(serializers.ModelSerializer):
fields = ["id", "compute", "name", "uuid", "is_template", "created", "drbd"]
# what a VM's device dicts tell of the host: its files and pools
HOST_KEYS = {"image", "storage", "path", "backing_file", "loader"}
class InstanceDetailsSerializer(serializers.ModelSerializer):
networks = serializers.SerializerMethodField()
@ -24,14 +28,28 @@ class InstanceDetailsSerializer(serializers.ModelSerializer):
found = {}
return [{**nic, **dict(zip(("ipv4", "ipv6"), found.get(nic["mac"], (None, None))))} for nic in instance.networks]
def superuser(self):
request = self.context.get("request")
return bool(request and request.user.is_superuser)
def get_fields(self):
fields = super().get_fields()
# the host's ISO images are a superuser's, as on the VM page
request = self.context.get("request")
if not (request and request.user.is_superuser):
del fields["media_iso"]
# the host's files are a superuser's, as on the VM page: its ISO images and the VM's NVRAM file
if not self.superuser():
del fields["media_iso"], fields["nvram"]
return fields
def to_representation(self, instance):
data = super().to_representation(instance)
if not self.superuser(): # a disk's, CD-ROM's and firmware's file and pool too
for field in ("disks", "media"):
data[field] = [{key: value for key, value in device.items() if key not in HOST_KEYS}
for device in data[field]]
data["firmware"] = {key: value for key, value in data["firmware"].items() if key not in HOST_KEYS}
for snap in data["snapshots"]: # the disks a revert detaches, by device
snap["detaches"] = [{"dev": disk["dev"]} for disk in snap.get("detaches", [])]
return data
class Meta:
model = Instance
fields = [

View file

@ -33,7 +33,7 @@
<p class="small fw-semibold mb-1">{% trans "Disks" %}</p>
<ul class="small ps-3">
{% for disk in instance.config_disks %}
<li><strong>{{ disk.dev }}</strong> <span class="text-break">{{ disk.path|default:_("no file") }}</span></li>
<li><strong>{{ disk.dev }}</strong>{% if request.user.is_superuser %} <span class="text-break">{{ disk.path|default:_("no file") }}</span>{% endif %}</li>
{% endfor %}
</ul>
{% endif %}

View file

@ -93,7 +93,7 @@
<form action="{% url 'instances:revert_external_snapshot' instance.id %}" method="post">{% csrf_token %}{% submission_key %}
<input type="hidden" name="name" value="{{ snap.name }}">
<button type="submit" class="btn btn-sm btn-outline-secondary" name="revert_external_snapshot"
data-confirm="{% blocktrans with name=snap.name %}Revert to snapshot {{ name }}? Changes made since it are lost.{% endblocktrans %}{% if not snap.memory %}{% if instance.status == 1 %} {% trans "The VM is powered off and starts again from the snapshot's disks, as after a power cut." %}{% elif instance.status == 3 %} {% trans "The VM is powered off and comes back paused on the snapshot's disks." %}{% endif %}{% endif %}{% if snap.detaches %} {% trans 'These disks are detached; their writes since the current snapshot are discarded and their files are kept:' %} {% for d in snap.detaches %}{{ d.dev }} ({{ d.path }}){% if not forloop.last %}, {% endif %}{% endfor %}.{% endif %}{% if instance.nvram %} {% trans 'Firmware variables (NVRAM) are not restored.' %}{% endif %}"
data-confirm="{% blocktrans with name=snap.name %}Revert to snapshot {{ name }}? Changes made since it are lost.{% endblocktrans %}{% if not snap.memory %}{% if instance.status == 1 %} {% trans "The VM is powered off and starts again from the snapshot's disks, as after a power cut." %}{% elif instance.status == 3 %} {% trans "The VM is powered off and comes back paused on the snapshot's disks." %}{% endif %}{% endif %}{% if snap.detaches %} {% trans 'These disks are detached; their writes since the current snapshot are discarded and their files are kept:' %} {% for d in snap.detaches %}{{ d.dev }}{% if request.user.is_superuser %} ({{ d.path }}){% endif %}{% if not forloop.last %}, {% endif %}{% endfor %}.{% endif %}{% if instance.nvram %} {% trans 'Firmware variables (NVRAM) are not restored.' %}{% endif %}"
{% if busy or held %} disabled{% endif %}>{% trans "Revert" %}</button>
</form>
<form action="{% url 'instances:delete_external_snapshot' instance.id %}" method="post">{% csrf_token %}{% submission_key %}

View file

@ -50,6 +50,25 @@ class ApiParityTests(TestCase):
fields = InstanceDetailsSerializer(self.vm, context={"request": Request(user)}).fields
self.assertEqual("media_iso" in fields, shown, user)
def test_the_hosts_files_and_pools_are_a_superusers(self):
# the VM page shows an owner none of them: a disk is its device, size and settings
class Request:
def __init__(self, user):
self.user = user
read = {"disks": [{"dev": "vda", "size": 1, "image": "a.qcow2", "storage": "default", "path": "/pool/a.qcow2",
"backing_file": "/pool/base.qcow2"}],
"media": [{"dev": "sda", "image": "x.iso", "storage": "iso", "path": "/iso/x.iso"}],
"firmware": {"loader": "/usr/share/OVMF/OVMF_CODE.fd", "type": "pflash"},
"snapshots": [{"name": "s", "detaches": [{"dev": "vdb", "path": "/pool/b.qcow2"}]}, {"name": "i"}]}
with patch("rest_framework.serializers.ModelSerializer.to_representation", return_value=read):
owner = InstanceDetailsSerializer(self.vm, context={"request": Request(self.user)}).data
admin = InstanceDetailsSerializer(self.vm, context={"request": Request(self.admin)}).data
self.assertEqual(owner, {"disks": [{"dev": "vda", "size": 1}], "media": [{"dev": "sda"}], "firmware": {"type": "pflash"},
"snapshots": [{"name": "s", "detaches": [{"dev": "vdb"}]}, {"name": "i", "detaches": []}]})
self.assertEqual(admin, read)
self.assertNotIn("nvram", InstanceDetailsSerializer(self.vm, context={"request": Request(self.user)}).fields)
def test_a_flavor_is_at_least_one_of_each_and_has_its_id(self):
self.client.force_login(self.admin)
response = self.client.post("/api/v1/flavor/", {"label": "zero", "memory": 0, "vcpu": -1, "disk": 0},

View file

@ -240,15 +240,19 @@ class DestroyOrderTestCase(TransactionTestCase):
response = self.client.get(reverse("instances:destroy", args=[self.instance.id]))
self.assertEqual(b"Its TPM state is deleted" in response.content, shown)
def test_the_confirmation_page_names_the_host_only_to_whom_the_app_shows_hosts(self):
def test_the_confirmation_page_names_the_host_and_files_only_to_whom_the_app_shows_hosts(self):
owner = get_user_model().objects.create_user("destroy_owner", password="pw")
self.instance.userinstance_set.create(user=owner, is_delete=True)
for user, shown in ((self.admin, True), (owner, False)):
with self.subTest(user=user.username), patch("instances.models.wvmInstance"):
with self.subTest(user=user.username), patch("instances.models.wvmInstance") as wvm:
wvm.return_value.get_disk_devices.return_value = [{"dev": "vda", "path": "/pool/own.qcow2"}]
self.client.force_login(user)
response = self.client.get(reverse("instances:destroy", args=[self.instance.id]))
self.assertEqual(response.status_code, 200)
self.assertEqual("on destroy-compute" in response.content.decode(), shown)
page = response.content.decode()
self.assertEqual("on destroy-compute" in page, shown)
self.assertIn("<strong>vda</strong>", page)
self.assertEqual("/pool/own.qcow2" in page, shown)
def test_the_confirmation_page_of_a_paused_vm_offers_the_form(self):
with patch("instances.models.wvmInstance") as wvm:

View file

@ -7,12 +7,14 @@ from unittest.mock import PropertyMock, patch
import libvirt
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.contrib.messages import get_messages
from django.test import TestCase
from django.urls import reverse
from lxml import html as lxml_html
from vrtManager import util
from accounts.models import UserInstance
from appsettings.models import AppSettings
from appsettings.settings import get_settings
from computes.models import Compute
@ -136,6 +138,16 @@ class SnapshotTabTestCase(TestCase):
self.assertIn("vdb (/pool/later.qcow2)", text)
self.assertIn("NVRAM", text)
def test_an_owner_is_told_detached_disks_by_device(self):
owner = get_user_model().objects.create_user("snap_owner", "o@example.com", "pw")
owner.user_permissions.add(Permission.objects.get(codename="snapshot_instances"))
UserInstance.objects.create(user=owner, instance=self.instance, is_change=True)
self.client.force_login(owner)
doc = self.page(external=[self.snap("e", detaches=[{"dev": "vdb", "path": "/pool/later.qcow2"}])])
[button] = doc.xpath("//button[@name='revert_external_snapshot']")
self.assertIn("vdb.", button.get("data-confirm"))
self.assertNotIn("/pool/later.qcow2", button.get("data-confirm"))
def test_each_kind_is_listed_once_per_page(self):
doc = self.page(internal=[self.snap("i")], external=[self.snap("e")])
flags = sorted(c.args[0] for c in self.proxy.get_snapshot.call_args_list)