diff --git a/src/backend/InvenTree/part/models.py b/src/backend/InvenTree/part/models.py index ede4c29e47..9ad9373162 100644 --- a/src/backend/InvenTree/part/models.py +++ b/src/backend/InvenTree/part/models.py @@ -800,13 +800,31 @@ class Part( log_error('validate_part_ipn', plugin=plugin.slug) # If we get to here, none of the plugins have raised an error - pattern = get_global_setting('PART_IPN_REGEX', '', create=False).strip() + pattern = str( + get_global_setting('PART_IPN_REGEX', '', create=False) or '' + ).strip() - if pattern: - match = re.search(pattern, self.IPN) + # Blank IPN values are permitted, and are not checked against the pattern + if not pattern or not self.IPN: + return - if match is None: - raise ValidationError(_(f'IPN must match regex pattern {pattern}')) + try: + match = re.search(pattern, str(self.IPN)) + except re.error: + # A malformed pattern may already be stored (e.g. from before validation was added) + log_error('validate_ipn') + raise ValidationError({ + 'IPN': _( + 'The IPN regex pattern configured in system settings is invalid' + ) + }) + + if match is None: + raise ValidationError({ + 'IPN': _('IPN must match regex pattern {pattern}').format( + pattern=pattern + ) + }) def validate_revision(self): """Check the 'revision' and 'revision_of' fields.""" diff --git a/src/backend/InvenTree/part/system_settings.py b/src/backend/InvenTree/part/system_settings.py index 5cd7ccb85f..3299b04ffe 100644 --- a/src/backend/InvenTree/part/system_settings.py +++ b/src/backend/InvenTree/part/system_settings.py @@ -44,7 +44,11 @@ SYSTEM_SETTINGS: dict[str, InvenTreeSettingsKeyType] = { }, 'PART_IPN_REGEX': { 'name': _('IPN Regex'), - 'description': _('Regular expression pattern for matching Part IPN'), + 'description': _( + 'Regular expression pattern for matching Part IPN. The pattern may match any part of the IPN: use ^ and $ to match the whole value. Parts without an IPN are not checked.' + ), + 'default': '', + 'validator': part.validators.validate_ipn_regex, }, 'PART_ALLOW_DUPLICATE_IPN': { 'name': _('Allow Duplicate IPN'), diff --git a/src/backend/InvenTree/part/test_part.py b/src/backend/InvenTree/part/test_part.py index 57b21dc0cb..8b4050b8c7 100644 --- a/src/backend/InvenTree/part/test_part.py +++ b/src/backend/InvenTree/part/test_part.py @@ -792,6 +792,42 @@ class PartSettingsTest(InvenTreeTestCase): Part.objects.filter(pk=part.pk).delete() + def test_ipn_regex(self): + """Test the PART_IPN_REGEX setting.""" + from common.models import InvenTreeSetting + + # An invalid regular expression cannot be saved + for pattern in ['[abc', '(unclosed', '*start']: + with self.assertRaises(ValidationError): + set_global_setting('PART_IPN_REGEX', pattern, self.user) + + # Valid pattern: matching is a search (substring), unless anchored + set_global_setting('PART_IPN_REGEX', r'^PN-\d+$', self.user) + + Part.objects.create(name='Valid', description='Matches', IPN='PN-123') + + for ipn in ['PN-ABC', 'XPN-123', 'PN-123X']: + with self.assertRaises(ValidationError) as err: + Part.objects.create(name='Invalid', description='No match', IPN=ipn) + self.assertIn('IPN', err.exception.message_dict) + + # Blank IPN values are not checked against the pattern + for ipn in [None, '', ' ']: + Part.objects.create(name='Blank', description='No IPN', IPN=ipn) + + # A malformed pattern already stored in the database (bypassing validation) + # results in a validation error, rather than an unhandled exception + InvenTreeSetting.objects.filter(key='PART_IPN_REGEX').update(value='[abc') + cache.clear() + + with self.assertRaises(ValidationError) as err: + Part.objects.create(name='Broken', description='Bad regex', IPN='PN-1') + self.assertIn('IPN', err.exception.message_dict) + + # Clearing the pattern disables the check + set_global_setting('PART_IPN_REGEX', '', self.user) + Part.objects.create(name='Any', description='Any IPN', IPN='anything') + def test_duplicate_ipn(self): """Test the setting which controls duplicate IPN values.""" # Create a part diff --git a/src/backend/InvenTree/part/validators.py b/src/backend/InvenTree/part/validators.py index 47294bcb7a..ac7b961069 100644 --- a/src/backend/InvenTree/part/validators.py +++ b/src/backend/InvenTree/part/validators.py @@ -3,10 +3,29 @@ import re from django.core.exceptions import FieldDoesNotExist, ValidationError +from django.utils.translation import gettext_lazy as _ from jinja2.sandbox import SandboxedEnvironment +def validate_ipn_regex(value): + """Validate that the PART_IPN_REGEX setting is a valid regular expression. + + An empty value is allowed (and disables IPN pattern matching). + """ + pattern = str(value or '').strip() + + if not pattern: + return + + try: + re.compile(pattern) + except re.error as exc: + raise ValidationError({ + 'value': _('Invalid regular expression: {error}').format(error=exc) + }) + + def validate_part_name_format(value): """Validate part name format.