[bug] Fix boolean casting for INVENTREE_LOGIN_ENFORCE_MFA (#13400)

Use str2bool to ensure that falsey strings are decoded as boolean False
This commit is contained in:
Oliver authored and GitHub committed 2026-11-27 11:50:59 +11:00
1 parent b0ffa90c05
commit a27f04cedf
2 files changed
+66 -4

No files matched your search

+14 -4
View File
@@ -14,10 +14,20 @@ from common.settings import get_global_setting
def mfa_enforced() -> bool:
"""Check if MFA is enforced globally for all users."""
return bool(
settings.MFA_ENABLED
and get_global_setting('LOGIN_ENFORCE_MFA', None, 'INVENTREE_LOGIN_ENFORCE_MFA')
"""Check if MFA is enforced globally for all users.
MFA enforcement is controlled by the LOGIN_ENFORCE_MFA global setting,
which can be overridden by the INVENTREE_LOGIN_ENFORCE_MFA environment variable.
"""
if not settings.MFA_ENABLED:
return False
return InvenTree.helpers.str2bool(
get_global_setting(
'LOGIN_ENFORCE_MFA',
backup_value=None,
environment_key='INVENTREE_LOGIN_ENFORCE_MFA',
)
)
+52
View File
@@ -1,6 +1,7 @@
"""Unit tests for the 'users' app."""
import datetime
import os
from unittest import mock
from django.apps import apps
@@ -764,3 +765,54 @@ class UserProfileMetadataPermissionTests(InvenTreeAPITestCase):
url = self._metadata_url(self.other_user.profile.pk)
self.get(url, expected_code=403)
self.patch(url, {'metadata': {'x': 1}}, expected_code=403)
class MfaEnforcedTest(TestCase):
"""Tests for the mfa_enforced helper function."""
def test_setting(self):
"""MFA enforcement follows the LOGIN_ENFORCE_MFA global setting."""
from users.authentication import mfa_enforced
with self.settings(MFA_ENABLED=True), mock.patch.dict('os.environ', {}):
# Ensure the environment variable is not set (restored after the block)
os.environ.pop('INVENTREE_LOGIN_ENFORCE_MFA', None)
set_global_setting('LOGIN_ENFORCE_MFA', False)
self.assertFalse(mfa_enforced())
set_global_setting('LOGIN_ENFORCE_MFA', True)
self.assertTrue(mfa_enforced())
set_global_setting('LOGIN_ENFORCE_MFA', False)
# Never enforced if MFA support is disabled on the server
with (
self.settings(MFA_ENABLED=False),
mock.patch.dict('os.environ', {'INVENTREE_LOGIN_ENFORCE_MFA': 'True'}),
):
self.assertFalse(mfa_enforced())
def test_environment(self):
"""The environment variable overrides the setting, and is parsed as a boolean."""
from users.authentication import mfa_enforced
set_global_setting('LOGIN_ENFORCE_MFA', False)
with self.settings(MFA_ENABLED=True):
for value in ['True', 'true', '1', 'yes']:
with mock.patch.dict(
'os.environ', {'INVENTREE_LOGIN_ENFORCE_MFA': value}
):
self.assertTrue(mfa_enforced(), value)
# "False-y" values must not enforce MFA
set_global_setting('LOGIN_ENFORCE_MFA', True)
for value in ['False', 'false', '0', 'no']:
with mock.patch.dict(
'os.environ', {'INVENTREE_LOGIN_ENFORCE_MFA': value}
):
self.assertFalse(mfa_enforced(), value)
set_global_setting('LOGIN_ENFORCE_MFA', False)