1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 08:56:07 +00:00

fix(accounts): a page whose session ended says so; a form sent then is not lost in a 405

A session that ended while a page was open went unnoticed: the VM list,
the VM page and the job panel kept asking, were sent to the sign-in
page, and showed what they had as if it were current. A button pressed
then sent the user to sign in and, after it, to the form's own address
by GET, where its view answered an empty 405 and the action was lost.

The panel's LoginRequiredMiddleware (webvirtcloud.middleware) answers a
page's script 401, upon which session_end.js says the user was signed
out, with a link to sign in and come back, and the page stops asking
and reloading. A form sent after the end (or with a token a sign-in
elsewhere replaced) goes back, after the sign-in, to the page it was on,
and the sign-in page says it was not done. accounts.E002 asks for this
middleware; Django's own is a warning (W002), so an update keeps a
panel whose local settings name it running.
This commit is contained in:
catborise 2026-11-21 23:30:47 +03:00
parent 2373d73b37
commit 7359fbb147
17 changed files with 189 additions and 15 deletions

View file

@ -24,12 +24,23 @@ def password_change_middleware_check(app_configs, **kwargs):
@register(Tags.security)
def login_required_middleware_check(app_configs, **kwargs):
middleware = list(settings.MIDDLEWARE)
required = "django.contrib.auth.middleware.LoginRequiredMiddleware"
required = "webvirtcloud.middleware.LoginRequiredMiddleware"
django_s = "django.contrib.auth.middleware.LoginRequiredMiddleware"
old = "login_required.middleware.LoginRequiredMiddleware"
if django_s in middleware and old not in middleware:
# it signs in as well; a page whose session ended does not say so, and a form sent then is lost
return [
Warning(
"MIDDLEWARE uses Django's LoginRequiredMiddleware, not the panel's.",
hint=f"data/local_settings.py sets MIDDLEWARE: replace '{django_s}' with '{required}', "
"as webvirtcloud/settings.py has it.",
id="accounts.W002",
)
]
if old in middleware or required not in middleware:
return [
Error(
"MIDDLEWARE must use Django's LoginRequiredMiddleware.",
"MIDDLEWARE must use the panel's LoginRequiredMiddleware.",
hint=f"data/local_settings.py sets MIDDLEWARE: replace '{old}' with '{required}' "
"and delete LOGIN_REQUIRED_IGNORE_VIEW_NAMES, as webvirtcloud/settings.py has it.",
id="accounts.E002",

View file

@ -4,7 +4,8 @@ from django.test import SimpleTestCase, override_settings
from accounts.checks import login_required_middleware_check
OLD = "login_required.middleware.LoginRequiredMiddleware"
NEW = "django.contrib.auth.middleware.LoginRequiredMiddleware"
NEW = "webvirtcloud.middleware.LoginRequiredMiddleware"
DJANGO = "django.contrib.auth.middleware.LoginRequiredMiddleware"
class LoginRequiredMiddlewareCheckTestCase(SimpleTestCase):
@ -19,5 +20,9 @@ class LoginRequiredMiddlewareCheckTestCase(SimpleTestCase):
old = [OLD if m == NEW else m for m in settings.MIDDLEWARE]
self.assertEqual(self.ids(old), ["accounts.E002"])
def test_django_s_own_is_warned_of(self):
# it signs in too: an update with it in data/local_settings.py still starts the panel
self.assertEqual(self.ids([DJANGO if m == NEW else m for m in settings.MIDDLEWARE]), ["accounts.W002"])
def test_missing_login_middleware_is_rejected(self):
self.assertEqual(self.ids([m for m in settings.MIDDLEWARE if m != NEW]), ["accounts.E002"])

Binary file not shown.

View file

@ -13150,3 +13150,15 @@ msgstr "%(job)s iptal edilsin mi? Olduğu yerde durur."
#, python-format
msgid "Block %(name)s? They are signed out and their API tokens are deleted; unblocking does not bring the tokens back."
msgstr "%(name)s engellensin mi? Oturumları kapatılır ve API anahtarları silinir; engeli kaldırmak anahtarları geri getirmez."
#: webvirtcloud/middleware.py
msgid "You were signed out, so it was not done: sign in and do it again."
msgstr "Oturumunuz kapanmıştı, bu yüzden işlem yapılmadı: giriş yapıp yeniden deneyin."
#: templates/base.html
msgid "You were signed out: this page is no longer updated."
msgstr "Oturumunuz kapandı: bu sayfa artık güncellenmiyor."
#: templates/base.html
msgid "Sign in again"
msgstr "Yeniden giriş yapın"

Binary file not shown.

View file

@ -12321,3 +12321,15 @@ msgstr "取消 %(job)s?它将停在当前进度。"
#, python-format
msgid "Block %(name)s? They are signed out and their API tokens are deleted; unblocking does not bring the tokens back."
msgstr "禁用 %(name)s?其登录将被注销,API 令牌将被删除;解除禁用不会恢复这些令牌。"
#: webvirtcloud/middleware.py
msgid "You were signed out, so it was not done: sign in and do it again."
msgstr "您已退出登录,因此操作未执行:请登录后重试。"
#: templates/base.html
msgid "You were signed out: this page is no longer updated."
msgstr "您已退出登录:此页面不再更新。"
#: templates/base.html
msgid "Sign in again"
msgstr "重新登录"

View file

@ -1,7 +1,8 @@
// Reloads the page while it shows an active job, so the page follows the job to its end.
setInterval(function () {
// not while a form is filled in or a dialog asks (a job's Cancel)
if (!document.hidden && !document.querySelector("form :focus, .modal.show")) {
// not while a form is filled in or a dialog asks (a job's Cancel); a page whose session
// ended stays as it is: a 401 to its job panel said so (session_end.js)
if (!document.hidden && !window.sessionEnded && !document.querySelector("form :focus, .modal.show")) {
window.location.reload();
}
}, 5000);

View file

@ -105,10 +105,8 @@
button.disabled = true;
var url = text.url + "?" + new URLSearchParams({q: form.elements.q.value});
fetch(url, {headers: {"X-Requested-With": "XMLHttpRequest"}}).then(function (response) {
if (response.redirected) {
// signed out meanwhile: reloading goes to the login form, then back here
location.reload();
return new Promise(function () {});
if (response.status === 401) {
return {error: sessionEnd()}; // signed out meanwhile (session_end.js)
}
return response.json();
}).catch(function () {

View file

@ -14,8 +14,8 @@ function pollWhileVisible(interval, request, onData, firstDelay) {
function run() {
timer = null;
if (stopped || document.hidden) {
return;
if (stopped || document.hidden || window.sessionEnded) {
return; // a page whose session ended asks nothing more (session_end.js)
}
running = true;
request()
@ -58,5 +58,6 @@ function pageInUse() {
|| !!(active && active.matches && active.matches("input, select, textarea"))
|| !!(window.xmlEditUnsaved && window.xmlEditUnsaved())
|| (typeof bulkPowerChosen === "function" && bulkPowerChosen()) // the VM list's bulk form in use (bulk_power.js)
|| !!document.querySelector("button[data-busy]"); // a form being sent (submit_busy.js)
|| !!document.querySelector("button[data-busy]") // a form being sent (submit_busy.js)
|| !!window.sessionEnded; // signed out: the page keeps its notice (session_end.js)
}

25
static/js/session_end.js Normal file
View file

@ -0,0 +1,25 @@
// A session that ends while the page is open: a script's request is answered 401
// (webvirtcloud.middleware.LoginRequiredMiddleware). sessionEnd() says so, with a link to sign
// in and come back here, and the page stops asking and reloading (poll.js, pageInUse): what it
// shows is no longer updated. A jQuery request's 401 calls it; a fetch's caller does. Gives
// the words it shows.
function sessionEnd() {
var notice = document.getElementById("session-ended");
if (notice && !window.sessionEnded) {
window.sessionEnded = true;
var link = document.createElement("a");
link.className = "alert-link";
link.href = notice.dataset.href;
link.textContent = notice.dataset.link;
notice.className = "alert alert-warning";
notice.setAttribute("role", "alert");
notice.replaceChildren(notice.dataset.text + " ", link);
notice.hidden = false;
}
return notice ? notice.dataset.text : "";
}
$(document).ajaxError(function (event, xhr) {
if (xhr.status === 401) {
sessionEnd();
}
});

View file

@ -44,6 +44,9 @@
return fetch(form.action, {
method: "POST", body: data, redirect: "manual", headers: {"X-Requested-With": "XMLHttpRequest"},
}).then(function (response) {
if (response.status === 401) {
return {error: sessionEnd()}; // signed out meanwhile (session_end.js): the edit stays
}
return response.json();
}).then(function (answer) {
return {diff: answer.diff, saved: answer.saved, error: answer.error || answer.detail};

View file

@ -49,6 +49,11 @@
</div>
</div>
{% endblock page_header %}
{% if request.user.is_authenticated %}
{# the words session_end.js shows when the session ends while the page is open #}
<div id="session-ended" hidden data-text="{% trans "You were signed out: this page is no longer updated." %}"
data-link="{% trans "Sign in again" %}" data-href="{% url 'accounts:login' %}?next={{ request.get_full_path|urlencode }}"></div>
{% endif %}
<div id="messages">{% bootstrap_messages %}</div>
{% block content %}{% endblock %}
</div>
@ -79,6 +84,7 @@
<script src="{% static 'js/bootstrap.bundle.min.js' %}"></script>
<script src="{% static 'js/confirm_dialog.js' %}"></script>
<script src="{% static 'js/submit_busy.js' %}"></script>
<script src="{% static 'js/session_end.js' %}"></script>
<!-- Table sorting -->
<script src="{% static 'js/tablesort.min.js' %}"></script>
<script src="{% static 'js/tablesort.number.min.js' %}"></script>

View file

@ -7,6 +7,9 @@
var pane = document.getElementById("backups");
var hidden = pane && pane.classList.contains("tab-pane") && !pane.classList.contains("active");
var busy = document.querySelector(".dropdown-menu.show, .modal.show, input:focus, select:focus, textarea:focus");
if (window.sessionEnded) {
return; // signed out: the page keeps its notice (session_end.js)
}
if (hidden || busy || document.hidden) {
setTimeout(check, 4000);
} else {

View file

@ -1,11 +1,17 @@
import re
import uuid
from urllib.parse import urlsplit
from django.conf import settings
from django.contrib import messages
from django.http import JsonResponse
from django.shortcuts import redirect, render
from django.contrib.auth import middleware as auth_middleware
from django.contrib.auth.views import redirect_to_login
from django.http import HttpResponse, JsonResponse
from django.shortcuts import redirect, render, resolve_url
from django.utils.http import url_has_allowed_host_and_scheme
from django.utils.translation import gettext_lazy as _
from django.views import csrf
import libvirt
from libvirt import libvirtError
from logs.audit import request_ip, write
@ -37,6 +43,33 @@ def same_origin_referer(request, default):
return default
class LoginRequiredMiddleware(auth_middleware.LoginRequiredMiddleware):
"""Django's, for a session that ended while a page was open. A page's script asking (an XHR)
gets 401, which session_end.js tells the user about, not the sign-in page. A form sent (a POST)
is not asked for again by GET after the sign-in, where its view would answer 405: the sign-in
goes back to the page the form was on, and says it was not done."""
def handle_no_permission(self, request, view_func):
if request.headers.get("x-requested-with") == "XMLHttpRequest":
return HttpResponse(status=401)
if request.method not in ("POST", "PUT", "PATCH", "DELETE"):
return super().handle_no_permission(request, view_func)
messages.info(request, _("You were signed out, so it was not done: sign in and do it again."))
page = urlsplit(same_origin_referer(request, "/"))
# a form shown again at its own address (one with errors): that answers POST only
back = "/" if page.path == request.path else page.path + (f"?{page.query}" if page.query else "")
return redirect_to_login(back, resolve_url(self.get_login_url(view_func)), self.get_redirect_field_name(view_func))
def csrf_failure(request, reason=""):
"""A form sent with a token no longer good. After a session ended (a sign-in elsewhere
gives a new token), as LoginRequiredMiddleware does for it; else, and for the sign-in
form itself, Django's 403."""
if not request.user.is_authenticated and request.path != resolve_url(settings.LOGIN_URL):
return LoginRequiredMiddleware(lambda request: None).handle_no_permission(request, None)
return csrf.csrf_failure(request, reason)
def error_text(request, exception):
"""
The libvirt error to show. Administrators (superusers and the global

View file

@ -114,7 +114,7 @@ MIDDLEWARE = [
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django_otp.middleware.OTPMiddleware",
"django.contrib.auth.middleware.LoginRequiredMiddleware",
"webvirtcloud.middleware.LoginRequiredMiddleware",
"accounts.middleware.ForcePasswordChangeMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
@ -201,6 +201,8 @@ AUTH_PASSWORD_VALIDATORS = [
]
LOGIN_URL = "/accounts/login/"
# a form sent after the session ended goes to sign in, not to a 403
CSRF_FAILURE_VIEW = "webvirtcloud.middleware.csrf_failure"
# Tests create users by the thousand: a fast hash for them (manage.py test only)
if sys.argv[1:2] == ["test"]:

View file

@ -18,6 +18,7 @@ function advance(ms) {
}
const listeners = {};
global.document = { hidden: false, addEventListener: (ev, fn) => { listeners[ev] = fn; } };
global.window = {};
function setHidden(h) { document.hidden = h; listeners.visibilitychange(); }
// requests: each returns a promise that the test settles. Like jQuery, it runs

View file

@ -0,0 +1,61 @@
"""A session that ends while a page is open: its scripts are told so (401), and a form
sent then goes back to its page after the sign-in, said not done, not to a 405."""
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 lxml import html
from computes.models import Compute
from instances.models import Instance
class SessionEndTests(TestCase):
def setUp(self):
compute = Compute.objects.create(name="se-host", hostname="192.0.2.11", login="", password="", type=4)
self.vm = Instance.objects.create(compute=compute, name="se-vm", uuid="00000000-0000-4000-8000-0000000000dd")
self.page = reverse("instances:instance", args=[self.vm.pk])
def test_a_script_asking_is_answered_401(self):
response = self.client.get(reverse("instances:states"), HTTP_X_REQUESTED_WITH="XMLHttpRequest")
self.assertEqual(response.status_code, 401)
def test_a_page_asked_signs_in_and_comes_back(self):
response = self.client.get(self.page)
self.assertRedirects(response, reverse("accounts:login") + f"?next={self.page}", fetch_redirect_response=False)
def test_a_form_sent_comes_back_to_its_page_and_says_it_was_not_done(self):
response = self.client.post(reverse("instances:poweron", args=[self.vm.pk]),
HTTP_REFERER=f"http://testserver{self.page}?x=1#power")
self.assertRedirects(response, reverse("accounts:login") + "?next=" + self.page + "%3Fx%3D1",
fetch_redirect_response=False)
self.assertEqual([str(m) for m in get_messages(response.wsgi_request)],
["You were signed out, so it was not done: sign in and do it again."])
# a Referer from elsewhere: the home page
response = self.client.post(reverse("instances:poweron", args=[self.vm.pk]), HTTP_REFERER="https://example.com/x")
self.assertRedirects(response, reverse("accounts:login") + "?next=/", fetch_redirect_response=False)
def test_a_form_shown_again_at_its_own_address_goes_home(self):
# an API token form with errors answers at the create address, which takes POST only
create = reverse("accounts:api_token_create")
response = self.client.post(create, HTTP_REFERER=f"http://testserver{create}")
self.assertRedirects(response, reverse("accounts:login") + "?next=/", fetch_redirect_response=False)
def test_an_options_request_is_not_said_lost(self):
response = self.client.options(self.page)
self.assertEqual(get_messages(response.wsgi_request)._queued_messages, [])
def test_a_stale_token_after_the_end_goes_to_sign_in(self):
from django.test import Client
client = Client(enforce_csrf_checks=True)
response = client.post(reverse("instances:poweron", args=[self.vm.pk]), HTTP_REFERER=f"http://testserver{self.page}")
self.assertRedirects(response, reverse("accounts:login") + f"?next={self.page}", fetch_redirect_response=False)
# the sign-in form itself: Django's 403, as before
self.assertEqual(client.post(reverse("accounts:login"), {"username": "x", "password": "y"}).status_code, 403)
def test_a_signed_in_page_has_the_notice_hidden(self):
self.client.force_login(get_user_model().objects.create_superuser("se-admin", "se@example.com", "pw"))
(notice,) = html.fromstring(self.client.get(reverse("instances:index")).content).xpath("//*[@id='session-ended']")
self.assertIsNotNone(notice.get("hidden"))
self.assertIn("next=/instances/", notice.get("data-href"))