1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-03 17:36:05 +00:00

fix(computes): the compute forms save their own kind, a password as typed, and say when the host is not reached

The kind of a compute came from a hidden form field: posted as another
number it was saved, and the edit page of that compute failed. Each form
now saves its own kind. Passwords lost their leading and trailing spaces
on the forms and the API, so a SASL password with one never worked. A
host name whose last label is all digits, such as an IPv4 address with a
trailing dot, was taken and libvirt could not resolve it. A host saved with
a wrong password or not answering was saved silently; the page now says
why the panel cannot connect to it.
This commit is contained in:
catborise 2026-11-12 08:47:32 +03:00
parent d682c4bc82
commit eb3bc69754
10 changed files with 139 additions and 69 deletions

View file

@ -10,6 +10,7 @@ class ComputeSerializer(serializers.ModelSerializer):
password = serializers.CharField(
style={"input_type": "password"},
write_only=True,
trim_whitespace=False,
required=False,
allow_blank=True,
allow_null=True,

View file

@ -13,6 +13,9 @@ class KeepSecretsMixin:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.instance.type = self.conn_type # the form's own kind, never a posted one
if "password" in self.fields:
self.fields["password"].strip = False # a SASL password may begin or end with a space
for name in ("password", "gstfsd_key"):
if name in self.fields and getattr(self.instance, name):
self.fields[name].widget.attrs["placeholder"] = _("Stored, leave empty to keep")
@ -31,56 +34,56 @@ SASL_LABELS = {"login": _("SASL login"), "password": _("SASL password")} | DETAI
class TcpComputeForm(KeepSecretsMixin, forms.ModelForm):
conn_type = CONN_TCP
kind = "TCP"
about = _("libvirt over TCP, with a SASL login")
hostname = forms.CharField(validators=[validate_hostname])
type = forms.IntegerField(widget=forms.HiddenInput, initial=CONN_TCP)
class Meta:
model = Compute
widgets = SECRET_WIDGETS
labels = SASL_LABELS
help_texts = DETAILS_HELP
fields = "__all__"
exclude = ["type"]
class SshComputeForm(KeepSecretsMixin, forms.ModelForm):
conn_type = CONN_SSH
kind = "SSH"
about = _("libvirt over SSH, with the panel's SSH key")
hostname = forms.CharField(validators=[validate_hostname], label=_("FQDN/IP"))
type = forms.IntegerField(widget=forms.HiddenInput, initial=CONN_SSH)
class Meta:
model = Compute
widgets = SECRET_WIDGETS
labels = {"login": _("SSH user")} | DETAILS
help_texts = DETAILS_HELP
exclude = ["password"]
exclude = ["password", "type"]
class TlsComputeForm(KeepSecretsMixin, forms.ModelForm):
conn_type = CONN_TLS
kind = "TLS"
about = _("libvirt over TLS, with certificates")
hostname = forms.CharField(validators=[validate_hostname])
type = forms.IntegerField(widget=forms.HiddenInput, initial=CONN_TLS)
class Meta:
model = Compute
widgets = SECRET_WIDGETS
labels = SASL_LABELS
help_texts = DETAILS_HELP
fields = "__all__"
exclude = ["type"]
class SocketComputeForm(KeepSecretsMixin, forms.ModelForm):
conn_type = CONN_SOCKET
kind = _("Local")
about = _("the libvirt of the host the panel runs on, by its socket")
hostname = forms.CharField(widget=forms.HiddenInput, initial="localhost")
type = forms.IntegerField(widget=forms.HiddenInput, initial=CONN_SOCKET)
class Meta:
model = Compute
widgets = SECRET_WIDGETS
labels = DETAILS
help_texts = DETAILS_HELP
fields = ["name", "details", "hostname", "type", "migration_address", "gstfsd_key"]
fields = ["name", "details", "hostname", "migration_address", "gstfsd_key"]

View file

@ -0,0 +1,38 @@
"""The compute forms: each saves its own kind of compute, keeps a password
as typed, and tells when the host saved cannot be reached."""
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from computes.models import Compute
from computes.tests.fakes import no_host_answers
class ComputeFormTests(TestCase):
def setUp(self):
self.client.force_login(get_user_model().objects.create_superuser("cf-admin", "cf@example.com", "pw"))
no_host_answers(self)
def add(self, **data):
return self.client.post(reverse("add_tcp_host"), {"name": "kvm1", "hostname": "192.0.2.1", "login": "wvc",
"password": "pw", "details": "", **data}, follow=True)
def test_a_posted_kind_is_not_taken(self):
self.add(type=99)
compute = Compute.objects.get(name="kvm1")
self.assertEqual(compute.type, 1)
self.assertEqual(self.client.get(reverse("compute_update", args=[compute.id])).status_code, 200)
def test_a_password_keeps_its_spaces(self):
self.add(password=" pass phrase ")
self.assertEqual(Compute.objects.get(name="kvm1").password, " pass phrase ")
compute = Compute.objects.get(name="kvm1")
self.client.patch(f"/api/v1/computes/{compute.id}/", {"password": " other "}, content_type="application/json")
compute.refresh_from_db()
self.assertEqual(compute.password, " other ")
def test_a_host_that_does_not_answer_is_saved_with_a_warning(self):
response = self.add()
self.assertTrue(Compute.objects.filter(name="kvm1").exists())
self.assertContains(response, "The host was saved, but the panel cannot connect to it: unreachable")

View file

@ -16,6 +16,13 @@ class HostnameValidatorTestCase(unittest.TestCase):
with self.subTest(value=value):
validate_hostname(value)
def test_rejects_what_is_neither_an_address_nor_a_name(self):
# a name's last label is never all digits: libvirt cannot resolve these
for value in ("192.0.2.10.", "192.0.2.1.5", "999.1.1.1"):
with self.subTest(value=value):
with self.assertRaises(ValidationError):
validate_hostname(value)
def test_rejects_uri_and_option_injection(self):
for value in (
"-x",

View file

@ -9,6 +9,12 @@ _hostname = re.compile(r"[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-
_login = re.compile(r"[A-Za-z0-9._][A-Za-z0-9._-]*")
def _is_name(value):
"""A host name: its last label is never all digits ("192.0.2.1." is no
address and no name, libvirt cannot resolve it)."""
return bool(_hostname.fullmatch(value)) and not value.rstrip(".").rsplit(".", 1)[-1].isdigit()
def validate_hostname(value):
"""An IPv4 address or a host name that goes safely into a libvirt
connection URI. No scheme, port, path, query, whitespace or IPv6 literal:
@ -19,7 +25,7 @@ def validate_hostname(value):
if ip_address(value).version == 4:
return
except ValueError:
if _hostname.fullmatch(value):
if _is_name(value):
return
raise ValidationError(_("Enter an IPv4 address or a host name, without a scheme, port or path"))
@ -42,7 +48,7 @@ def validate_migration_address(value):
if not getattr(ip_address(value), "scope_id", None):
return
except ValueError:
if _hostname.fullmatch(value):
if _is_name(value):
return
raise ValidationError(_("Enter an IP address or a host name, without a scheme or port"))

View file

@ -4,6 +4,7 @@ from contextlib import suppress
from admin.decorators import superuser_only
from django.conf import settings
from django.contrib import messages
from django.core import signing
from django.db import IntegrityError
from django.http import HttpResponse, JsonResponse
@ -155,6 +156,18 @@ def instances(request, compute_id):
)
# the form of each kind of compute, by Compute.type
FORMS = {form.conn_type: form for form in (TcpComputeForm, SshComputeForm, TlsComputeForm, SocketComputeForm)}
def saved(request, form):
"""Tells that the panel cannot connect to the compute the form saved, and why (Compute.clean)."""
if form.instance.unreachable:
messages.warning(request, _("The host was saved, but the panel cannot connect to it: %(error)s")
% {"error": form.instance.unreachable})
return redirect(reverse("computes"))
@sensitive_post_parameters()
@superuser_only
def compute_create(request, FormClass):
@ -165,7 +178,7 @@ def compute_create(request, FormClass):
compute = form.instance
with audit(request, compute, f"Compute {compute.name} ({compute.hostname})", "add"):
form.save()
return redirect(reverse("computes"))
return saved(request, form)
return render(request, "computes/form.html", {"form": form})
@ -175,15 +188,7 @@ def compute_create(request, FormClass):
def compute_update(request, compute_id):
compute = get_object_or_404(Compute, pk=compute_id)
if compute.type == 1:
FormClass = TcpComputeForm
elif compute.type == 2:
FormClass = SshComputeForm
elif compute.type == 3:
FormClass = TlsComputeForm
elif compute.type == 4:
FormClass = SocketComputeForm
FormClass = FORMS[compute.type]
subject = f"Compute {compute.name} ({compute.hostname})"
before = snapshot(compute)
form = FormClass(request.POST or None, instance=compute)
@ -197,7 +202,7 @@ def compute_update(request, compute_id):
entry.action = "change " + ", ".join(fields)
entry.skip = not fields
if form.is_valid():
return redirect(reverse("computes"))
return saved(request, form)
return render(request, "computes/form.html", {"form": form})