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

fix(instances): a console settings page opened before another change does not undo it

The console form compared what was posted with the settings saved at the
time of the save, so every field of a page opened earlier counted as a
change: an administrator who moved a console to localhost had it opened
to all interfaces again when another one, on an older page, only
generated a new password. The form now sends back a fingerprint of the
type, listen address and keymap it showed, and a save made after these
changed is refused with a message to check them and save again.

A refused save names the reasons without the field names.
This commit is contained in:
catborise 2026-11-13 22:31:08 +03:00
parent 7fe79463fc
commit 88e7e0fa90
10 changed files with 96 additions and 47 deletions

View file

@ -2,6 +2,7 @@ import re
from django import forms
from django.conf import settings
from django.utils.crypto import salted_hmac
from django.utils.translation import gettext_lazy as _
from .models import Flavor
@ -19,6 +20,12 @@ class FlavorForm(forms.ModelForm):
fields = "__all__"
def console_seen(console_type, listener, keymap, passwd):
"""The fingerprint of the console settings a page shows, which it sends
back: a page opened before another change would undo it."""
return salted_hmac("instances.console_seen", repr((console_type, listener, keymap, passwd)), algorithm="sha256").hexdigest()
class ConsoleForm(forms.Form):
console_type = forms.ChoiceField(
label=_("Console type"), required=False, widget=forms.Select(attrs={"class": "form-select"})
@ -39,6 +46,7 @@ class ConsoleForm(forms.Form):
required=False,
strip=False,
)
seen = forms.CharField(widget=forms.HiddenInput, required=False)
def __init__(self, *args, instance, is_superuser, **kwargs):
# the VM's settings as the initial values: a save changes only the fields edited
@ -51,6 +59,8 @@ class ConsoleForm(forms.Form):
"password_action": "keep",
"keymap": instance.config_console_keymap or "auto",
}
kwargs["initial"]["seen"] = console_seen(*(kwargs["initial"][k] for k in ("console_type", "listen_on", "keymap")),
instance.config_console_passwd)
super(ConsoleForm, self).__init__(*args, **kwargs)
types = [("vnc", "VNC")]
if settings.SERIAL_CONSOLE_ENABLED:
@ -85,6 +95,8 @@ class ConsoleForm(forms.Form):
def clean(self):
data = super().clean()
if data.get("seen") != self.initial["seen"]:
raise forms.ValidationError(_("The console settings were changed meanwhile; check them and save again."))
action = data.get("password_action")
if action == "set":
password = data.get("password", "")

View file

@ -697,7 +697,7 @@
{% endif %}
{% if can_manage_console %}
<div role="tabpanel" class="tab-pane" id="vncsettings">
<form method="post" action="{% url 'instances:update_console' instance.id %}" aria-label="{% trans "Console settings" %}">{% csrf_token %}
<form method="post" action="{% url 'instances:update_console' instance.id %}" aria-label="{% trans "Console settings" %}">{% csrf_token %}{{ console_form.seen }}
{% if instance.status != 5 %}
<p class="small text-body-secondary">{% trans "The running console keeps its current settings; changes here apply after the VM is shut down and started." %}</p>
{% endif %}

View file

@ -10,7 +10,7 @@ from django.contrib.auth import get_user_model
from django.contrib.messages import get_messages
from django.test import TestCase, override_settings
from django.urls import reverse
from instances.forms import ConsoleForm
from instances.forms import ConsoleForm, console_seen
from instances.models import Instance
from unittest.mock import PropertyMock
from accounts.models import UserInstance
@ -35,7 +35,9 @@ class UpdateConsoleTestCase(TestCase):
proxy.get_console_type.side_effect = lambda config=False: console_type if config else "vnc"
proxy.get_console_listener_addr.return_value = "127.0.0.1"
proxy.get_console_keymap.return_value = ""
proxy.get_console_passwd.return_value = None
proxy.set_console_passwd.return_value = True
data = {"seen": console_seen(console_type, "127.0.0.1", "auto", None), **data}
response = self.client.post(reverse("instances:update_console", args=[self.instance.id]), data)
return proxy, [str(m) for m in get_messages(response.wsgi_request)]
@ -45,6 +47,16 @@ class UpdateConsoleTestCase(TestCase):
proxy.set_console_listener_addr.assert_called_once_with("0.0.0.0")
proxy.set_console_passwd.assert_not_called()
def test_a_page_opened_before_another_change_does_not_undo_it(self):
# another administrator moved the console to localhost and set a keymap
# or set a new password
for stale in (console_seen("vnc", "0.0.0.0", "auto", None), console_seen("vnc", "127.0.0.1", "auto", "Other-1")):
proxy, messages = self.post({**VNC, "listen_on": "0.0.0.0", "password_action": "generate", "seen": stale})
proxy.set_console_listener_addr.assert_not_called()
proxy.set_console_passwd.assert_not_called()
self.assertEqual(messages[-1], "Console settings were not saved: "
"The console settings were changed meanwhile; check them and save again.")
def test_a_template_s_console_settings_are_not_changed(self):
# its page has no console form: a template is cloned, not run
self.instance.is_template = True
@ -94,7 +106,7 @@ class UpdateConsoleTestCase(TestCase):
with patch("instances.models.wvmInstance") as wvm:
wvm.return_value.get_console_type.side_effect = lambda config=False: "pty" if config else "vnc"
form = ConsoleForm(instance=Instance.objects.get(pk=self.instance.pk), is_superuser=True)
self.assertEqual((form["console_type"].value(), sorted(form.fields)), ("pty", ["console_type"]))
self.assertEqual((form["console_type"].value(), sorted(form.fields)), ("pty", ["console_type", "seen"]))
def test_a_spice_console_stays_spice_when_its_settings_are_saved(self):
# SPICE is not offered for new consoles: a save would have made it VNC
@ -135,6 +147,8 @@ class ConsoleListenerTests(TestCase):
proxy.get_console_passwd.return_value = "Old-pass-1"
proxy.get_console_keymap.return_value = ""
proxy.set_console_passwd.return_value = True
proxy.get_console_type.return_value = "vnc"
data = {"seen": console_seen("vnc", "127.0.0.1" if local else "0.0.0.0", "auto", "Old-pass-1"), **data}
response = self.client.post(reverse("instances:update_console", args=[self.vm.id]), data)
return proxy, [str(m) for m in get_messages(response.wsgi_request)]

View file

@ -8,6 +8,7 @@ from appsettings.models import AppSettings
from computes.models import Compute
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.contrib.messages import get_messages
from django.http.response import Http404
from django.shortcuts import reverse
from django.test import TestCase
@ -18,6 +19,7 @@ from operations.models import Operation
from vrtManager.tests import livetest
from .test_create_instance import run
from instances.forms import ConsoleForm
from instances.models import Flavor, Instance
from computes.utils import refresh_instance_database
@ -734,12 +736,17 @@ class InstancesTestCase(TestCase):
self.assertEqual(Instance.objects.count(), instance_count)
def test_console(self):
# the other address than the saved one: the save must change it
listen = "127.0.0.1" if self.instance.config_console_listener_address == "0.0.0.0" else "0.0.0.0"
response = self.client.post(
reverse("instances:update_console", args=[self.instance.id]),
{"listen_on": "0.0.0.0", "password_action": "keep", "keymap": "auto"},
{"listen_on": listen, "password_action": "keep", "keymap": "auto",
"seen": ConsoleForm(instance=self.instance, is_superuser=True).initial["seen"]},
HTTP_REFERER=reverse("index"),
)
self.assertEqual(response.status_code, 302)
self.assertEqual([str(m) for m in get_messages(response.wsgi_request)], [])
self.assertEqual(Instance.objects.get(pk=self.instance.pk).config_console_listener_address, listen)
def test_status(self):
response = self.client.get(reverse("instances:status", args=[self.instance.id]))

View file

@ -10,6 +10,7 @@ from django.contrib.auth import get_user_model
from django.contrib.messages import get_messages
from django.test import TestCase
from django.urls import reverse
from instances.forms import console_seen
from instances.models import Instance
from libvirt import libvirtError
from logs.models import Logs
@ -122,8 +123,12 @@ class VMRowTests(TestCase):
def test_console_password_rows_never_hold_the_password(self):
self.proxy.get_console_type.return_value = "vnc"
self.proxy.console_listens_locally.return_value = True
self.proxy.get_console_listener_addr.return_value = "127.0.0.1"
self.proxy.get_console_keymap.return_value = ""
self.proxy.get_console_passwd.return_value = ""
self.proxy.set_console_passwd.return_value = False # no graphics device
form = {"listen_on": "127.0.0.1", "keymap": "auto", "password_action": "set"}
form = {"listen_on": "127.0.0.1", "keymap": "auto", "password_action": "set",
"seen": console_seen("vnc", "127.0.0.1", "auto", "")}
self.post("update_console", {**form, "password": "Vnc-pw-1"})
self.proxy.set_console_passwd.return_value = True
self.post("update_console", {**form, "password": "Vnc-pw-2"})
@ -139,7 +144,8 @@ class VMRowTests(TestCase):
self.proxy.get_console_keymap.return_value = ""
self.proxy.set_console_keymap.return_value = False # no graphics device
self.proxy.set_console_listener_addr.return_value = False # a socket, no address
form = {"listen_on": "0.0.0.0", "keymap": "de", "password_action": "keep"}
form = {"listen_on": "0.0.0.0", "keymap": "de", "password_action": "keep",
"seen": console_seen("vnc", "127.0.0.1", "auto", "")}
self.post("update_console", form)
self.proxy.set_console_keymap.return_value = None # the define's result
self.proxy.set_console_listener_addr.return_value = None
@ -154,7 +160,8 @@ class VMRowTests(TestCase):
self.proxy.get_console_passwd.return_value = ""
self.proxy.get_console_keymap.return_value = "de"
self.proxy.set_console_keymap.return_value = None
self.post("update_console", {"listen_on": "127.0.0.1", "keymap": "auto", "password_action": "keep"})
self.post("update_console", {"listen_on": "127.0.0.1", "keymap": "auto", "password_action": "keep",
"seen": console_seen("vnc", "127.0.0.1", "de", "")})
self.proxy.set_console_keymap.assert_called_once_with("auto")
self.assertEqual(self.rows(), [("VM vm: remove console keymap", True)])
@ -164,7 +171,7 @@ class VMRowTests(TestCase):
self.proxy.get_console_listener_addr.return_value = "192.0.2.10"
self.proxy.get_console_keymap.return_value = "de"
self.proxy.get_console_passwd.return_value = "Vnc-pw-1"
form = {"listen_on": "192.0.2.10", "keymap": "de"}
form = {"listen_on": "192.0.2.10", "keymap": "de", "seen": console_seen("vnc", "192.0.2.10", "de", "Vnc-pw-1")}
self.post("update_console", {**form, "password_action": "keep"})
self.post("update_console", {**form, "password_action": "set", "password": "Vnc-pw-2"})
self.assertEqual(self.rows(), [("VM vm: set console password", True)])

View file

@ -2375,7 +2375,7 @@ def update_console(request, pk):
raise PermissionDenied
form = ConsoleForm(request.POST, instance=instance, is_superuser=request.user.is_superuser)
if not form.is_valid():
messages.error(request, _("Console settings were not saved: %(errors)s") % {"errors": form.errors.as_text()})
messages.error(request, _("Console settings were not saved: %(errors)s") % {"errors": " ".join(e for errors in form.errors.values() for e in errors)})
return get_safe_redirect(request, default=reverse("instances:instance", args=[instance.id]) + "#vncsettings")
console_type = form.cleaned_data["console_type"]
if console_type not in ("", instance.config_console_type):

Binary file not shown.

View file

@ -369,7 +369,7 @@ msgstr "Kullanıcı adını girin"
#: accounts/templates/accounts/otp_login.html:37
#: accounts/templates/login.html:36 admin/templates/admin/user_form.html:32
#: console/templates/console-vnc.html:82 instances/forms.py:27
#: console/templates/console-vnc.html:82 instances/forms.py:34
#: instances/templates/instances/access_tab.html:53
msgid "Password"
msgstr "Parola"
@ -758,7 +758,7 @@ msgstr ""
"yalnızca bir sahibe izin veriliyor"
#: admin/forms.py:208 computes/templates/computes/list.html:58
#: computes/templates/overview.html:58 instances/forms.py:14
#: computes/templates/overview.html:58 instances/forms.py:15
#: instances/templates/allinstances_index_grouped.html:16
#: instances/templates/allinstances_index_nongrouped.html:14
#: instances/templates/create_instance_w2.html:63
@ -2797,70 +2797,75 @@ msgstr ""
msgid "Templates cannot be started."
msgstr "Şablon makineler başlatılamaz."
#: instances/forms.py:13 instances/templates/create_instance_w2.html:69
#: instances/forms.py:14 instances/templates/create_instance_w2.html:69
#: instances/templates/instances/settings_tab.html:858 instances/views.py:239
msgid "Memory (MiB)"
msgstr "Bellek (MiB)"
#: instances/forms.py:15
#: instances/forms.py:16
msgid "Disk (GiB)"
msgstr "Disk (GiB)"
#: instances/forms.py:24
#: instances/forms.py:31
msgid "Console type"
msgstr "Konsol tipi"
#: instances/forms.py:29
#: instances/forms.py:36
msgid "Keep the password"
msgstr "Parolayı koru"
#: instances/forms.py:30
#: instances/forms.py:37
msgid "Generate a new one"
msgstr "Yenisini oluştur"
#: instances/forms.py:31
#: instances/forms.py:38
msgid "Set a new one"
msgstr "Yenisini belirle"
#: instances/forms.py:32
#: instances/forms.py:39
msgid "No password"
msgstr "Parola yok"
#: instances/forms.py:37
#: instances/forms.py:44
msgid "New password"
msgstr "Yeni parola"
#: instances/forms.py:57
#: instances/forms.py:66
msgid "Serial (xterm; the guest needs a getty on ttyS0)"
msgstr "Seri (xterm; konuk sistemde ttyS0 üzerinde getty gerekir)"
#: instances/forms.py:67
#: instances/forms.py:76
msgid "Auto"
msgstr "Otomatik"
#: instances/forms.py:76
#: instances/forms.py:85
msgid "Listen on"
msgstr "Dinlenen"
#: instances/forms.py:83
#: instances/forms.py:92
msgid "Keymap"
msgstr "Klavye eşlemi"
#: instances/forms.py:92
#: instances/forms.py:98
msgid "The console settings were changed meanwhile; check them and save again."
msgstr ""
"Konsol ayarları bu arada değişti; ayarları kontrol edip yeniden kaydedin."
#: instances/forms.py:103
msgid "Enter the new password."
msgstr "Yeni parolayı girin."
#: instances/forms.py:96
#: instances/forms.py:107
msgid ""
"A VNC password takes up to 8 letters, digits or symbols, without accents."
msgstr ""
"VNC parolası en çok 8 harf, rakam ya da simge alır; aksanlı harf olmaz."
#: instances/forms.py:98
#: instances/forms.py:109
msgid "A password takes no line breaks or other control characters."
msgstr "Parola satır sonu ya da başka denetim karakteri içeremez."
#: instances/forms.py:104
#: instances/forms.py:115
msgid ""
"The console listens beyond localhost; only an administrator can remove its "
"password."
@ -2868,7 +2873,7 @@ msgstr ""
"Konsol localhost dışında da dinliyor; parolasını yalnızca bir yönetici "
"kaldırabilir."
#: instances/forms.py:148
#: instances/forms.py:159
msgid "The name of the virtual machine must not contain any special characters"
msgstr "Sanal makine adı özel karakterler içeremez"

Binary file not shown.

View file

@ -364,7 +364,7 @@ msgstr "输入用户名"
#: accounts/templates/accounts/otp_login.html:37
#: accounts/templates/login.html:36 admin/templates/admin/user_form.html:32
#: console/templates/console-vnc.html:82 instances/forms.py:27
#: console/templates/console-vnc.html:82 instances/forms.py:34
#: instances/templates/instances/access_tab.html:53
msgid "Password"
msgstr "密码"
@ -735,7 +735,7 @@ msgid ""
msgstr "NEW_USER_DEFAULT_INSTANCES:%(name)s 已有所有者,且只允许一个所有者"
#: admin/forms.py:208 computes/templates/computes/list.html:58
#: computes/templates/overview.html:58 instances/forms.py:14
#: computes/templates/overview.html:58 instances/forms.py:15
#: instances/templates/allinstances_index_grouped.html:16
#: instances/templates/allinstances_index_nongrouped.html:14
#: instances/templates/create_instance_w2.html:63
@ -2687,75 +2687,79 @@ msgstr "不支持控制台类型 '%(type)s'。请将虚拟机图形切换为 VNC
msgid "Templates cannot be started."
msgstr "模板无法启动。"
#: instances/forms.py:13 instances/templates/create_instance_w2.html:69
#: instances/forms.py:14 instances/templates/create_instance_w2.html:69
#: instances/templates/instances/settings_tab.html:858 instances/views.py:239
msgid "Memory (MiB)"
msgstr "内存(MiB)"
#: instances/forms.py:15
#: instances/forms.py:16
msgid "Disk (GiB)"
msgstr "磁盘(GiB)"
#: instances/forms.py:24
#: instances/forms.py:31
msgid "Console type"
msgstr "控制台类型"
#: instances/forms.py:29
#: instances/forms.py:36
msgid "Keep the password"
msgstr "保留密码"
#: instances/forms.py:30
#: instances/forms.py:37
msgid "Generate a new one"
msgstr "生成新密码"
#: instances/forms.py:31
#: instances/forms.py:38
msgid "Set a new one"
msgstr "设置新密码"
#: instances/forms.py:32
#: instances/forms.py:39
msgid "No password"
msgstr "无密码"
#: instances/forms.py:37
#: instances/forms.py:44
msgid "New password"
msgstr "新密码"
#: instances/forms.py:57
#: instances/forms.py:66
msgid "Serial (xterm; the guest needs a getty on ttyS0)"
msgstr "串行(xterm;客户机需要在 ttyS0 上运行 getty)"
#: instances/forms.py:67
#: instances/forms.py:76
msgid "Auto"
msgstr "自动"
#: instances/forms.py:76
#: instances/forms.py:85
msgid "Listen on"
msgstr "监听地址"
#: instances/forms.py:83
#: instances/forms.py:92
msgid "Keymap"
msgstr "键盘映射"
#: instances/forms.py:92
#: instances/forms.py:98
msgid "The console settings were changed meanwhile; check them and save again."
msgstr "控制台设置已在此期间被更改;请检查后重新保存。"
#: instances/forms.py:103
msgid "Enter the new password."
msgstr "请输入新密码。"
#: instances/forms.py:96
#: instances/forms.py:107
msgid ""
"A VNC password takes up to 8 letters, digits or symbols, without accents."
msgstr "VNC 密码最多 8 个字母、数字或符号,不能有带重音的字母。"
#: instances/forms.py:98
#: instances/forms.py:109
msgid "A password takes no line breaks or other control characters."
msgstr "密码不能包含换行或其他控制字符。"
#: instances/forms.py:104
#: instances/forms.py:115
msgid ""
"The console listens beyond localhost; only an administrator can remove its "
"password."
msgstr "控制台监听的不只是 localhost;只有管理员可以移除其密码。"
#: instances/forms.py:148
#: instances/forms.py:159
msgid "The name of the virtual machine must not contain any special characters"
msgstr "虚拟机名称不能包含任何特殊字符"