mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-02 17:06:09 +00:00
A user locked by failed sign-ins could only be unlocked with manage.py axes_reset_username on the server, and nothing in the panel showed the lock. The Users page and the user's page now mark a locked user, counted as django-axes counts (a username's failures from one address, over browsers, in any letter case), and the user's page has Unlock sign-in for a superuser; it ends the lock from every address and is on the Logs page. A sign-in lasted Django's default two weeks, also after the browser was closed. It now ends Session length (hours) after the sign-in, a setting on the Settings page, 24 by default; a change applies from the next sign-in. An idle timeout would not help: an open VM list refreshes itself every five seconds. Blocking a user signs them out. django-auth-ldap does not check is_active for an open session, so a blocked LDAP user kept theirs. The OTP sign-in page showed its error as a red list inside the red box; it is plain text as on the other sign-in page, and django-otp's errors are in Turkish and Chinese.
188 lines
11 KiB
Python
188 lines
11 KiB
Python
import re
|
|
from urllib.parse import urlsplit
|
|
from pathlib import Path
|
|
|
|
from admin.decorators import superuser_only
|
|
from django.conf import settings
|
|
from django.core.exceptions import ValidationError
|
|
from django.core.validators import URLValidator, validate_email
|
|
from django.contrib import messages
|
|
from django.db import DatabaseError, transaction
|
|
from django.http import HttpResponseRedirect
|
|
from django.shortcuts import render
|
|
from django.utils.translation import gettext as _
|
|
from django.utils.translation import gettext_noop
|
|
from logs.audit import audit
|
|
from operations import alerts
|
|
from operations.utils import BOUNDS
|
|
from vrtManager.util import OperationError
|
|
|
|
from appsettings.models import AppSettings
|
|
|
|
|
|
# the themes "manage.py build_themes" compiles; base.html links the chosen one
|
|
THEMES_DIR = Path(settings.BASE_DIR, "static", "css", "themes")
|
|
|
|
# the whole-number settings and their range: they are read as numbers, and a
|
|
# letter would break the page or the job that reads one
|
|
NUMBERS = {
|
|
**{key: bounds[:2] for key, bounds in BOUNDS.items()},
|
|
"LOGS_PER_PAGE": (1, 1000),
|
|
"LOGIN_FAILURE_LIMIT": (1, 1000),
|
|
"LOGIN_LOCKOUT_MINUTES": (1, 10080),
|
|
"LOGIN_SESSION_HOURS": (1, 8760),
|
|
"SNAPSHOT_FREE_SPACE_PERCENT": (0, 100),
|
|
"SNAPSHOT_FREE_SPACE_MIN_GIB": (0, 100000),
|
|
"INSTANCE_VOLUME_DEFAULT_OWNER_UID": (0, 4294967294),
|
|
"INSTANCE_VOLUME_DEFAULT_OWNER_GID": (0, 4294967294),
|
|
}
|
|
|
|
|
|
# settings whose values the audit log does not show
|
|
SECRET_SETTINGS = {"ALERT_WEBHOOK"}
|
|
|
|
# the Settings page's groups, in order; a setting in none shows under Other. The
|
|
# titles stay English here: the page links them by slug and translates them
|
|
GROUPS = [
|
|
(gettext_noop("New VM defaults"), ["INSTANCE_ARCH_DEFAULT_TYPE", "INSTANCE_MACHINE_DEFAULT_TYPE",
|
|
"INSTANCE_FIRMWARE_DEFAULT_TYPE", "INSTANCE_CPU_DEFAULT_MODE", "INSTANCE_NIC_DEFAULT_TYPE",
|
|
"INSTANCE_VIDEO_DEFAULT_TYPE", "INSTANCE_INPUT_DEFAULT_DEVICE", "INSTANCE_CDROM_ADD"]),
|
|
(gettext_noop("Disks"), ["INSTANCE_VOLUME_DEFAULT_BUS", "INSTANCE_VOLUME_DEFAULT_FORMAT", "INSTANCE_VOLUME_DEFAULT_CACHE",
|
|
"INSTANCE_VOLUME_DEFAULT_IO", "INSTANCE_VOLUME_DEFAULT_DISCARD",
|
|
"INSTANCE_VOLUME_DEFAULT_DETECT_ZEROES", "INSTANCE_VOLUME_DEFAULT_SCSI_CONTROLLER",
|
|
"INSTANCE_VOLUME_DEFAULT_OWNER_UID", "INSTANCE_VOLUME_DEFAULT_OWNER_GID"]),
|
|
(gettext_noop("Clones"), ["CLONE_INSTANCE_AUTO_NAME", "CLONE_INSTANCE_DEFAULT_PREFIX"]),
|
|
(gettext_noop("Console"), ["CONSOLE_SCALE", "CONSOLE_VIEW_ONLY", "CONSOLE_RESIZE_SESSION", "CONSOLE_CLIP_VIEWPORT"]),
|
|
(gettext_noop("VM access and owners"), ["SHOW_ACCESS_ROOT_PASSWORD", "SHOW_ACCESS_SSH_KEYS",
|
|
"ALLOW_INSTANCE_MULTIPLE_OWNER", "QUOTA_DEBUG"]),
|
|
(gettext_noop("Snapshots and jobs"), ["SNAPSHOT_FREE_SPACE_PERCENT", "SNAPSHOT_FREE_SPACE_MIN_GIB",
|
|
"WORKER_CONCURRENCY", "JOB_RETENTION_DAYS"]),
|
|
(gettext_noop("Migrations"), ["MIGRATION_BANDWIDTH"]),
|
|
(gettext_noop("Login"), ["LOGIN_FAILURE_LIMIT", "LOGIN_LOCKOUT_MINUTES", "LOGIN_SESSION_HOURS",
|
|
"LOGIN_NOTICE"]),
|
|
(gettext_noop("Alerts"), ["ALERT_EMAILS", "ALERT_WEBHOOK"]),
|
|
(gettext_noop("Lists and pages"), ["VIEW_INSTANCES_LIST_STYLE", "VM_DRBD_STATUS", "LOGS_PER_PAGE",
|
|
"LOG_RETENTION_DAYS"]),
|
|
]
|
|
|
|
|
|
def refusal(setting, value):
|
|
"""Why the value cannot be saved for the setting, or None."""
|
|
if len(value) > AppSettings._meta.get_field("value").max_length:
|
|
return _("%(setting)s takes at most %(length)s characters") % {
|
|
"setting": _(setting.name), "length": AppSettings._meta.get_field("value").max_length}
|
|
if setting.key in NUMBERS:
|
|
low, high = NUMBERS[setting.key]
|
|
if not (value.isascii() and value.isdigit() and len(value) <= 10 and low <= int(value) <= high):
|
|
return _("%(setting)s must be a whole number between %(low)s and %(high)s") % {
|
|
"setting": _(setting.name), "low": low, "high": high}
|
|
elif setting.choices and value not in setting.choices_as_list():
|
|
return _("%(setting)s must be one of %(choices)s") % {
|
|
"setting": _(setting.name), "choices": ", ".join(setting.choices_as_list())}
|
|
elif setting.key == "CLONE_INSTANCE_DEFAULT_PREFIX" and not re.fullmatch(r"[a-zA-Z0-9-]+", value):
|
|
# a clone's name is the prefix and a number, and takes only these
|
|
return _("%(setting)s takes letters, digits and '-' only") % {"setting": _(setting.name)}
|
|
try:
|
|
if setting.key == "ALERT_EMAILS":
|
|
for address in filter(None, (a.strip() for a in value.split(","))):
|
|
validate_email(address)
|
|
elif setting.key == "ALERT_WEBHOOK" and value.strip():
|
|
URLValidator(schemes=["http", "https"])(value.strip())
|
|
if "@" in urlsplit(value.strip()).netloc: # urllib would take user:password@ for the host
|
|
raise ValidationError("credentials in the URL")
|
|
except ValidationError:
|
|
return _("%(setting)s: %(value)s is not an e-mail address or an http(s) URL") % {"setting": _(setting.name), "value": value}
|
|
return None
|
|
|
|
|
|
def combined_refusal(values):
|
|
"""Why settings that work only together cannot be saved as values
|
|
(key: value, saved or new), untranslated, or None."""
|
|
# libvirt refuses such a disk: every new VM would fail
|
|
if values["INSTANCE_VOLUME_DEFAULT_IO"] == "native" and values["INSTANCE_VOLUME_DEFAULT_CACHE"] not in ("none", "directsync"):
|
|
return gettext_noop("Disk I/O native needs disk cache none or directsync")
|
|
return None
|
|
|
|
|
|
@superuser_only
|
|
def appsettings(request):
|
|
"""The settings, in groups; a group's form saves its changed settings,
|
|
or none of them when one is refused."""
|
|
bootstrap_theme = AppSettings.objects.get(key="BOOTSTRAP_THEME")
|
|
themes_list = sorted(p.name.removesuffix(".min.css") for p in THEMES_DIR.glob("*.min.css"))
|
|
# the theme has its own form
|
|
settings_by_key = {s.key: s for s in AppSettings.objects.exclude(key="BOOTSTRAP_THEME")}
|
|
|
|
if request.method == "POST":
|
|
if "test_alert" in request.POST: # with the settings saved
|
|
results = alerts.test()
|
|
if not results:
|
|
messages.error(request, _("Set an alert e-mail address or webhook and save it first"))
|
|
for channel, error in results.items():
|
|
name = _("E-mail") if channel == "mail" else _("Webhook")
|
|
if error is None:
|
|
messages.success(request, _("%(channel)s: the test alert was sent") % {"channel": name})
|
|
else:
|
|
messages.error(request, _("%(channel)s: the test alert failed: %(error)s") % {"channel": name, "error": error})
|
|
return HttpResponseRedirect(request.get_full_path()) # the results are at the top
|
|
if "BOOTSTRAP_THEME" in request.POST:
|
|
theme = request.POST.get("BOOTSTRAP_THEME", "")
|
|
if theme not in themes_list:
|
|
messages.error(request, _("Unknown theme: %(theme)s") % {"theme": theme})
|
|
return HttpResponseRedirect(request.get_full_path())
|
|
if theme != bootstrap_theme.value:
|
|
with audit(request, None, "Setting Theme", f"change to {theme}"):
|
|
bootstrap_theme.value = theme
|
|
bootstrap_theme.save()
|
|
msg = _("Theme is changed. Now: %(theme)s") % {"theme": theme}
|
|
messages.success(request, msg)
|
|
return HttpResponseRedirect(request.get_full_path())
|
|
|
|
# a field counts as changed against the value the page showed (was-KEY): one left
|
|
# as it was does not undo what another administrator saved meanwhile
|
|
posted = sorted(((s, request.POST[s.key]) for s in settings_by_key.values() if s.key in request.POST),
|
|
key=lambda item: item[0].name)
|
|
changed = [(s, value) for s, value in posted if value != request.POST.get(f"was-{s.key}", s.value)]
|
|
refusals = [refused for refused in (refusal(s, value) for s, value in changed) if refused]
|
|
# checked only when the pair changes: a pair saved before does not block other settings
|
|
pair = {"INSTANCE_VOLUME_DEFAULT_IO", "INSTANCE_VOLUME_DEFAULT_CACHE"}
|
|
pair_changed = bool(pair & {s.key for s, _v in changed})
|
|
if not refusals and pair_changed and (refused := combined_refusal(
|
|
{key: s.value for key, s in settings_by_key.items()} | {s.key: value for s, value in changed})):
|
|
refusals = [_(refused)]
|
|
for refused in refusals:
|
|
messages.error(request, refused)
|
|
if changed and not refusals:
|
|
# a webhook URL is a secret of its own (Slack's): not in the log
|
|
action = "change " + ", ".join(f"{s.name} to {'(not shown)' if s.key in SECRET_SETTINGS else value}"
|
|
for s, value in changed)
|
|
try:
|
|
# one row, and all of the group or none of it
|
|
with audit(request, None, "Settings", action), transaction.atomic():
|
|
# the pair as saved now, locked: another administrator's save of its other half
|
|
# since this page was read must not make it one libvirt refuses
|
|
if pair_changed:
|
|
saved = AppSettings.objects.select_for_update().filter(key__in=pair).values_list("key", "value")
|
|
if refused := combined_refusal(dict(saved) | {s.key: value for s, value in changed}):
|
|
raise OperationError(refused)
|
|
for setting, value in changed:
|
|
setting.value = value
|
|
setting.save()
|
|
except (DatabaseError, OperationError) as err: # the audit row records it as failed
|
|
messages.error(request, err)
|
|
else:
|
|
messages.success(request, _("Saved: %(settings)s") % {"settings": ", ".join(s.name for s, _v in changed)})
|
|
elif not refusals:
|
|
messages.info(request, _("Nothing changed"))
|
|
return HttpResponseRedirect(request.get_full_path())
|
|
|
|
groups = []
|
|
for title, keys in GROUPS:
|
|
groups.append((title, [settings_by_key.pop(key) for key in keys if key in settings_by_key]))
|
|
if settings_by_key:
|
|
groups.append((gettext_noop("Other"), sorted(settings_by_key.values(), key=lambda s: s.name)))
|
|
for _title, settings_list in groups:
|
|
for setting in settings_list:
|
|
setting.bounds = NUMBERS.get(setting.key)
|
|
return render(request, "appsettings.html",
|
|
{"bootstrap_theme": bootstrap_theme, "themes_list": themes_list, "groups": groups})
|