diff --git a/accounts/checks.py b/accounts/checks.py index 1ef972c6..50fb7fbc 100644 --- a/accounts/checks.py +++ b/accounts/checks.py @@ -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", diff --git a/accounts/tests/test_checks.py b/accounts/tests/test_checks.py index a49cd916..240362e9 100644 --- a/accounts/tests/test_checks.py +++ b/accounts/tests/test_checks.py @@ -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"]) diff --git a/locale/tr/LC_MESSAGES/django.mo b/locale/tr/LC_MESSAGES/django.mo index 16bac01b..385ffdb8 100644 Binary files a/locale/tr/LC_MESSAGES/django.mo and b/locale/tr/LC_MESSAGES/django.mo differ diff --git a/locale/tr/LC_MESSAGES/django.po b/locale/tr/LC_MESSAGES/django.po index 7544554c..c3a4eadc 100644 --- a/locale/tr/LC_MESSAGES/django.po +++ b/locale/tr/LC_MESSAGES/django.po @@ -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" diff --git a/locale/zh/LC_MESSAGES/django.mo b/locale/zh/LC_MESSAGES/django.mo index 3f782f6e..6df3351b 100644 Binary files a/locale/zh/LC_MESSAGES/django.mo and b/locale/zh/LC_MESSAGES/django.mo differ diff --git a/locale/zh/LC_MESSAGES/django.po b/locale/zh/LC_MESSAGES/django.po index 557a8b74..41ec1174 100644 --- a/locale/zh/LC_MESSAGES/django.po +++ b/locale/zh/LC_MESSAGES/django.po @@ -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 "重新登录" diff --git a/operations/static/operations/follow_active.js b/operations/static/operations/follow_active.js index 61cc6ff1..e304f9c0 100644 --- a/operations/static/operations/follow_active.js +++ b/operations/static/operations/follow_active.js @@ -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); diff --git a/static/js/find_address.js b/static/js/find_address.js index 2b15c3f3..95cacf90 100644 --- a/static/js/find_address.js +++ b/static/js/find_address.js @@ -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 () { diff --git a/static/js/poll.js b/static/js/poll.js index 325b5666..8734b43c 100644 --- a/static/js/poll.js +++ b/static/js/poll.js @@ -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) } diff --git a/static/js/session_end.js b/static/js/session_end.js new file mode 100644 index 00000000..270cce97 --- /dev/null +++ b/static/js/session_end.js @@ -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(); + } +}); diff --git a/static/js/xml_editor.js b/static/js/xml_editor.js index 7998bed8..8efd7daa 100644 --- a/static/js/xml_editor.js +++ b/static/js/xml_editor.js @@ -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}; diff --git a/templates/base.html b/templates/base.html index ac70ec29..80dc3e36 100644 --- a/templates/base.html +++ b/templates/base.html @@ -49,6 +49,11 @@ {% endblock page_header %} + {% if request.user.is_authenticated %} + {# the words session_end.js shows when the session ends while the page is open #} + + {% endif %}
{% bootstrap_messages %}
{% block content %}{% endblock %} @@ -79,6 +84,7 @@ + diff --git a/vmbackups/static/vmbackups/pending.js b/vmbackups/static/vmbackups/pending.js index f6c5c11d..a284460a 100644 --- a/vmbackups/static/vmbackups/pending.js +++ b/vmbackups/static/vmbackups/pending.js @@ -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 { diff --git a/webvirtcloud/middleware.py b/webvirtcloud/middleware.py index 4646976c..12580c2b 100644 --- a/webvirtcloud/middleware.py +++ b/webvirtcloud/middleware.py @@ -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 diff --git a/webvirtcloud/settings.py b/webvirtcloud/settings.py index 7811d069..ba81da6d 100644 --- a/webvirtcloud/settings.py +++ b/webvirtcloud/settings.py @@ -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"]: diff --git a/webvirtcloud/tests/js/poll.test.js b/webvirtcloud/tests/js/poll.test.js index 147be071..ee6564ad 100644 --- a/webvirtcloud/tests/js/poll.test.js +++ b/webvirtcloud/tests/js/poll.test.js @@ -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 diff --git a/webvirtcloud/tests/test_session_end.py b/webvirtcloud/tests/test_session_end.py new file mode 100644 index 00000000..232fc772 --- /dev/null +++ b/webvirtcloud/tests/test_session_end.py @@ -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"))