1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-03 01:16:10 +00:00

fix(instances): the API tells a VM's fault reason; doc/permissions.md as the code is

An authorization sweep of everything added since 2026-11-09 (tags, Balance,
maintenance, Bulk Migrate, volume download, protection, disk I/O limits,
crash action, bulk power/snapshot/tag, backup targets, schedules, verify and
restores, unlock and OTP reset) as a stranger, staff, a view_instances
auditor, a flagless owner and an owner with every flag found no gap.

- the VM details of the API carry state_reason when a fault put the VM in
  its state, as the VM page tells it: libvirt's state and reason codes of
  one read and the reason in the request's language; null otherwise. A
  script watching the API can tell a VM a full storage paused from one
  paused by hand, in any language
- the bulk actions name a refused VM to whoever sees it (a view_instances
  auditor too), and a bulk snapshot no longer tells one who does not see a
  VM that it is a template (_visible_vms, one filter for the three)
- doc/permissions.md: creating a VM and the VM report, host devices, video,
  RNG, TPM, the crash and hang action, disk I/O limits, disk moves and
  protection are a superuser's, so are verifying a backup, restoring one
  disk, backing up a template and the backup API; deleting a VM takes its
  disk files when chosen; notes on bulk actions, the Jobs page, the address
  search, API tokens and LDAP passwords
This commit is contained in:
catborise 2026-11-23 08:01:04 +03:00
parent 72f5c544ee
commit 36635eb450
6 changed files with 61 additions and 12 deletions

View file

@ -9,11 +9,12 @@ WebVirtCloud combines three kinds of access rights:
- `instances.snapshot_instances` — may create, revert and delete snapshots of VMs they may change.
- `instances.backup_instances` — may back up the VMs they may change (see the table).
- `instances.passwordless_console` — the console page fills in the VNC password automatically, and the `.vv` file holds it (ticked by default on the Users page's new-user form; a user made otherwise, such as from LDAP, does not get it).
- `accounts.change_password` — may change their own password.
- `accounts.change_password` — may change their own password (a local one; LDAP users change theirs in LDAP).
- **Per-VM ownership** (an owner entry for a user on a VM, managed by a superuser on the VM's page) with three flags: `is_change`, `is_delete`, `is_vnc`. An owner without flags may see, start and stop the VM and open its console.
| Action on a VM | Superuser | Owner | Owner flag / permission needed | `view_instances` only |
|---|---|---|---|---|
| Create a VM; the VM report (Excel) | ✅ | ❌ | — | ❌ |
| See the VM (list, detail) | ✅ | ✅ | — | ✅ |
| Start, shut down, power cycle, force off | ✅ | ✅ | — | ❌ |
| Open the console (noVNC or, when it is on, the serial console; `.vv` file for virt-viewer, VDI URL) | ✅ | ✅ | — | ❌ |
@ -21,12 +22,13 @@ WebVirtCloud combines three kinds of access rights:
| Change console settings (type, VNC password, keymap) | ✅ | ✅ | `is_change` and `is_vnc`; the listen address, and removing the password of a console that listens beyond localhost, are a superuser's; nobody's on a template | ❌ |
| Snapshots | ✅ | ✅ | `is_change` and `instances.snapshot_instances` | ❌ |
| Clone | ✅ | ✅ | `is_change` and `instances.clone_instances` (templates: viewing the template is enough) | templates only, with `instances.clone_instances` |
| Delete the VM | ✅ | ✅ | `is_delete` | ❌ |
| Delete the VM, with its disk files when chosen | ✅ | ✅ | `is_delete` | ❌ |
| Disks and media (add, attach, edit, detach, delete volumes; CD-ROM/ISO) | ✅ | ❌ | — | ❌ |
| Network interfaces, boot options, vCPU hotplug, autostart, guest agent, suspend/resume, migrate, raw XML, owners | ✅ | ❌ | — | ❌ |
| Network interfaces, host devices (PCI/USB), boot options, vCPU hotplug, autostart, guest agent, video, RNG, TPM, crash and hang action, disk I/O limits, suspend/resume, migrate, disk moves, protection, raw XML, owners | ✅ | ❌ | — | ❌ |
| Set tags (owners and `view_instances` see them) | ✅ | ❌ | — | ❌ |
| Backups: back up (within the backup quota), restore over the VM or as a new VM (within the VM quota), into and from targets open to VM owners | ✅ | ✅ | `is_change` and `instances.backup_instances` | ❌ |
| Delete a backup one took by hand (not a schedule's) on a target open to VM owners | ✅ | ✅ | `instances.backup_instances` (ownership not needed) | ❌ |
| Verify a backup; restore one of its disks as a new volume | ✅ | ❌ | — | ❌ |
| Backup targets and schedules | ✅ | ❌ | — | ❌ |
Notes:
@ -35,5 +37,9 @@ Notes:
- `is_staff` gives no access to VMs and does not reveal console settings or VNC passwords by itself.
- A VM an administrator paused stays paused for its owners: their power actions on it are refused.
- A protected VM (a superuser's setting on its Settings tab) is neither deleted nor restored over, by anyone, until the protection is turned off.
- A template VM is changed (resize, root password, SSH keys, title and description, snapshots) only by superusers and by staff owners with `is_change`, and deleted only by superusers and staff owners with `is_delete`; other owners keep view, console and power (power on and power cycle of a template are refused with a warning). Cloning a template needs only view access and `instances.clone_instances`.
- The VM list's bulk start, shut down, force off and snapshot follow the rows above for each chosen VM (templates take no bulk snapshot); bulk tagging is a superuser's.
- The Jobs page shows a user the jobs they started; superusers see every job.
- Finding VMs by IP or MAC address searches a user's own VMs; superusers and `view_instances` users search every host.
- An API token acts with its user's rights: the API allows what the pages allow, but its backup endpoints are a superuser's.
- A template VM is changed (resize, root password, SSH keys, title and description, snapshots) only by superusers and by staff owners with `is_change`, deleted only by superusers and staff owners with `is_delete`, and backed up only by superusers; other owners keep view, console and power (power on and power cycle of a template are refused with a warning). Cloning a template needs only view access and `instances.clone_instances`.
- On VM pages, users without ownership or `view_instances` get **404** (the VM's existence is not revealed), and users who can see a VM but lack the right for an action get **403**. Superuser-only pages answer **403** to everyone else; the console page answers **403** both for a missing VM and for a VM the user may not open.

View file

@ -2,6 +2,7 @@ from computes.api.serializers import TAGS
from computes.models import Compute
from django.conf import settings
from instances.models import Flavor, Instance
from instances.states import REASONS
from instances.utils import nic_macs
from libvirt import libvirtError
from rest_framework import serializers
@ -22,8 +23,18 @@ HOST_KEYS = {"image", "storage", "path", "backing_file", "loader"}
class InstanceDetailsSerializer(serializers.ModelSerializer):
networks = serializers.SerializerMethodField()
state_reason = serializers.SerializerMethodField()
tags = serializers.SlugRelatedField(**TAGS)
def get_state_reason(self, instance) -> dict | None:
"""When a fault put the VM in its state (a disk error, a guest crash, its
watchdog; instances.states.REASONS): libvirt's state and reason codes of
one read (virDomainGetState) and the reason in the request's language;
else null."""
read = instance.state_and_reason
text = REASONS.get(read)
return None if text is None else {"state": read[0], "reason": read[1], "text": str(text)}
def get_networks(self, instance) -> list[dict]:
"""Each NIC with its addresses (None: none known), which the VM page
reads after it loads (views.nic_addresses)."""
@ -61,6 +72,7 @@ class InstanceDetailsSerializer(serializers.ModelSerializer):
"id",
"compute",
"status",
"state_reason",
"uuid",
"name",
"tags",

View file

@ -69,6 +69,16 @@ class ApiParityTests(TestCase):
self.assertEqual(admin, read)
self.assertNotIn("nvram", InstanceDetailsSerializer(self.vm, context={"request": Request(self.user)}).fields)
def test_the_details_tell_why_a_fault_paused_or_stopped_the_vm(self):
# as the VM page: a VM a full storage paused is told from one paused by hand
self.client.force_login(self.user)
for read, told in (([libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_PAUSED_IOERROR],
{"state": 3, "reason": 5, "text": "Paused by a disk error"}),
([libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_PAUSED_USER], None)):
with self.subTest(read=read), patch("instances.models.wvmInstance") as wvm:
wvm.return_value.get_state.return_value = read
self.assertEqual(InstanceDetailsSerializer(self.vm).get_state_reason(Instance.objects.get(pk=self.vm.pk)), told)
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

@ -8,6 +8,7 @@ from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.contrib.messages import get_messages
from django.core.exceptions import PermissionDenied
from django.test import TransactionTestCase
@ -182,6 +183,13 @@ class BulkPowerTestCase(TransactionTestCase):
self.assertEqual(said, ["a chosen VM: you may not power it now", "1 VM is queued; the Jobs page follows it."])
self.assertEqual(Operation.objects.get().params["instance"], self.vms[0].pk)
def test_an_auditor_is_refused_by_the_name_of_a_vm_they_see(self):
auditor = get_user_model().objects.create_user("bp-auditor", password="pw")
auditor.user_permissions.add(Permission.objects.get(codename="view_instances"))
_response, said = self.submit("start", self.vms[:1], user=auditor)
self.assertEqual(said, ["bp-vm1: you may not power it now"])
self.assertFalse(Operation.objects.exists())
def test_a_refusal_goes_back_to_the_list_it_came_from(self):
host_list = reverse("instances", args=[self.vms[0].compute_id])
for given, back in ((host_list, host_list), ("?page=2", reverse("instances:index")), ("//example.com/", reverse("instances:index")),

View file

@ -83,6 +83,15 @@ class BulkSnapshotTestCase(TestCase):
self.assertEqual(said, ["bs-vm1: The VM has internal snapshots; external snapshots cannot be mixed with them"])
self.assertFalse(Operation.objects.exists())
def test_a_vm_one_does_not_see_is_not_told_a_template(self):
# a template and a VM of no owner are refused alike: neither tells what it is
Instance.objects.filter(pk=self.vms[1].pk).update(is_template=True)
stranger = get_user_model().objects.create_user("bs-stranger", password="pw")
stranger.user_permissions.add(Permission.objects.get(codename="snapshot_instances"))
_response, said = self.post("s1", self.vms, user=stranger)
self.assertEqual(said, ["a chosen VM: you may not snapshot it"] * 2)
self.assertFalse(Operation.objects.exists())
def test_the_box_is_for_one_who_may_snapshot_a_listed_vm(self):
owner = get_user_model().objects.create_user("bs-owner2", password="pw")
owner.user_permissions.add(Permission.objects.get(codename="snapshot_instances"))

View file

@ -779,9 +779,7 @@ def _queue_each(request, vms, kind, raw, refused):
A VM refused (refused: the words, with %(vm)s), gone or held by another job is named, if the
user may see it; the others are queued. One key per VM: a resent form queues none twice."""
key = request.POST.get("submission_key", "")
names = dict(Instance.objects.filter(pk__in=vms).values_list("pk", "name"))
seen = names if request.user.is_superuser else dict(Instance.objects.filter(
pk__in=vms, userinstance__user=request.user).values_list("pk", "name"))
seen = dict(_visible_vms(request, vms).values_list("pk", "name"))
queued = 0
for pk in vms:
name = seen.get(pk) or _("a chosen VM") # one the user may not see is not named
@ -840,7 +838,8 @@ def bulk_snapshot(request):
messages.error(request, error_text(request, err))
return _back_to_list(request)
# a template's page has no snapshot controls: none is taken here either
templates = set(Instance.objects.filter(pk__in=vms, is_template=True).values_list("pk", flat=True))
# of the VMs the user sees: one they do not see is refused as any other they may not snapshot
templates = set(_visible_vms(request, vms).filter(is_template=True).values_list("pk", flat=True))
for pk in templates:
messages.error(request, _("%(vm)s: a template's snapshots are not taken here") % {"vm": _visible_name(request, pk)})
if templates and not set(vms) - templates:
@ -849,12 +848,17 @@ def bulk_snapshot(request):
{"name": name, "external": True}, _("%(vm)s: you may not snapshot it"))
def _visible_vms(request, vms):
"""Those of the VMs (ids) the user may see: superusers and view_instances users every one."""
visible = Instance.objects.filter(pk__in=vms)
if request.user.is_superuser or request.user.has_perm("instances.view_instances"):
return visible
return visible.filter(userinstance__user=request.user)
def _visible_name(request, pk):
"""The VM's name if the user may see it, else words that do not name it."""
visible = Instance.objects.filter(pk=pk)
if not request.user.is_superuser:
visible = visible.filter(userinstance__user=request.user)
return visible.values_list("name", flat=True).first() or _("a chosen VM")
return _visible_vms(request, [pk]).values_list("name", flat=True).first() or _("a chosen VM")
def from_script(request):