From c699384cba388ce7c27d3b8cadfa4498aa482297 Mon Sep 17 00:00:00 2001 From: Andres Schumann Date: Mon, 23 Nov 2026 19:08:47 +0100 Subject: [PATCH] Make session cookie SameSite configurable from global configuration Add the Session cookie SameSite global setting (Security, default Strict, accepts Lax or Strict). A module installed from ready() overrides the SESSION_COOKIE_SAMESITE lookup so the value is read from the configuration at request time. The override is verified at startup and reverted to the Django default if it does not take effect. Tests cover the default, values saved from the web, invalid values, the Set-Cookie attribute produced by SessionMiddleware, shadowed lookups and the revert path. --- src/uds/__init__.py | 4 + src/uds/core/util/config.py | 14 +++ src/uds/core/util/session_samesite.py | 98 ++++++++++++++++++++ tests/core/util/test_session_samesite.py | 113 +++++++++++++++++++++++ 4 files changed, 229 insertions(+) create mode 100644 src/uds/core/util/session_samesite.py create mode 100644 tests/core/util/test_session_samesite.py diff --git a/src/uds/__init__.py b/src/uds/__init__.py index 7d144d08c..ef42f7ddf 100644 --- a/src/uds/__init__.py +++ b/src/uds/__init__.py @@ -83,6 +83,10 @@ def ready(self) -> None: from . import plugins as plugins from . import REST as REST + from .core.util import session_samesite + + session_samesite.install() + default_app_config = "uds.UDSAppConfig" diff --git a/src/uds/core/util/config.py b/src/uds/core/util/config.py index dada1beb3..a3bb162f1 100644 --- a/src/uds/core/util/config.py +++ b/src/uds/core/util/config.py @@ -431,6 +431,10 @@ def get_config_values( } +SESSION_COOKIE_SAMESITE_VALUES: typing.Final[tuple[str, ...]] = ("Lax", "Strict") +SESSION_COOKIE_SAMESITE_DEFAULT: typing.Final[str] = "Strict" + + class GlobalConfig: """ Simple helper to keep track of global configuration @@ -539,6 +543,16 @@ class GlobalConfig: help=_("Enable enhanced security modules"), group=Config.GroupType.HARDENING, ) + SESSION_COOKIE_SAMESITE: Config.Value = Config.section(Config.SectionType.SECURITY).value( + "Session cookie SameSite", + SESSION_COOKIE_SAMESITE_DEFAULT, + type=Config.FieldType.TEXT, + help=_( + "SameSite policy of the session cookie: Lax or Strict. Lax is required for SSO " + "logins (SAML, OAuth2, EntraID) to keep the session after the identity provider redirects back" + ), + group=Config.GroupType.HARDENING, + ) # Password complexity enforcement. Applies when an # administrator sets the password of a user that lives in the internal # database (i.e. not synchronized from an external source). diff --git a/src/uds/core/util/session_samesite.py b/src/uds/core/util/session_samesite.py new file mode 100644 index 000000000..c7426ad2f --- /dev/null +++ b/src/uds/core/util/session_samesite.py @@ -0,0 +1,98 @@ +# +# Copyright (c) 2026 Virtual Cable S.L.U. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L.U. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +""" +Author: Andres Schumann, aschumann at virtualcable dot es +""" + +import logging +import typing + +from django.conf import LazySettings, global_settings, settings + +from uds.core.util.config import ( + SESSION_COOKIE_SAMESITE_DEFAULT, + SESSION_COOKIE_SAMESITE_VALUES, + GlobalConfig, +) + +logger: logging.Logger = logging.getLogger(__name__) + +SETTING_NAME: typing.Final[str] = "SESSION_COOKIE_SAMESITE" + +_django_getattr: typing.Callable[[typing.Any, str], typing.Any] | None = None + + +def configured_value() -> str: + # force=True: the config cache is per process and this runs only when a session cookie is written, + # so reading the database here keeps every worker on the value saved from the web. + value = GlobalConfig.SESSION_COOKIE_SAMESITE.as_str(force=True) + if value in SESSION_COOKIE_SAMESITE_VALUES: + return value + logger.warning( + "Invalid %s '%s' in global configuration, using %s", + SETTING_NAME, + value, + SESSION_COOKIE_SAMESITE_DEFAULT, + ) + return SESSION_COOKIE_SAMESITE_DEFAULT + + +def _getattr(wrapped: typing.Any, name: str) -> typing.Any: + if name == SETTING_NAME: + return configured_value() + assert _django_getattr is not None + return _django_getattr(wrapped, name) + + +def _verify() -> bool: + # Django caches attribute lookups in the settings __dict__; a cached entry would bypass _getattr. + return settings.SESSION_COOKIE_SAMESITE == configured_value() + + +def install() -> None: + global _django_getattr + if _django_getattr is not None: + return + + _django_getattr = LazySettings.__getattr__ + del settings.SESSION_COOKIE_SAMESITE # Removes the file value, so the lookup reaches _getattr + LazySettings.__getattr__ = _getattr # type: ignore[method-assign] # Django offers no hook for per-key lookups + + if not _verify(): + logger.error("%s override is not effective, reverting to the Django default", SETTING_NAME) + uninstall() + + +def uninstall() -> None: + global _django_getattr + if _django_getattr is None: + return + + LazySettings.__getattr__ = _django_getattr # type: ignore[method-assign] + _django_getattr = None + settings.SESSION_COOKIE_SAMESITE = global_settings.SESSION_COOKIE_SAMESITE diff --git a/tests/core/util/test_session_samesite.py b/tests/core/util/test_session_samesite.py new file mode 100644 index 000000000..732e7325d --- /dev/null +++ b/tests/core/util/test_session_samesite.py @@ -0,0 +1,113 @@ +# +# Copyright (c) 2026 Virtual Cable S.L.U. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of Virtual Cable S.L.U. nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +""" +Author: Andres Schumann, aschumann at virtualcable dot es +""" + +import importlib +from unittest import mock + +from django.conf import LazySettings, global_settings, settings +from django.contrib.sessions.middleware import SessionMiddleware +from django.http import HttpResponse +from django.test import RequestFactory + +from uds.core.util import session_samesite +from uds.core.util.config import SESSION_COOKIE_SAMESITE_DEFAULT, GlobalConfig +from uds.models.config import Config as DBConfig + +from ...utils.test import UDSTestCase + + +class SessionSameSiteTest(UDSTestCase): + def setUp(self) -> None: + super().setUp() + GlobalConfig.SESSION_COOKIE_SAMESITE.get(force=True) + session_samesite.install() + + def tearDown(self) -> None: + session_samesite.install() + super().tearDown() + + def session_cookie_samesite(self) -> str: + request = RequestFactory().get("/") + engine = importlib.import_module(settings.SESSION_ENGINE) + request.session = engine.SessionStore() + request.session["probe"] = "value" + middleware = SessionMiddleware(lambda _: HttpResponse()) + response = middleware.process_response(request, HttpResponse()) + return str(response.cookies[settings.SESSION_COOKIE_NAME]["samesite"]) + + def test_default_is_strict_when_not_saved(self) -> None: + self.assertEqual(SESSION_COOKIE_SAMESITE_DEFAULT, "Strict") + DBConfig.objects.filter( + section=GlobalConfig.SESSION_COOKIE_SAMESITE.section(), + key=GlobalConfig.SESSION_COOKIE_SAMESITE.key(), + ).delete() + + self.assertEqual(settings.SESSION_COOKIE_SAMESITE, "Strict") + self.assertEqual(self.session_cookie_samesite(), "Strict") + + def test_value_saved_from_web_is_applied_to_session_cookie(self) -> None: + for value in ("Lax", "Strict"): + with self.subTest(value=value): + GlobalConfig.SESSION_COOKIE_SAMESITE.set(value) + + self.assertEqual(settings.SESSION_COOKIE_SAMESITE, value) + self.assertEqual(self.session_cookie_samesite(), value) + + def test_invalid_value_falls_back_to_default(self) -> None: + GlobalConfig.SESSION_COOKIE_SAMESITE.set("None") + + with self.assertLogs(session_samesite.logger, level="WARNING"): + value = settings.SESSION_COOKIE_SAMESITE + + self.assertEqual(value, SESSION_COOKIE_SAMESITE_DEFAULT) + + def test_verification_detects_setting_shadowed_in_cache(self) -> None: + GlobalConfig.SESSION_COOKIE_SAMESITE.set("Strict") + self.assertTrue(session_samesite._verify()) + + settings.__dict__[session_samesite.SETTING_NAME] = "Lax" + try: + self.assertFalse(session_samesite._verify()) + finally: + del settings.__dict__[session_samesite.SETTING_NAME] + + def test_failed_verification_reverts_to_django_default(self) -> None: + django_getattr = session_samesite._django_getattr + self.assertIsNotNone(django_getattr) + session_samesite.uninstall() + try: + with mock.patch.object(session_samesite, "_verify", return_value=False): + session_samesite.install() + + self.assertIs(LazySettings.__getattr__, django_getattr) + self.assertEqual(settings.SESSION_COOKIE_SAMESITE, global_settings.SESSION_COOKIE_SAMESITE) + finally: + session_samesite.install()