2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-04-28 11:36:44 +00:00

Site access updates (#6731)

* Throw error on invalid site access policy

- If ALLOWED_HOSTS is empty, exit
- If CSRF_TRUSTED_ORIGINS is empty, exit
- Closes https://github.com/inventree/InvenTree/issues/6730

* Set parameters for devcontainer

* Update documentation

* Ignore server exit in testing mode

* Add INVENTREE_SITE_URL to CI

* Further CI updates

* Update settings.py

* Unit test updates

* More unit test updates

* Bump API version

* Re-introduce checks in settings.py

- Allow more lenient behaviour in TESTING mode
This commit is contained in:
Oliver 2024-03-18 12:53:48 +11:00 committed by GitHub
parent 0c661f4f83
commit 23f0950a76
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 32 additions and 4 deletions

View File

@ -31,6 +31,8 @@ services:
INVENTREE_DB_USER: inventree_user INVENTREE_DB_USER: inventree_user
INVENTREE_DB_PASSWORD: inventree_password INVENTREE_DB_PASSWORD: inventree_password
INVENTREE_PLUGINS_ENABLED: True INVENTREE_PLUGINS_ENABLED: True
INVENTREE_SITE_URL: http://localhost:8000
INVENTREE_CORS_ORIGIN_ALLOW_ALL: True
INVENTREE_PY_ENV: /home/inventree/dev/venv INVENTREE_PY_ENV: /home/inventree/dev/venv
depends_on: depends_on:

View File

@ -20,6 +20,7 @@ env:
INVENTREE_MEDIA_ROOT: ../test_inventree_media INVENTREE_MEDIA_ROOT: ../test_inventree_media
INVENTREE_STATIC_ROOT: ../test_inventree_static INVENTREE_STATIC_ROOT: ../test_inventree_static
INVENTREE_BACKUP_DIR: ../test_inventree_backup INVENTREE_BACKUP_DIR: ../test_inventree_backup
INVENTREE_SITE_URL: http://localhost:8000
jobs: jobs:
paths-filter: paths-filter:
@ -132,6 +133,7 @@ jobs:
INVENTREE_PYTHON_TEST_SERVER: http://localhost:12345 INVENTREE_PYTHON_TEST_SERVER: http://localhost:12345
INVENTREE_PYTHON_TEST_USERNAME: testuser INVENTREE_PYTHON_TEST_USERNAME: testuser
INVENTREE_PYTHON_TEST_PASSWORD: testpassword INVENTREE_PYTHON_TEST_PASSWORD: testpassword
INVENTREE_SITE_URL: http://localhost:8000
outputs: outputs:
version: ${{ steps.version.outputs.version }} version: ${{ steps.version.outputs.version }}

View File

@ -22,6 +22,7 @@ jobs:
INVENTREE_MEDIA_ROOT: ./media INVENTREE_MEDIA_ROOT: ./media
INVENTREE_STATIC_ROOT: ./static INVENTREE_STATIC_ROOT: ./static
INVENTREE_BACKUP_DIR: ./backup INVENTREE_BACKUP_DIR: ./backup
INVENTREE_SITE_URL: http://localhost:8000
steps: steps:
- name: Checkout Code - name: Checkout Code

View File

@ -1,11 +1,14 @@
"""InvenTree API version information.""" """InvenTree API version information."""
# InvenTree API version # InvenTree API version
INVENTREE_API_VERSION = 184 INVENTREE_API_VERSION = 185
"""Increment this API version number whenever there is a significant change to the API that any clients need to know about.""" """Increment this API version number whenever there is a significant change to the API that any clients need to know about."""
INVENTREE_API_TEXT = """ INVENTREE_API_TEXT = """
v185 - 2024-03-18 : https://github.com/inventree/InvenTree/pull/6731
- Adds a default URL to the generated API schema (http://localhost:8000)
v184 - 2024-03-17 : https://github.com/inventree/InvenTree/pull/10464 v184 - 2024-03-17 : https://github.com/inventree/InvenTree/pull/10464
- Add additional fields for tests (start/end datetime, test station) - Add additional fields for tests (start/end datetime, test station)

View File

@ -1002,10 +1002,11 @@ if not ALLOWED_HOSTS:
'No ALLOWED_HOSTS specified. Defaulting to ["*"] for debug mode. This is not recommended for production use' 'No ALLOWED_HOSTS specified. Defaulting to ["*"] for debug mode. This is not recommended for production use'
) )
ALLOWED_HOSTS = ['*'] ALLOWED_HOSTS = ['*']
else: elif not TESTING:
logger.error( logger.error(
'No ALLOWED_HOSTS specified. Please provide a list of allowed hosts, or specify INVENTREE_SITE_URL' 'No ALLOWED_HOSTS specified. Please provide a list of allowed hosts, or specify INVENTREE_SITE_URL'
) )
sys.exit(-1)
# Ensure that the ALLOWED_HOSTS do not contain any scheme info # Ensure that the ALLOWED_HOSTS do not contain any scheme info
for i, host in enumerate(ALLOWED_HOSTS): for i, host in enumerate(ALLOWED_HOSTS):
@ -1025,6 +1026,12 @@ CSRF_TRUSTED_ORIGINS = get_setting(
if SITE_URL and SITE_URL not in CSRF_TRUSTED_ORIGINS: if SITE_URL and SITE_URL not in CSRF_TRUSTED_ORIGINS:
CSRF_TRUSTED_ORIGINS.append(SITE_URL) CSRF_TRUSTED_ORIGINS.append(SITE_URL)
if not TESTING and len(CSRF_TRUSTED_ORIGINS) == 0:
logger.error(
'No CSRF_TRUSTED_ORIGINS specified. Please provide a list of trusted origins, or specify INVENTREE_SITE_URL'
)
sys.exit(-1)
USE_X_FORWARDED_HOST = get_boolean_setting( USE_X_FORWARDED_HOST = get_boolean_setting(
'INVENTREE_USE_X_FORWARDED_HOST', 'INVENTREE_USE_X_FORWARDED_HOST',
config_key='use_x_forwarded_host', config_key='use_x_forwarded_host',
@ -1265,5 +1272,5 @@ SPECTACULAR_SETTINGS = {
'SCHEMA_PATH_PREFIX': '/api/', 'SCHEMA_PATH_PREFIX': '/api/',
} }
if SITE_URL: if SITE_URL and not TESTING:
SPECTACULAR_SETTINGS['SERVERS'] = [{'url': SITE_URL}] SPECTACULAR_SETTINGS['SERVERS'] = [{'url': SITE_URL}]

View File

@ -574,6 +574,7 @@ class FormatTest(TestCase):
class TestHelpers(TestCase): class TestHelpers(TestCase):
"""Tests for InvenTree helper functions.""" """Tests for InvenTree helper functions."""
@override_settings(SITE_URL=None)
def test_absolute_url(self): def test_absolute_url(self):
"""Test helper function for generating an absolute URL.""" """Test helper function for generating an absolute URL."""
base = 'https://demo.inventree.org:12345' base = 'https://demo.inventree.org:12345'
@ -1347,6 +1348,7 @@ class TestInstanceName(InvenTreeTestCase):
site_obj = Site.objects.all().order_by('id').first() site_obj = Site.objects.all().order_by('id').first()
self.assertEqual(site_obj.name, 'Testing title') self.assertEqual(site_obj.name, 'Testing title')
@override_settings(SITE_URL=None)
def test_instance_url(self): def test_instance_url(self):
"""Test instance url settings.""" """Test instance url settings."""
# Set up required setting # Set up required setting

View File

@ -12,6 +12,7 @@ from django.core.cache import cache
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import Client, TestCase from django.test import Client, TestCase
from django.test.utils import override_settings
from django.urls import reverse from django.urls import reverse
import PIL import PIL
@ -271,6 +272,7 @@ class SettingsTest(InvenTreeTestCase):
print(f"run_settings_check failed for user setting '{key}'") print(f"run_settings_check failed for user setting '{key}'")
raise exc raise exc
@override_settings(SITE_URL=None)
def test_defaults(self): def test_defaults(self):
"""Populate the settings with default values.""" """Populate the settings with default values."""
for key in InvenTreeSetting.SETTINGS.keys(): for key in InvenTreeSetting.SETTINGS.keys():

View File

@ -6,6 +6,7 @@ from django.conf import settings
from django.core.cache import cache from django.core.cache import cache
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.test import TestCase from django.test import TestCase
from django.test.utils import override_settings
from allauth.account.models import EmailAddress from allauth.account.models import EmailAddress
@ -63,6 +64,7 @@ class TemplateTagTest(InvenTreeTestCase):
"""Test the 'instance name' setting.""" """Test the 'instance name' setting."""
self.assertEqual(inventree_extras.inventree_instance_name(), 'InvenTree') self.assertEqual(inventree_extras.inventree_instance_name(), 'InvenTree')
@override_settings(SITE_URL=None)
def test_inventree_base_url(self): def test_inventree_base_url(self):
"""Test that the base URL tag returns correctly.""" """Test that the base URL tag returns correctly."""
self.assertEqual(inventree_extras.inventree_base_url(), '') self.assertEqual(inventree_extras.inventree_base_url(), '')

View File

@ -59,9 +59,12 @@ The following basic options are available:
| INVENTREE_BASE_URL | base_url | Server base URL | *Not specified* | | INVENTREE_BASE_URL | base_url | Server base URL | *Not specified* |
| INVENTREE_AUTO_UPDATE | auto_update | Database migrations will be run automatically | False | | INVENTREE_AUTO_UPDATE | auto_update | Database migrations will be run automatically | False |
!!! tip "INVENTREE_SITE_URL"
The *INVENTREE_SITE_URL* option defines the base URL for the InvenTree server. This is a critical setting, and it is required for correct operation of the server. If not specified, the server will attempt to determine the site URL automatically - but this may not always be correct!
## Server Access ## Server Access
Depending on how your InvenTree installation is configured, you will need to pay careful attention to the following settings. If you are running your server behind a proxy, or want to adjust support for CORS requests, one or more of the following settings may need to be adjusted. Depending on how your InvenTree installation is configured, you will need to pay careful attention to the following settings. If you are running your server behind a proxy, or want to adjust support for [CORS requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), one or more of the following settings may need to be adjusted.
!!! warning "Advanced Users" !!! warning "Advanced Users"
The following settings require a certain assumed level of knowledge. You should also refer to the [django documentation]({% include "django.html" %}/ref/settings/) for more information. The following settings require a certain assumed level of knowledge. You should also refer to the [django documentation]({% include "django.html" %}/ref/settings/) for more information.
@ -86,6 +89,10 @@ Depending on how your InvenTree installation is configured, you will need to pay
| INVENTREE_USE_X_FORWARDED_PORT | use_x_forwarded_port | Use forwarded port header | False | | INVENTREE_USE_X_FORWARDED_PORT | use_x_forwarded_port | Use forwarded port header | False |
| INVENTREE_CORS_ALLOW_CREDENTIALS | cors.allow_credentials | Allow cookies in cross-site requests | True | | INVENTREE_CORS_ALLOW_CREDENTIALS | cors.allow_credentials | Allow cookies in cross-site requests | True |
### Proxy Settings
If you are running InvenTree behind another proxy, you will need to ensure that the InvenTree server is configured to listen on the correct host and port. You will likely have to adjust the `INVENTREE_ALLOWED_HOSTS` setting to ensure that the server will accept requests from the proxy.
## Admin Site ## Admin Site
Django provides a powerful [administrator interface]({% include "django.html" %}/ref/contrib/admin/) which can be used to manage the InvenTree database. This interface is enabled by default, and available at the `/admin/` URL. Django provides a powerful [administrator interface]({% include "django.html" %}/ref/contrib/admin/) which can be used to manage the InvenTree database. This interface is enabled by default, and available at the `/admin/` URL.