1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 08:56:07 +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})

Binary file not shown.

View file

@ -1813,11 +1813,11 @@ msgstr "Hiçbir şey değişmedi"
msgid "Other"
msgstr "Diğer"
#: computes/forms.py:18
#: computes/forms.py:21
msgid "Stored, leave empty to keep"
msgstr "Kayıtlı, korumak için boş bırakın"
#: computes/forms.py:28 computes/templates/computes/instances.html:45
#: computes/forms.py:31 computes/templates/computes/instances.html:45
#: instances/templates/instances/settings_tab.html:871
#: instances/templates/instances/settings_tab.html:903
#: instances/templates/instances/snapshots_tab.html:27
@ -1825,43 +1825,43 @@ msgstr "Kayıtlı, korumak için boş bırakın"
msgid "Description"
msgstr "Tanım"
#: computes/forms.py:29
#: computes/forms.py:32
msgid "Shown on the hosts list"
msgstr "Sunucu listesinde gösterilir"
#: computes/forms.py:30
#: computes/forms.py:33
msgid "SASL login"
msgstr "SASL kullanıcı adı"
#: computes/forms.py:30
#: computes/forms.py:33
msgid "SASL password"
msgstr "SASL parolası"
#: computes/forms.py:35 computes/templates/create_comp_block.html:10
#: computes/forms.py:39 computes/templates/create_comp_block.html:10
msgid "libvirt over TCP, with a SASL login"
msgstr "TCP üzerinden libvirt, SASL girişiyle"
#: computes/forms.py:49 computes/templates/create_comp_block.html:14
#: computes/forms.py:53 computes/templates/create_comp_block.html:14
msgid "libvirt over SSH, with the panel's SSH key"
msgstr "SSH üzerinden libvirt, panelin SSH anahtarıyla"
#: computes/forms.py:50
#: computes/forms.py:54
msgid "FQDN/IP"
msgstr "FQDN/IP"
#: computes/forms.py:56
#: computes/forms.py:59
msgid "SSH user"
msgstr "SSH kullanıcısı"
#: computes/forms.py:63 computes/templates/create_comp_block.html:18
#: computes/forms.py:67 computes/templates/create_comp_block.html:18
msgid "libvirt over TLS, with certificates"
msgstr "TLS üzerinden libvirt, sertifikalarla"
#: computes/forms.py:76 computes/templates/create_comp_block.html:21
#: computes/forms.py:80 computes/templates/create_comp_block.html:21
msgid "Local"
msgstr "Yerel"
#: computes/forms.py:77 computes/templates/create_comp_block.html:22
#: computes/forms.py:81 computes/templates/create_comp_block.html:22
msgid "the libvirt of the host the panel runs on, by its socket"
msgstr "panelin çalıştığı sunucunun libvirt'i, soketi üzerinden"
@ -1907,12 +1907,12 @@ msgstr ""
"sanal makinenin root parolasını ve SSH anahtarını bununla ayarlar; boş: bu "
"sunucuda ayarlanamazlar"
#: computes/models.py:176
#: computes/models.py:179
#, python-format
msgid "This host is already added as %(name)s"
msgstr "Bu sunucu zaten %(name)s olarak ekli"
#: computes/models.py:179
#: computes/models.py:182
#, python-format
msgid ""
"The panel cannot reach the host to tell that its VMs are there: %(error)s"
@ -1920,7 +1920,7 @@ msgstr ""
"Panel sunucuya ulaşamadığı için VM'lerinin orada olduğunu doğrulayamıyor: "
"%(error)s"
#: computes/models.py:186
#: computes/models.py:189
msgid ""
"The host its VMs are on is not known yet: change the connection when the "
"panel has reached the host at its current one"
@ -1928,7 +1928,7 @@ msgstr ""
"VM'lerinin bulunduğu sunucu henüz bilinmiyor: bağlantıyı, panel sunucuya "
"mevcut bağlantısından ulaştıktan sonra değiştirin"
#: computes/models.py:189
#: computes/models.py:192
msgid "This is another host than the one its VMs are on: add it as a new host"
msgstr ""
"Bu, VM'lerinin bulunduğu sunucudan başka bir sunucu: yeni bir sunucu olarak "
@ -2413,11 +2413,11 @@ msgstr "Konuk mimarileri"
msgid "Emulator"
msgstr "Emülatör"
#: computes/validators.py:24
#: computes/validators.py:30
msgid "Enter an IPv4 address or a host name, without a scheme, port or path"
msgstr "Şema, port veya yol olmadan bir IPv4 adresi ya da sunucu adı girin"
#: computes/validators.py:35
#: computes/validators.py:41
msgid ""
"The login may contain only letters, digits, '.', '_' and '-', and may not "
"start with '-'"
@ -2425,11 +2425,11 @@ msgstr ""
"Kullanıcı adı yalnızca harf, rakam, '.', '_' ve '-' içerebilir ve '-' ile "
"başlayamaz"
#: computes/validators.py:47
#: computes/validators.py:53
msgid "Enter an IP address or a host name, without a scheme or port"
msgstr "Şema veya port olmadan bir IP adresi ya da sunucu adı girin"
#: computes/validators.py:54
#: computes/validators.py:60
msgid ""
"Enter the 64 hexadecimal characters of GSTFSD_KEY in the host's "
"/etc/default/webvirt-gstfsd"
@ -2437,7 +2437,12 @@ msgstr ""
"Sunucudaki /etc/default/webvirt-gstfsd içindeki GSTFSD_KEY değerinin 64 "
"onaltılık karakterini girin"
#: computes/views.py:217
#: computes/views.py:166
#, python-format
msgid "The host was saved, but the panel cannot connect to it: %(error)s"
msgstr "Sunucu kaydedildi, ancak panel ona bağlanamıyor: %(error)s"
#: computes/views.py:222
#, python-format
msgid ""
"Its VMs keep running on the host and leave the panel; their owners are kept "
@ -9085,17 +9090,17 @@ msgstr "Bağlantı başarısız: %(error)s"
msgid "Connection closed (%(reason)s)"
msgstr "Bağlantı kapandı (%(reason)s)"
#: vrtManager/connection.py:469
#: vrtManager/connection.py:476
#, python-format
msgid "Connection Failed: %(host)s is not connected"
msgstr "Bağlantı başarısız: %(host)s bağlı değil"
#: vrtManager/connection.py:521
#: vrtManager/connection.py:528
#, python-format
msgid "This host has no architecture %(arch)s"
msgstr "Bu sunucuda %(arch)s mimarisi yok"
#: vrtManager/connection.py:1171
#: vrtManager/connection.py:1178
#, python-format
msgid ""
"Pool %(pool)s is not active: the files the disks of the VMs in it are made "

Binary file not shown.

View file

@ -1756,11 +1756,11 @@ msgstr "没有任何更改"
msgid "Other"
msgstr "其他"
#: computes/forms.py:18
#: computes/forms.py:21
msgid "Stored, leave empty to keep"
msgstr "已保存,留空则保持不变"
#: computes/forms.py:28 computes/templates/computes/instances.html:45
#: computes/forms.py:31 computes/templates/computes/instances.html:45
#: instances/templates/instances/settings_tab.html:871
#: instances/templates/instances/settings_tab.html:903
#: instances/templates/instances/snapshots_tab.html:27
@ -1768,43 +1768,43 @@ msgstr "已保存,留空则保持不变"
msgid "Description"
msgstr "描述"
#: computes/forms.py:29
#: computes/forms.py:32
msgid "Shown on the hosts list"
msgstr "显示在主机列表中"
#: computes/forms.py:30
#: computes/forms.py:33
msgid "SASL login"
msgstr "SASL 登录名"
#: computes/forms.py:30
#: computes/forms.py:33
msgid "SASL password"
msgstr "SASL 密码"
#: computes/forms.py:35 computes/templates/create_comp_block.html:10
#: computes/forms.py:39 computes/templates/create_comp_block.html:10
msgid "libvirt over TCP, with a SASL login"
msgstr "通过 TCP 连接 libvirt,使用 SASL 登录"
#: computes/forms.py:49 computes/templates/create_comp_block.html:14
#: computes/forms.py:53 computes/templates/create_comp_block.html:14
msgid "libvirt over SSH, with the panel's SSH key"
msgstr "通过 SSH 连接 libvirt,使用面板的 SSH 密钥"
#: computes/forms.py:50
#: computes/forms.py:54
msgid "FQDN/IP"
msgstr "FQDN/IP"
#: computes/forms.py:56
#: computes/forms.py:59
msgid "SSH user"
msgstr "SSH 用户"
#: computes/forms.py:63 computes/templates/create_comp_block.html:18
#: computes/forms.py:67 computes/templates/create_comp_block.html:18
msgid "libvirt over TLS, with certificates"
msgstr "通过 TLS 连接 libvirt,使用证书"
#: computes/forms.py:76 computes/templates/create_comp_block.html:21
#: computes/forms.py:80 computes/templates/create_comp_block.html:21
msgid "Local"
msgstr "本地"
#: computes/forms.py:77 computes/templates/create_comp_block.html:22
#: computes/forms.py:81 computes/templates/create_comp_block.html:22
msgid "the libvirt of the host the panel runs on, by its socket"
msgstr "面板所在主机的 libvirt,通过其套接字连接"
@ -1847,24 +1847,24 @@ msgstr ""
"主机 /etc/default/webvirt-gstfsd 中的 GSTFSD_KEY:面板用它为已关机的虚拟机设置 root 密码和 SSH "
"密钥;留空:无法在此设置"
#: computes/models.py:176
#: computes/models.py:179
#, python-format
msgid "This host is already added as %(name)s"
msgstr "此主机已作为 %(name)s 添加"
#: computes/models.py:179
#: computes/models.py:182
#, python-format
msgid ""
"The panel cannot reach the host to tell that its VMs are there: %(error)s"
msgstr "面板无法连接该主机,因此无法确认其虚拟机在那里:%(error)s"
#: computes/models.py:186
#: computes/models.py:189
msgid ""
"The host its VMs are on is not known yet: change the connection when the "
"panel has reached the host at its current one"
msgstr "其虚拟机所在的主机尚不明确:请在面板通过当前连接访问到该主机后再更改连接"
#: computes/models.py:189
#: computes/models.py:192
msgid "This is another host than the one its VMs are on: add it as a new host"
msgstr "这不是其虚拟机所在的主机:请将其添加为新主机"
@ -2331,27 +2331,32 @@ msgstr "客户机架构"
msgid "Emulator"
msgstr "模拟器"
#: computes/validators.py:24
#: computes/validators.py:30
msgid "Enter an IPv4 address or a host name, without a scheme, port or path"
msgstr "请输入 IPv4 地址或主机名,不带协议、端口或路径"
#: computes/validators.py:35
#: computes/validators.py:41
msgid ""
"The login may contain only letters, digits, '.', '_' and '-', and may not "
"start with '-'"
msgstr "登录名只能包含字母、数字、'.'、'_' 和 '-',且不能以 '-' 开头"
#: computes/validators.py:47
#: computes/validators.py:53
msgid "Enter an IP address or a host name, without a scheme or port"
msgstr "请输入 IP 地址或主机名,不带协议或端口"
#: computes/validators.py:54
#: computes/validators.py:60
msgid ""
"Enter the 64 hexadecimal characters of GSTFSD_KEY in the host's "
"/etc/default/webvirt-gstfsd"
msgstr "请输入主机 /etc/default/webvirt-gstfsd 中 GSTFSD_KEY 的 64 个十六进制字符"
#: computes/views.py:217
#: computes/views.py:166
#, python-format
msgid "The host was saved, but the panel cannot connect to it: %(error)s"
msgstr "主机已保存,但面板无法连接到它:%(error)s"
#: computes/views.py:222
#, python-format
msgid ""
"Its VMs keep running on the host and leave the panel; their owners are kept "
@ -8586,17 +8591,17 @@ msgstr "连接失败:%(error)s"
msgid "Connection closed (%(reason)s)"
msgstr "连接已关闭(%(reason)s)"
#: vrtManager/connection.py:469
#: vrtManager/connection.py:476
#, python-format
msgid "Connection Failed: %(host)s is not connected"
msgstr "连接失败:%(host)s 未连接"
#: vrtManager/connection.py:521
#: vrtManager/connection.py:528
#, python-format
msgid "This host has no architecture %(arch)s"
msgstr "此主机没有 %(arch)s 架构"
#: vrtManager/connection.py:1171
#: vrtManager/connection.py:1178
#, python-format
msgid ""
"Pool %(pool)s is not active: the files the disks of the VMs in it are made "