2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-07-07 06:00:57 +00:00

fix(backend) : use correct settings patching (#9910)

* fix(backend): use correct settings patching

* and more fixes

* fix context in test

* add better test for cors
This commit is contained in:
Matthias Mair
2025-07-02 02:35:27 +02:00
committed by GitHub
parent 252c74ab9f
commit dea8b4f0ad
8 changed files with 78 additions and 91 deletions

View File

@ -1,6 +1,7 @@
"""Middleware for InvenTree.""" """Middleware for InvenTree."""
import sys import sys
from urllib.parse import urlsplit
from django.conf import settings from django.conf import settings
from django.contrib.auth.middleware import PersistentRemoteUserMiddleware from django.contrib.auth.middleware import PersistentRemoteUserMiddleware
@ -8,6 +9,7 @@ from django.http import HttpResponse
from django.shortcuts import redirect, render from django.shortcuts import redirect, render
from django.urls import resolve, reverse_lazy from django.urls import resolve, reverse_lazy
from django.utils.deprecation import MiddlewareMixin from django.utils.deprecation import MiddlewareMixin
from django.utils.http import is_same_domain
import structlog import structlog
from error_report.middleware import ExceptionProcessor from error_report.middleware import ExceptionProcessor
@ -242,9 +244,13 @@ class InvenTreeHostSettingsMiddleware(MiddlewareMixin):
) )
# Check trusted origins # Check trusted origins
referer = urlsplit(accessed_scheme)
if not any( if not any(
accessed_scheme.startswith(origin) is_same_domain(referer.netloc, host)
for host in [
urlsplit(origin).netloc.lstrip('*')
for origin in settings.CSRF_TRUSTED_ORIGINS for origin in settings.CSRF_TRUSTED_ORIGINS
]
): ):
msg = f'INVE-E7: The used path `{accessed_scheme}` is not in the TRUSTED_ORIGINS' msg = f'INVE-E7: The used path `{accessed_scheme}` is not in the TRUSTED_ORIGINS'
logger.error(msg) logger.error(msg)

View File

@ -1,6 +1,5 @@
"""Test the sso and auth module functionality.""" """Test the sso and auth module functionality."""
from django.conf import settings
from django.contrib.auth.models import Group, User from django.contrib.auth.models import Group, User
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.test import override_settings from django.test import override_settings
@ -130,12 +129,10 @@ class EmailSettingsContext:
def __enter__(self): def __enter__(self):
"""Enable stuff.""" """Enable stuff."""
InvenTreeSetting.set_setting('LOGIN_ENABLE_REG', True) InvenTreeSetting.set_setting('LOGIN_ENABLE_REG', True)
settings.EMAIL_HOST = 'localhost'
def __exit__(self, type, value, traceback): def __exit__(self, type, value, traceback):
"""Exit stuff.""" """Exit stuff."""
InvenTreeSetting.set_setting('LOGIN_ENABLE_REG', False) InvenTreeSetting.set_setting('LOGIN_ENABLE_REG', False)
settings.EMAIL_HOST = ''
class TestAuth(InvenTreeAPITestCase): class TestAuth(InvenTreeAPITestCase):
@ -185,7 +182,7 @@ class TestAuth(InvenTreeAPITestCase):
self.post(self.reg_url, self.email_args(), expected_code=403) self.post(self.reg_url, self.email_args(), expected_code=403)
# Enable registration - now it should work # Enable registration - now it should work
with EmailSettingsContext(): with self.settings(EMAIL_HOST='localhost') as _, EmailSettingsContext() as _:
resp = self.post(self.reg_url, self.email_args(), expected_code=200) resp = self.post(self.reg_url, self.email_args(), expected_code=200)
self.assertEqual(resp.json()['data']['user']['email'], self.test_email) self.assertEqual(resp.json()['data']['user']['email'], self.test_email)
@ -216,6 +213,6 @@ class TestAuth(InvenTreeAPITestCase):
self.assertIn('The provided email domain is not approved.', str(resp.json())) self.assertIn('The provided email domain is not approved.', str(resp.json()))
# Right format should work # Right format should work
with EmailSettingsContext(): with self.settings(EMAIL_HOST='localhost') as _, EmailSettingsContext() as _:
resp = self.post(self.reg_url, self.email_args(), expected_code=200) resp = self.post(self.reg_url, self.email_args(), expected_code=200)
self.assertEqual(resp.json()['data']['user']['email'], self.test_email) self.assertEqual(resp.json()['data']['user']['email'], self.test_email)

View File

@ -1,6 +1,5 @@
"""Tests for middleware functions.""" """Tests for middleware functions."""
from django.conf import settings
from django.http import Http404 from django.http import Http404
from django.urls import reverse from django.urls import reverse
@ -81,7 +80,7 @@ class MiddlewareTests(InvenTreeTestCase):
log_error('testpath') log_error('testpath')
# Test setup without ignored errors # Test setup without ignored errors
settings.IGNORED_ERRORS = [] with self.settings(IGNORED_ERRORS=[]):
try: try:
raise Http404 raise Http404
except Http404: except Http404:
@ -133,3 +132,11 @@ class MiddlewareTests(InvenTreeTestCase):
self.assertNotContains( self.assertNotContains(
response, 'window.INVENTREE_SETTINGS', status_code=500 response, 'window.INVENTREE_SETTINGS', status_code=500
) )
with self.settings(
SITE_URL='http://testserver', CSRF_TRUSTED_ORIGINS=['http://*.testserver']
):
response = self.client.get(reverse('web'))
self.assertEqual(response.status_code, 200)
self.assertNotContains(response, 'INVE-E7')
self.assertContains(response, 'window.INVENTREE_SETTINGS')

View File

@ -1153,8 +1153,7 @@ class TestSettings(InvenTreeTestCase):
# add shortcut # add shortcut
user_count = user_model.objects.count user_count = user_model.objects.count
# enable testing mode # enable testing mode
settings.TESTING_ENV = True with self.settings(TESTING_ENV=True):
# nothing set # nothing set
self.run_reload() self.run_reload()
self.assertEqual(user_count(), 1) self.assertEqual(user_count(), 1)
@ -1186,9 +1185,6 @@ class TestSettings(InvenTreeTestCase):
}) })
self.assertEqual(user_count(), 3) self.assertEqual(user_count(), 3)
# make sure to clean up
settings.TESTING_ENV = False
def test_initial_install(self): def test_initial_install(self):
"""Test if install of plugins on startup works.""" """Test if install of plugins on startup works."""
from common.settings import set_global_setting from common.settings import set_global_setting

View File

@ -1,6 +1,5 @@
"""Unit tests for event_sample sample plugins.""" """Unit tests for event_sample sample plugins."""
from django.conf import settings
from django.test import TestCase from django.test import TestCase
from common.models import InvenTreeSetting from common.models import InvenTreeSetting
@ -23,15 +22,12 @@ class EventPluginSampleTests(TestCase):
InvenTreeSetting.set_setting('ENABLE_PLUGINS_EVENTS', True, change_user=None) InvenTreeSetting.set_setting('ENABLE_PLUGINS_EVENTS', True, change_user=None)
# Enable event testing # Enable event testing
settings.PLUGIN_TESTING_EVENTS = True with self.settings(PLUGIN_TESTING_EVENTS=True):
# Check that an event is issued # Check that an event is issued
with self.assertLogs(logger='inventree', level='DEBUG') as cm: with self.assertLogs(logger='inventree', level='DEBUG') as cm:
trigger_event('test.event') trigger_event('test.event')
self.assertIn('Event `test.event` triggered in sample plugin', str(cm[1])) self.assertIn('Event `test.event` triggered in sample plugin', str(cm[1]))
# Disable again
settings.PLUGIN_TESTING_EVENTS = False
def test_mixin(self): def test_mixin(self):
"""Test that MixinNotImplementedError is raised.""" """Test that MixinNotImplementedError is raised."""
with self.assertRaises(MixinNotImplementedError): with self.assertRaises(MixinNotImplementedError):

View File

@ -1,6 +1,5 @@
"""Unit tests for event_sample sample plugins.""" """Unit tests for event_sample sample plugins."""
from django.conf import settings
from django.test import TestCase from django.test import TestCase
from common.models import InvenTreeSetting from common.models import InvenTreeSetting
@ -21,15 +20,12 @@ class FilteredEventPluginSampleTests(TestCase):
InvenTreeSetting.set_setting('ENABLE_PLUGINS_EVENTS', True, change_user=None) InvenTreeSetting.set_setting('ENABLE_PLUGINS_EVENTS', True, change_user=None)
# Enable event testing # Enable event testing
settings.PLUGIN_TESTING_EVENTS = True with self.settings(PLUGIN_TESTING_EVENTS=True):
# Check that an event is issued # Check that an event is issued
with self.assertLogs(logger='inventree', level='DEBUG') as cm: with self.assertLogs(logger='inventree', level='DEBUG') as cm:
trigger_event('test.event') trigger_event('test.event')
self.assertIn('Event `test.event` triggered in sample plugin', str(cm[1])) self.assertIn('Event `test.event` triggered in sample plugin', str(cm[1]))
# Disable again
settings.PLUGIN_TESTING_EVENTS = False
def test_ignore_event(self): def test_ignore_event(self):
"""Check if the event is issued.""" """Check if the event is issued."""
# Activate plugin # Activate plugin
@ -40,7 +36,7 @@ class FilteredEventPluginSampleTests(TestCase):
InvenTreeSetting.set_setting('ENABLE_PLUGINS_EVENTS', True, change_user=None) InvenTreeSetting.set_setting('ENABLE_PLUGINS_EVENTS', True, change_user=None)
# Enable event testing # Enable event testing
settings.PLUGIN_TESTING_EVENTS = True with self.settings(PLUGIN_TESTING_EVENTS=True):
# Check that an event is issued # Check that an event is issued
with self.assertLogs(logger='inventree', level='DEBUG') as cm: with self.assertLogs(logger='inventree', level='DEBUG') as cm:
trigger_event('test.some.other.event') trigger_event('test.some.other.event')
@ -48,6 +44,3 @@ class FilteredEventPluginSampleTests(TestCase):
'DEBUG:inventree:Event `test.some.other.event` triggered in sample plugin', 'DEBUG:inventree:Event `test.some.other.event` triggered in sample plugin',
cm[1], cm[1],
) )
# Disable again
settings.PLUGIN_TESTING_EVENTS = False

View File

@ -1,6 +1,5 @@
"""Tests for general API tests for the plugin app.""" """Tests for general API tests for the plugin app."""
from django.conf import settings
from django.test import override_settings from django.test import override_settings
from django.urls import reverse from django.urls import reverse
@ -92,9 +91,8 @@ class PluginDetailAPITest(PluginMixin, InvenTreeAPITestCase):
) )
# install disabled # install disabled
settings.PLUGINS_INSTALL_DISABLED = True with self.settings(PLUGINS_INSTALL_DISABLED=True):
self.post(url, {}, expected_code=400) self.post(url, {}, expected_code=400)
settings.PLUGINS_INSTALL_DISABLED = False
def test_plugin_activate(self): def test_plugin_activate(self):
"""Test the plugin activate.""" """Test the plugin activate."""

View File

@ -10,7 +10,6 @@ from pathlib import Path
from unittest import mock from unittest import mock
from unittest.mock import patch from unittest.mock import patch
from django.conf import settings
from django.test import TestCase, override_settings from django.test import TestCase, override_settings
import plugin.templatetags.plugin_extras as plugin_tags import plugin.templatetags.plugin_extras as plugin_tags
@ -410,9 +409,7 @@ class RegistryTests(TestCase):
# Check that the registry is not reloaded # Check that the registry is not reloaded
self.assertFalse(registry.check_reload()) self.assertFalse(registry.check_reload())
settings.TESTING = False with self.settings(TESTING=False, PLUGIN_TESTING_RELOAD=True):
settings.PLUGIN_TESTING_RELOAD = True
# Check that the registry is reloaded # Check that the registry is reloaded
registry.reload_plugins(full_reload=True, collect=True, force_reload=True) registry.reload_plugins(full_reload=True, collect=True, force_reload=True)
self.assertFalse(registry.check_reload()) self.assertFalse(registry.check_reload())
@ -420,6 +417,3 @@ class RegistryTests(TestCase):
# Check that changed hashes run through # Check that changed hashes run through
registry.registry_hash = 'abc' registry.registry_hash = 'abc'
self.assertTrue(registry.check_reload()) self.assertTrue(registry.check_reload())
settings.TESTING = True
settings.PLUGIN_TESTING_RELOAD = False