Arthur 3 dagar sedan
förälder
incheckning
9d1851ea91
50 ändrade filer med 1708 tillägg och 244 borttagningar
  1. 14 1
      docs/configuration/miscellaneous.md
  2. 1 0
      docs/configuration/system.md
  3. 30 0
      docs/integrations/graphql-api.md
  4. 3 1
      docs/models/extras/webhook.md
  5. 1 9
      netbox/account/views.py
  6. 4 0
      netbox/circuits/tests/test_models.py
  7. 7 0
      netbox/core/management/commands/upgrade.py
  8. 18 1
      netbox/core/signals.py
  9. 3 2
      netbox/core/tests/test_management_commands.py
  10. 50 0
      netbox/core/tests/test_signals.py
  11. 15 5
      netbox/dcim/models/cables.py
  12. 1 0
      netbox/dcim/models/devices.py
  13. 5 0
      netbox/dcim/signals.py
  14. 126 0
      netbox/dcim/tests/test_models.py
  15. 67 1
      netbox/dcim/tests/test_views.py
  16. 24 11
      netbox/dcim/views.py
  17. 4 2
      netbox/extras/dashboard/utils.py
  18. 1 1
      netbox/extras/forms/bulk_edit.py
  19. 5 1
      netbox/extras/forms/bulk_import.py
  20. 1 1
      netbox/extras/forms/model_forms.py
  21. 2 1
      netbox/extras/models/models.py
  22. 4 0
      netbox/extras/tests/test_event_rules.py
  23. 37 0
      netbox/extras/tests/test_forms.py
  24. 2 0
      netbox/extras/tests/test_signals.py
  25. 4 2
      netbox/extras/views.py
  26. 5 1
      netbox/netbox/api/authentication.py
  27. 209 0
      netbox/netbox/graphql/extensions.py
  28. 2 0
      netbox/netbox/graphql/schema.py
  29. 6 1
      netbox/netbox/graphql/views.py
  30. 20 7
      netbox/netbox/middleware.py
  31. 23 0
      netbox/netbox/models/features.py
  32. 4 3
      netbox/netbox/settings.py
  33. 12 0
      netbox/netbox/tests/test_authentication.py
  34. 269 0
      netbox/netbox/tests/test_graphql.py
  35. 296 2
      netbox/netbox/tests/test_middleware.py
  36. 69 2
      netbox/netbox/tests/test_model_features.py
  37. 5 5
      netbox/netbox/tests/test_search.py
  38. 0 0
      netbox/project-static/dist/netbox.js
  39. 0 0
      netbox/project-static/dist/netbox.js.map
  40. 33 2
      netbox/project-static/src/htmx.ts
  41. 2 1
      netbox/templates/500.html
  42. 35 0
      netbox/templates/exceptions/maintenance_mode.html
  43. 174 174
      netbox/translations/en/LC_MESSAGES/django.po
  44. 12 4
      netbox/users/models/preferences.py
  45. 18 0
      netbox/users/signals.py
  46. 14 0
      netbox/users/tests/test_models.py
  47. 5 1
      netbox/utilities/forms/fields/dynamic.py
  48. 10 2
      netbox/utilities/tests/test_forms.py
  49. 8 0
      netbox/wireless/signals.py
  50. 48 0
      netbox/wireless/tests/test_models.py

+ 14 - 1
docs/configuration/miscellaneous.md

@@ -178,7 +178,20 @@ The number of days to retain job results (scripts and reports). Set this to `0`
 
 
 Default: `False`
 Default: `False`
 
 
-Setting this to `True` will display a "maintenance mode" banner at the top of every page. Additionally, NetBox will no longer update a user's "last active" time upon login. This is to allow new logins when the database is in a read-only state. Recording of login times will resume when maintenance mode is disabled.
+Setting this to `True` places NetBox in a read-only state, and displays a "maintenance mode" banner (see [`BANNER_MAINTENANCE`](#banner_maintenance)) at the top of every page.
+
+While maintenance mode is enabled, any request which attempts to write to the database through the web UI or the REST API fails with an error message. The following remain available:
+
+* Logging in and out, including via single sign-on and remote authentication
+* Provisioning API tokens via the REST API
+* Modifying the configuration under Admin > Configuration History, so that maintenance mode can be disabled again from the UI (unless it has been set in `configuration.py`)
+
+Additionally, NetBox will not update a user's "last login" time, or a token's "last used" time, while maintenance mode is enabled. This allows users to log in when the database itself is read-only. Note that logging in also saves the user's session, which is stored in the database unless [`SESSION_FILE_PATH`](./security.md#session_file_path) is set.
+
+User preferences that are normally saved while browsing (such as table ordering) apply only to the current request, and viewing a notification does not mark it as read.
+
+!!! note
+    Maintenance mode applies only to web UI and API requests. It does not prevent background jobs (such as scheduled scripts, data source synchronization, and housekeeping tasks) or management commands from writing to the database.
 
 
 ---
 ---
 
 

+ 1 - 0
docs/configuration/system.md

@@ -247,6 +247,7 @@ LOGGING = {
 * `netbox.auth.*` - Authentication events
 * `netbox.auth.*` - Authentication events
 * `netbox.api.views.*` - Views which handle business logic for the REST API
 * `netbox.api.views.*` - Views which handle business logic for the REST API
 * `netbox.event_rules` - Event rules
 * `netbox.event_rules` - Event rules
+* `netbox.graphql.query` - GraphQL API requests (logged at `INFO`; see [GraphQL API logging](../integrations/graphql-api.md#logging))
 * `netbox.jobs.*` - Background jobs
 * `netbox.jobs.*` - Background jobs
 * `netbox.reports.*` - Report execution (`module.name`)
 * `netbox.reports.*` - Report execution (`module.name`)
 * `netbox.scripts.*` - Custom script execution (`module.name`)
 * `netbox.scripts.*` - Custom script execution (`module.name`)

+ 30 - 0
docs/integrations/graphql-api.md

@@ -200,6 +200,36 @@ This will return up to 20 records with an ID greater than or equal to 124.
 
 
 NetBox's GraphQL API uses the same API authentication tokens as its REST API. See the [REST API authentication](./rest-api.md#authentication) documentation for further detail.
 NetBox's GraphQL API uses the same API authentication tokens as its REST API. See the [REST API authentication](./rest-api.md#authentication) documentation for further detail.
 
 
+## Logging
+
+NetBox can log each GraphQL request to the `netbox.graphql.query` logger at the `INFO` level. This logger is not enabled by default; to enable it, configure it under the [`LOGGING`](../configuration/system.md#logging) configuration parameter:
+
+```python
+LOGGING = {
+    'version': 1,
+    'handlers': {
+        'graphql': {
+            'class': 'logging.FileHandler',
+            'filename': '/var/log/netbox/graphql.log',
+        },
+    },
+    'loggers': {
+        'netbox.graphql.query': {
+            'handlers': ['graphql'],
+            'level': 'INFO',
+        },
+    },
+}
+```
+
+Each record includes the user, the API token ID (if a token was used), the client IP address, the operation name, the query, the query variables, the time taken, the number of errors, and the size of the response in bytes. The query is logged with its literal values replaced by placeholders (e.g. `name: "foo"` becomes `name: ""`), along with a hash of the result, so that identical queries can be grouped. The query and variables are each truncated to 4096 characters. These fields are also attached to each log record as a dictionary named `graphql`, for use by structured log formatters.
+
+!!! warning
+    Query variables are logged as submitted. If clients pass sensitive values as variables, those values will be written to the log.
+
+!!! tip
+    Log records are written as part of each request. On busy installations, consider using a [`QueueHandler`](https://docs.python.org/3/library/logging.handlers.html#queuehandler) so that slow log destinations don't delay API responses.
+
 ## Disabling the GraphQL API
 ## Disabling the GraphQL API
 
 
 If not needed, the GraphQL API can be disabled by setting the [`GRAPHQL_ENABLED`](../configuration/graphql-api.md#graphql_enabled) configuration parameter to False and restarting NetBox.
 If not needed, the GraphQL API can be disabled by setting the [`GRAPHQL_ENABLED`](../configuration/graphql-api.md#graphql_enabled) configuration parameter to False and restarting NetBox.

+ 3 - 1
docs/models/extras/webhook.md

@@ -85,7 +85,9 @@ Controls whether validation of the receiver's SSL certificate is enforced when H
 
 
 ### CA File Path
 ### CA File Path
 
 
-The file path to a particular certificate authority (CA) file to use when validating the receiver's SSL certificate (if not using the system defaults).
+The file path to a particular certificate authority (CA) file to use when validating the receiver's SSL certificate. If left blank (and SSL verification is enabled), validation uses NetBox's built-in CA bundle. The host's system trust store and the `REQUESTS_CA_BUNDLE` environment variable are ignored, so a receiver whose certificate is signed by a private CA must have that CA specified here.
+
+The file replaces the built-in bundle for this webhook. To keep trusting public CAs as well, provide a bundle that includes them.
 
 
 ### Timeout
 ### Timeout
 
 

+ 1 - 9
netbox/account/views.py

@@ -8,8 +8,6 @@ from django.contrib.auth import logout as auth_logout
 from django.contrib.auth import update_session_auth_hash
 from django.contrib.auth import update_session_auth_hash
 from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm
 from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm
 from django.contrib.auth.mixins import LoginRequiredMixin
 from django.contrib.auth.mixins import LoginRequiredMixin
-from django.contrib.auth.models import update_last_login
-from django.contrib.auth.signals import user_logged_in
 from django.http import HttpResponseRedirect, JsonResponse
 from django.http import HttpResponseRedirect, JsonResponse
 from django.shortcuts import get_object_or_404, redirect, render, resolve_url
 from django.shortcuts import get_object_or_404, redirect, render, resolve_url
 from django.urls import reverse, reverse_lazy
 from django.urls import reverse, reverse_lazy
@@ -117,12 +115,6 @@ class LoginView(View):
         if form.is_valid():
         if form.is_valid():
             logger.debug("Login form validation was successful")
             logger.debug("Login form validation was successful")
 
 
-            # If maintenance mode is enabled, assume the database is read-only, and disable updating the user's
-            # last_login time upon authentication.
-            if get_config().MAINTENANCE_MODE:
-                logger.warning("Maintenance mode enabled: disabling update of most recent login time")
-                user_logged_in.disconnect(update_last_login, dispatch_uid='update_last_login')
-
             # Authenticate user
             # Authenticate user
             auth_login(request, form.get_user())
             auth_login(request, form.get_user())
             logger.info(f"User {request.user} successfully authenticated")
             logger.info(f"User {request.user} successfully authenticated")
@@ -147,7 +139,7 @@ class LoginView(View):
 
 
             return response
             return response
 
 
-        username = form['username'].value()
+        username = form['username'].value() or ''
         logger.debug(f"Login form validation failed for username: {remove_linebreaks(username)}")
         logger.debug(f"Login form validation failed for username: {remove_linebreaks(username)}")
 
 
         return render(request, self.template_name, {
         return render(request, self.template_name, {

+ 4 - 0
netbox/circuits/tests/test_models.py

@@ -415,6 +415,7 @@ class CircuitTerminationChangeLoggingTestCase(TestCase):
         ObjectChange.objects.all().delete()
         ObjectChange.objects.all().delete()
 
 
         def _move():
         def _move():
+            termination.snapshot()
             termination.circuit = self.circuits[1]
             termination.circuit = self.circuits[1]
             termination.save()
             termination.save()
 
 
@@ -440,6 +441,7 @@ class CircuitTerminationChangeLoggingTestCase(TestCase):
         ObjectChange.objects.all().delete()
         ObjectChange.objects.all().delete()
 
 
         def _flip():
         def _flip():
+            termination.snapshot()
             termination.term_side = 'Z'
             termination.term_side = 'Z'
             termination.save()
             termination.save()
 
 
@@ -486,6 +488,7 @@ class CircuitTerminationChangeLoggingTestCase(TestCase):
         ))
         ))
         ObjectChange.objects.all().delete()
         ObjectChange.objects.all().delete()
 
 
+        termination.snapshot()
         self._tracked(termination.save)
         self._tracked(termination.save)
 
 
         self.assertFalse(self._circuit_changes(self.circuits[0]).exists())
         self.assertFalse(self._circuit_changes(self.circuits[0]).exists())
@@ -499,6 +502,7 @@ class CircuitTerminationChangeLoggingTestCase(TestCase):
         ObjectChange.objects.all().delete()
         ObjectChange.objects.all().delete()
 
 
         def _move():
         def _move():
+            termination.snapshot()
             termination.circuit = self.circuits[1]
             termination.circuit = self.circuits[1]
             termination.save(update_fields=('circuit',))
             termination.save(update_fields=('circuit',))
 
 

+ 7 - 0
netbox/core/management/commands/upgrade.py

@@ -60,6 +60,13 @@ class Command(BaseCommand):
             out.write("Checking for missing cable paths...")
             out.write("Checking for missing cable paths...")
             call_command('trace_paths', no_input=options['no_input'], stdout=out, stderr=self.stderr)
             call_command('trace_paths', no_input=options['no_input'], stdout=out, stderr=self.stderr)
 
 
+        # Config context cache (writes to the database)
+        if options['readonly']:
+            out.write("Skipping config context cache rebuild.")
+        else:
+            out.write("Caching config context data...")
+            call_command('rebuild_config_context_cache', stdout=out)
+
         # Documentation (filesystem; needs the documentation source tree)
         # Documentation (filesystem; needs the documentation source tree)
         if options['readonly'] and options['build_docs']:
         if options['readonly'] and options['build_docs']:
             out.write("Skipping documentation build.")
             out.write("Skipping documentation build.")

+ 18 - 1
netbox/core/signals.py

@@ -7,7 +7,7 @@ from django.core.signals import request_finished
 from django.db import transaction
 from django.db import transaction
 from django.db.models import CASCADE, RESTRICT
 from django.db.models import CASCADE, RESTRICT
 from django.db.models.fields.reverse_related import ManyToManyRel, ManyToOneRel
 from django.db.models.fields.reverse_related import ManyToManyRel, ManyToOneRel
-from django.db.models.signals import m2m_changed, post_migrate, post_save, pre_delete
+from django.db.models.signals import m2m_changed, post_migrate, post_save, pre_delete, pre_save
 from django.dispatch import Signal, receiver
 from django.dispatch import Signal, receiver
 from django.utils.translation import gettext_lazy as _
 from django.utils.translation import gettext_lazy as _
 from django.utils.translation import ngettext
 from django.utils.translation import ngettext
@@ -90,6 +90,19 @@ def update_object_types(sender, **kwargs):
 _signals_received = local()
 _signals_received = local()
 
 
 
 
+@receiver(pre_save)
+def snapshot_unsnapshotted_object(sender, instance, raw=False, using=None, **kwargs):
+    """
+    Generate a pre-change snapshot from the database for an existing object being saved without one.
+    """
+    if raw or not isinstance(instance, ChangeLoggingMixin) or current_request.get() is None:
+        return
+    if instance._state.adding or instance.pk is None or hasattr(instance, '_prechange_snapshot'):
+        return
+
+    instance.snapshot_from_db(using=using)
+
+
 @receiver((post_save, m2m_changed))
 @receiver((post_save, m2m_changed))
 def handle_changed_object(sender, instance, **kwargs):
 def handle_changed_object(sender, instance, **kwargs):
     """
     """
@@ -163,6 +176,10 @@ def handle_changed_object(sender, instance, **kwargs):
     enqueue_event(queue, instance, request, event_type, object_change_id=object_change_id)
     enqueue_event(queue, instance, request, event_type, object_change_id=object_change_id)
     events_queue.set(queue)
     events_queue.set(queue)
 
 
+    # Discard a snapshot read from the database only once the event has captured it
+    if instance.__dict__.pop('_prechange_snapshot_from_db', False):
+        instance.__dict__.pop('_prechange_snapshot', None)
+
     # Increment metric counters
     # Increment metric counters
     if event_type == OBJECT_CREATED:
     if event_type == OBJECT_CREATED:
         model_inserts.labels(instance._meta.model_name).inc()
         model_inserts.labels(instance._meta.model_name).inc()

+ 3 - 2
netbox/core/tests/test_management_commands.py

@@ -334,7 +334,7 @@ class UpgradeCommandTest(TestCase):
     def test_full_sequence_order(self):
     def test_full_sequence_order(self):
         seq, _, sub, _ = self._run()
         seq, _, sub, _ = self._run()
         self.assertEqual(seq, [
         self.assertEqual(seq, [
-            'migrate', 'trace_paths',
+            'migrate', 'trace_paths', 'rebuild_config_context_cache',
             'collectstatic', 'remove_stale_contenttypes', 'reindex', 'clearsessions',
             'collectstatic', 'remove_stale_contenttypes', 'reindex', 'clearsessions',
         ])
         ])
         sub.assert_not_called()  # docs not built by default
         sub.assert_not_called()  # docs not built by default
@@ -346,6 +346,7 @@ class UpgradeCommandTest(TestCase):
         sub.assert_not_called()
         sub.assert_not_called()
         self.assertIn('Skipping database migrations.', out)
         self.assertIn('Skipping database migrations.', out)
         self.assertIn('Skipping cable path check.', out)
         self.assertIn('Skipping cable path check.', out)
+        self.assertIn('Skipping config context cache rebuild.', out)
         self.assertIn('Skipping static file collection.', out)
         self.assertIn('Skipping static file collection.', out)
         self.assertIn('Skipping stale content type removal.', out)
         self.assertIn('Skipping stale content type removal.', out)
         self.assertIn('Skipping search index rebuild.', out)
         self.assertIn('Skipping search index rebuild.', out)
@@ -355,7 +356,7 @@ class UpgradeCommandTest(TestCase):
         seq, _, _, _ = self._run(skip_migrations=True, skip_static=True, skip_reindex=True)
         seq, _, _, _ = self._run(skip_migrations=True, skip_static=True, skip_reindex=True)
         self.assertEqual(
         self.assertEqual(
             seq,
             seq,
-            ['trace_paths', 'remove_stale_contenttypes', 'clearsessions'],
+            ['trace_paths', 'rebuild_config_context_cache', 'remove_stale_contenttypes', 'clearsessions'],
         )
         )
 
 
     def test_build_docs_invokes_zensical_when_sources_present(self):
     def test_build_docs_invokes_zensical_when_sources_present(self):

+ 50 - 0
netbox/core/tests/test_signals.py

@@ -78,6 +78,7 @@ class HandleChangedObjectSignalTestCase(TestCase):
         request = _build_request(self.user)
         request = _build_request(self.user)
 
 
         with event_tracking(request):
         with event_tracking(request):
+            site.snapshot()
             site.description = 'updated'
             site.description = 'updated'
             site.save()
             site.save()
 
 
@@ -87,6 +88,55 @@ class HandleChangedObjectSignalTestCase(TestCase):
         ).order_by('-pk')
         ).order_by('-pk')
         self.assertEqual(ocs.first().action, ObjectChangeActionChoices.ACTION_UPDATE)
         self.assertEqual(ocs.first().action, ObjectChangeActionChoices.ACTION_UPDATE)
 
 
+    def test_update_without_snapshot_records_prechange_from_database(self):
+        """An update saved without a snapshot records its pre-change data from the database. Ref: #23617"""
+        site = Site.objects.create(name='Site 1', slug='site-1')
+        request = _build_request(self.user)
+
+        with self.assertLogs('netbox.models.features', level='WARNING'), event_tracking(request):
+            site.description = 'first'
+            site.save()
+            site.description = 'second'
+            site.save()
+
+        ocs = ObjectChange.objects.filter(
+            changed_object_type=ContentType.objects.get_for_model(Site),
+            changed_object_id=site.pk,
+        ).order_by('pk')
+        self.assertEqual([oc.prechange_data['description'] for oc in ocs], ['', 'first'])
+        self.assertEqual([oc.postchange_data['description'] for oc in ocs], ['first', 'second'])
+        self.assertFalse(hasattr(site, '_prechange_snapshot'))
+
+    def test_update_without_snapshot_enqueues_prechange_from_database(self):
+        """The event for an update saved without a snapshot carries its pre-change data. Ref: #23617"""
+        site = Site.objects.create(name='Site 1', slug='site-1')
+        request = _build_request(self.user)
+
+        with self.assertLogs('netbox.models.features', level='WARNING'), event_tracking(request):
+            site.description = 'updated'
+            site.save()
+            snapshots = events_queue.get()[f'dcim.site:{site.pk}']['snapshots']
+
+        self.assertEqual(snapshots['prechange']['description'], '')
+        self.assertEqual(snapshots['postchange']['description'], 'updated')
+        self.assertFalse(hasattr(site, '_prechange_snapshot'))
+
+    def test_update_keeps_existing_snapshot(self):
+        site = Site.objects.create(name='Site 1', slug='site-1')
+        request = _build_request(self.user)
+
+        with self.assertNoLogs('netbox.models.features', level='WARNING'), event_tracking(request):
+            site.snapshot()
+            site.description = 'first'
+            site.save()
+
+        oc = ObjectChange.objects.get(
+            changed_object_type=ContentType.objects.get_for_model(Site),
+            changed_object_id=site.pk,
+        )
+        self.assertEqual(oc.prechange_data['description'], '')
+        self.assertEqual(oc.postchange_data['description'], 'first')
+
     def test_no_request_skips_objectchange(self):
     def test_no_request_skips_objectchange(self):
         # Saving outside a request context (no event_tracking) should not record any
         # Saving outside a request context (no event_tracking) should not record any
         # ObjectChange entries.
         # ObjectChange entries.

+ 15 - 5
netbox/dcim/models/cables.py

@@ -21,6 +21,7 @@ from dcim.exceptions import UnsupportedCablePath
 from dcim.fields import PathField
 from dcim.fields import PathField
 from dcim.utils import decompile_path_node, object_to_path_node, rebuild_cable_paths
 from dcim.utils import decompile_path_node, object_to_path_node, rebuild_cable_paths
 from netbox.choices import ColorChoices
 from netbox.choices import ColorChoices
+from netbox.context import current_request
 from netbox.models import ChangeLoggedModel, PrimaryModel
 from netbox.models import ChangeLoggedModel, PrimaryModel
 from utilities.conversion import to_meters
 from utilities.conversion import to_meters
 from utilities.data import normalize_update_fields
 from utilities.data import normalize_update_fields
@@ -353,6 +354,8 @@ class Cable(PrimaryModel):
 
 
     def save(self, *args, force_insert=False, force_update=False, using=None, update_fields=None):
     def save(self, *args, force_insert=False, force_update=False, using=None, update_fields=None):
         _created = self.pk is None
         _created = self.pk is None
+        # Unlike _created, also true for a new Cable with a preset pk (e.g. one restored by deserialize_object())
+        adding = self._state.adding
         save_kwargs = {
         save_kwargs = {
             'using': using,
             'using': using,
             'update_fields': update_fields,
             'update_fields': update_fields,
@@ -391,17 +394,24 @@ class Cable(PrimaryModel):
         profile_written = update_fields is None or 'profile' in update_fields
         profile_written = update_fields is None or 'profile' in update_fields
 
 
         # If this is a new Cable, save it before attempting to create its CableTerminations
         # If this is a new Cable, save it before attempting to create its CableTerminations
-        if self._state.adding:
+        if adding:
             super().save(*args, force_insert=True, **save_kwargs)
             super().save(*args, force_insert=True, **save_kwargs)
             # Update the private PK used in __str__()
             # Update the private PK used in __str__()
             self._pk = self.pk
             self._pk = self.pk
+            # Record the pre-termination state for the update made by the save below
+            self.snapshot()
 
 
-        if profile_written and self._orig_profile != self.profile:
-            self.update_terminations(force=True)
-        elif self._terminations_modified:
-            self.update_terminations()
+        force_terminations = profile_written and self._orig_profile != self.profile
+        if force_terminations or self._terminations_modified:
+            # update_terminations() writes before the pre_save fallback runs, so snapshot the stored Cable now
+            if current_request.get() is not None and not hasattr(self, '_prechange_snapshot'):
+                self.snapshot_from_db(using=using)
+            self.update_terminations(force=force_terminations)
 
 
         super().save(*args, force_update=True, **save_kwargs)
         super().save(*args, force_update=True, **save_kwargs)
+        # Discard the pre-termination snapshot so that a later save of this instance takes a fresh one
+        if adding:
+            self.__dict__.pop('_prechange_snapshot', None)
 
 
         try:
         try:
             trace_paths.send(Cable, instance=self, created=_created, status_written=status_written)
             trace_paths.send(Cable, instance=self, created=_created, status_written=status_written)

+ 1 - 0
netbox/dcim/models/devices.py

@@ -1175,6 +1175,7 @@ class Device(
         # Update Site and Rack assignment for any child Devices
         # Update Site and Rack assignment for any child Devices
         devices = Device.objects.filter(parent_bay__device=self)
         devices = Device.objects.filter(parent_bay__device=self)
         for device in devices:
         for device in devices:
+            device.snapshot()
             device.site = self.site
             device.site = self.site
             device.rack = self.rack
             device.rack = self.rack
             device.location = self.location
             device.location = self.location

+ 5 - 0
netbox/dcim/signals.py

@@ -501,5 +501,10 @@ def update_mac_address_interface(instance, created, raw, **kwargs):
     assign the MACAddress to the interface.
     assign the MACAddress to the interface.
     """
     """
     if created and not raw and instance.primary_mac_address:
     if created and not raw and instance.primary_mac_address:
+        # Keep any snapshot the caller took before making unsaved changes to the MAC address
+        if not hasattr(instance.primary_mac_address, '_prechange_snapshot'):
+            instance.primary_mac_address.snapshot()
         instance.primary_mac_address.assigned_object = instance
         instance.primary_mac_address.assigned_object = instance
         instance.primary_mac_address.save()
         instance.primary_mac_address.save()
+        # Discard the snapshot so that a later save of the MAC address takes a fresh one
+        instance.primary_mac_address.__dict__.pop('_prechange_snapshot', None)

+ 126 - 0
netbox/dcim/tests/test_models.py

@@ -56,6 +56,49 @@ class MACAddressTestCase(TestCase):
         cls.interface.primary_mac_address = cls.mac_a
         cls.interface.primary_mac_address = cls.mac_a
         cls.interface.save()
         cls.interface.save()
 
 
+    @tag('regression')  # Ref: #23617
+    def test_primary_mac_assignment_on_interface_creation_records_prechange(self):
+        mac = MACAddress.objects.create(mac_address='1234567890cd')
+        request = RequestFactory().get('/')
+        request.id = uuid.uuid4()
+        request.user = User.objects.create_user(username='testuser')
+
+        with event_tracking(request):
+            interface = Interface.objects.create(
+                device=self.interface.device, name='Interface 2', type=InterfaceTypeChoices.TYPE_1GE_FIXED,
+                primary_mac_address=mac
+            )
+
+        change = ObjectChange.objects.get(
+            changed_object_type=ObjectType.objects.get_for_model(MACAddress),
+            changed_object_id=mac.pk,
+        )
+        self.assertIsNone(change.prechange_data['assigned_object_id'])
+        self.assertEqual(change.postchange_data['assigned_object_id'], interface.pk)
+        self.assertFalse(hasattr(mac, '_prechange_snapshot'))
+
+    @tag('regression')  # Ref: #23617
+    def test_primary_mac_assignment_keeps_existing_snapshot(self):
+        mac = MACAddress.objects.create(mac_address='1234567890ce')
+        request = RequestFactory().get('/')
+        request.id = uuid.uuid4()
+        request.user = User.objects.create_user(username='testuser')
+
+        with event_tracking(request):
+            mac.snapshot()
+            mac.description = 'updated'
+            Interface.objects.create(
+                device=self.interface.device, name='Interface 2', type=InterfaceTypeChoices.TYPE_1GE_FIXED,
+                primary_mac_address=mac
+            )
+
+        change = ObjectChange.objects.get(
+            changed_object_type=ObjectType.objects.get_for_model(MACAddress),
+            changed_object_id=mac.pk,
+        )
+        self.assertEqual(change.prechange_data['description'], '')
+        self.assertEqual(change.postchange_data['description'], 'updated')
+
     @tag('regression')
     @tag('regression')
     def test_clean_will_not_allow_removal_of_assigned_object_if_primary(self):
     def test_clean_will_not_allow_removal_of_assigned_object_if_primary(self):
         self.mac_a.assigned_object = None
         self.mac_a.assigned_object = None
@@ -1327,6 +1370,29 @@ class DeviceBayTestCase(TestCase):
         self.assertIn('installed_device', cm.exception.message_dict)
         self.assertIn('installed_device', cm.exception.message_dict)
         self.assertIn('disabled device bay', str(cm.exception.message_dict['installed_device']))
         self.assertIn('disabled device bay', str(cm.exception.message_dict['installed_device']))
 
 
+    @tag('regression')  # Ref: #23617
+    def test_moving_parent_device_records_child_prechange(self):
+        DeviceBay.objects.create(device=self.parent_device, name='Bay 1', installed_device=self.child_device)
+        old_site = self.parent_device.site
+        new_site = Site.objects.create(name='Test Site 2', slug='test-site-2')
+        request = RequestFactory().get('/')
+        request.id = uuid.uuid4()
+        request.user = User.objects.create_user(username='testuser')
+
+        with event_tracking(request):
+            parent = Device.objects.get(pk=self.parent_device.pk)
+            parent.snapshot()
+            parent.site = new_site
+            parent.save()
+
+        change = ObjectChange.objects.get(
+            changed_object_type=ObjectType.objects.get_for_model(Device),
+            changed_object_id=self.child_device.pk,
+            action=ObjectChangeActionChoices.ACTION_UPDATE,
+        )
+        self.assertEqual(change.prechange_data['site'], old_site.pk)
+        self.assertEqual(change.postchange_data['site'], new_site.pk)
+
     def test_can_disable_bay_with_existing_device(self):
     def test_can_disable_bay_with_existing_device(self):
         """
         """
         Test that disabling a bay that already has a device installed does NOT raise an error
         Test that disabling a bay that already has a device installed does NOT raise an error
@@ -3440,6 +3506,65 @@ class CableDisconnectChangeLoggingTestCase(TestCase):
             action=ObjectChangeActionChoices.ACTION_UPDATE,
             action=ObjectChangeActionChoices.ACTION_UPDATE,
         ).order_by('time')
         ).order_by('time')
 
 
+    @tag('regression')  # Ref: #23617
+    def test_cable_creation_records_termination_prechange(self):
+        cable = self._connect(self.interface1, self.interface2)
+
+        # The update recording the terminations follows the creation of the Cable itself
+        change = self._updates(cable).get()
+        self.assertEqual(change.prechange_data['a_terminations'], [])
+        self.assertEqual(change.prechange_data['b_terminations'], [])
+        self.assertEqual(len(change.postchange_data['a_terminations']), 1)
+        self.assertEqual(len(change.postchange_data['b_terminations']), 1)
+
+    @tag('regression')  # Ref: #23617
+    def test_resaving_new_cable_records_current_prechange(self):
+        # The creation snapshot must not be reused, so the re-save falls back to the database
+        with self.assertLogs('netbox.models.features', level='WARNING'), event_tracking(self._request()):
+            cable = Cable(a_terminations=[self.interface1], b_terminations=[self.interface2])
+            cable.save()
+            cable.label = 'x'
+            cable.save()
+
+        change = self._updates(cable).last()
+        self.assertEqual(len(change.prechange_data['a_terminations']), 1)
+        self.assertEqual(len(change.prechange_data['b_terminations']), 1)
+        self.assertEqual(change.postchange_data['label'], 'x')
+
+    @tag('regression')  # Ref: #23617
+    def test_resaving_new_cable_with_preset_pk_records_current_prechange(self):
+        # A new Cable with a preset pk (e.g. restored by deserialize_object()) must also discard its creation snapshot
+        with self.assertLogs('netbox.models.features', level='WARNING'), event_tracking(self._request()):
+            cable = Cable(pk=1000000, a_terminations=[self.interface1], b_terminations=[self.interface2])
+            cable.save()
+            cable.label = 'x'
+            cable.save()
+
+        change = self._updates(cable).last()
+        self.assertEqual(len(change.prechange_data['a_terminations']), 1)
+        self.assertEqual(len(change.prechange_data['b_terminations']), 1)
+        self.assertEqual(change.postchange_data['label'], 'x')
+
+    @tag('regression')  # Ref: #23617
+    def test_termination_update_without_snapshot_records_prechange(self):
+        cable = self._connect(self.interface1, self.interface2)
+        old_b_termination = CableTermination.objects.get(cable=cable, cable_end=CableEndChoices.SIDE_B)
+
+        request = self._request()
+        with self.assertLogs('netbox.models.features', level='WARNING') as logs, event_tracking(request):
+            cable = Cable.objects.get(pk=cable.pk)
+            cable.label = 'x'
+            cable.b_terminations = [self.interface3]
+            cable.save()
+
+        change = self._updates(cable).get(request_id=request.id)
+        self.assertEqual(change.prechange_data['b_terminations'], [old_b_termination.pk])
+        self.assertEqual(change.prechange_data['label'], '')
+        self.assertNotEqual(change.postchange_data['b_terminations'], [old_b_termination.pk])
+        self.assertEqual(change.postchange_data['label'], 'x')
+        self.assertFalse(hasattr(cable, '_prechange_snapshot'))
+        self.assertEqual(len(logs.records), 1)
+
     @tag('regression')  # Ref: netbox-branching#631
     @tag('regression')  # Ref: netbox-branching#631
     def test_cable_deletion_records_disconnect(self):
     def test_cable_deletion_records_disconnect(self):
         cable = self._connect(self.interface1, self.interface2)
         cable = self._connect(self.interface1, self.interface2)
@@ -3517,6 +3642,7 @@ class CableDisconnectChangeLoggingTestCase(TestCase):
         request = self._request()
         request = self._request()
         with event_tracking(request):
         with event_tracking(request):
             cable = Cable.objects.get(pk=cable_pk)
             cable = Cable.objects.get(pk=cable_pk)
+            cable.snapshot()
             cable.b_terminations = [self.interface3]
             cable.b_terminations = [self.interface3]
             cable.save()
             cable.save()
 
 

+ 67 - 1
netbox/dcim/tests/test_views.py

@@ -5799,7 +5799,7 @@ class VirtualChassisTestCase(ViewTestCases.PrimaryObjectViewTestCase):
 
 
     @tag('regression')  # Ref: #23212
     @tag('regression')  # Ref: #23212
     def test_add_member_blocked_by_cross_chassis_lag(self):
     def test_add_member_blocked_by_cross_chassis_lag(self):
-        self.add_permissions('dcim.change_virtualchassis')
+        self.add_permissions('dcim.change_virtualchassis', 'dcim.change_device')
         vc1_member = Device.objects.get(name='Device 1')
         vc1_member = Device.objects.get(name='Device 1')
         device = Device.objects.get(name='Device 10')
         device = Device.objects.get(name='Device 10')
         lag = Interface.objects.create(device=vc1_member, name='lag0', type=InterfaceTypeChoices.TYPE_LAG)
         lag = Interface.objects.create(device=vc1_member, name='lag0', type=InterfaceTypeChoices.TYPE_LAG)
@@ -5815,6 +5815,72 @@ class VirtualChassisTestCase(ViewTestCases.PrimaryObjectViewTestCase):
         self.assertIsNone(device.virtual_chassis)
         self.assertIsNone(device.virtual_chassis)
         self.assertIsNone(device.vc_position)
         self.assertIsNone(device.vc_position)
 
 
+    def test_add_member(self):
+        self.add_permissions('dcim.change_virtualchassis', 'dcim.change_device')
+        device = Device.objects.get(name='Device 10')
+        vc = VirtualChassis.objects.get(name='VC1')
+
+        url = reverse('dcim:virtualchassis_add_member', kwargs={'pk': vc.pk})
+        response = self.client.post(url, {'device': device.pk, 'vc_position': 4, 'vc_priority': ''})
+        self.assertHttpStatus(response, 302)
+
+        device.refresh_from_db()
+        self.assertEqual(device.virtual_chassis, vc)
+        self.assertEqual(device.vc_position, 4)
+
+    @tag('regression')  # Ref: #23199
+    def test_add_member_requires_change_device_permission(self):
+        """
+        The add member form only displays and accepts devices the user can change.
+        """
+        self.add_permissions('dcim.change_virtualchassis')
+        device = Device.objects.get(name='Device 10')
+        vc = VirtualChassis.objects.get(name='VC1')
+        url = reverse('dcim:virtualchassis_add_member', kwargs={'pk': vc.pk})
+
+        # Adding the device is rejected
+        response = self.client.post(url, {'device': device.pk, 'vc_position': 4, 'vc_priority': ''})
+        self.assertHttpStatus(response, 200)
+        self.assertTrue(response.context['member_select_form'].has_error('device', code='invalid_choice'))
+        self.assertNotContains(response, device.name)
+
+        device.refresh_from_db()
+        self.assertIsNone(device.virtual_chassis)
+        self.assertIsNone(device.vc_position)
+
+        # The form does not display the device
+        response = self.client.get(url, {'device': device.pk})
+        self.assertHttpStatus(response, 200)
+        self.assertNotContains(response, device.name)
+
+    @tag('regression')  # Ref: #23199
+    def test_add_member_blocked_by_constrained_change_device_permission(self):
+        """
+        A device which would no longer satisfy the user's permission constraints once added is not saved.
+        """
+        self.add_permissions('dcim.change_virtualchassis')
+        obj_perm = ObjectPermission(
+            name='Test permission',
+            actions=['change'],
+            constraints={'virtual_chassis__isnull': True},
+        )
+        obj_perm.save()
+        obj_perm.users.add(self.user)
+        obj_perm.object_types.add(ObjectType.objects.get_for_model(Device))
+        device = Device.objects.get(name='Device 10')
+        vc = VirtualChassis.objects.get(name='VC1')
+
+        url = reverse('dcim:virtualchassis_add_member', kwargs={'pk': vc.pk})
+        response = self.client.post(url, {'device': device.pk, 'vc_position': 4, 'vc_priority': ''})
+        self.assertHttpStatus(response, 200)
+        self.assertIn(PermissionsViolation.message, response.context['membership_form'].non_field_errors())
+
+        # The change is rolled back
+        device.refresh_from_db()
+        self.assertIsNone(device.virtual_chassis)
+        self.assertIsNone(device.vc_position)
+        self.assertFalse(self._get_member_changes(device).exists())
+
     @tag('regression')  # Ref: #23212
     @tag('regression')  # Ref: #23212
     def test_create_with_members_blocked_by_cross_chassis_lag(self):
     def test_create_with_members_blocked_by_cross_chassis_lag(self):
         self.add_permissions('dcim.add_virtualchassis', 'dcim.view_device', 'dcim.change_device')
         self.add_permissions('dcim.add_virtualchassis', 'dcim.view_device', 'dcim.change_device')

+ 24 - 11
netbox/dcim/views.py

@@ -36,7 +36,7 @@ from netbox.ui.panels import (
 )
 )
 from netbox.views import generic
 from netbox.views import generic
 from utilities.exceptions import PermissionsViolation
 from utilities.exceptions import PermissionsViolation
-from utilities.forms import ConfirmationForm
+from utilities.forms import ConfirmationForm, restrict_form_fields
 from utilities.paginator import EnhancedPaginator, get_paginate_count
 from utilities.paginator import EnhancedPaginator, get_paginate_count
 from utilities.permissions import get_permission_for_model
 from utilities.permissions import get_permission_for_model
 from utilities.query import count_related
 from utilities.query import count_related
@@ -5298,6 +5298,7 @@ class VirtualChassisAddMemberView(ObjectPermissionRequiredMixin, GetReturnURLMix
         virtual_chassis = get_object_or_404(self.queryset, pk=pk)
         virtual_chassis = get_object_or_404(self.queryset, pk=pk)
         initial_data = {k: request.GET[k] for k in request.GET}
         initial_data = {k: request.GET[k] for k in request.GET}
         member_select_form = forms.VCMemberSelectForm(initial=initial_data)
         member_select_form = forms.VCMemberSelectForm(initial=initial_data)
+        restrict_form_fields(member_select_form, request.user, action='change')
         membership_form = forms.DeviceVCMembershipForm(initial=initial_data)
         membership_form = forms.DeviceVCMembershipForm(initial=initial_data)
 
 
         return render(request, 'dcim/virtualchassis_add_member.html', {
         return render(request, 'dcim/virtualchassis_add_member.html', {
@@ -5310,6 +5311,7 @@ class VirtualChassisAddMemberView(ObjectPermissionRequiredMixin, GetReturnURLMix
     def post(self, request, pk):
     def post(self, request, pk):
         virtual_chassis = get_object_or_404(self.queryset, pk=pk)
         virtual_chassis = get_object_or_404(self.queryset, pk=pk)
         member_select_form = forms.VCMemberSelectForm(request.POST)
         member_select_form = forms.VCMemberSelectForm(request.POST)
+        restrict_form_fields(member_select_form, request.user, action='change')
 
 
         if member_select_form.is_valid():
         if member_select_form.is_valid():
             device = member_select_form.cleaned_data['device']
             device = member_select_form.cleaned_data['device']
@@ -5329,16 +5331,27 @@ class VirtualChassisAddMemberView(ObjectPermissionRequiredMixin, GetReturnURLMix
                 membership_form.add_error(None, e.messages)
                 membership_form.add_error(None, e.messages)
 
 
             if membership_form.is_valid():
             if membership_form.is_valid():
-                membership_form.save()
-                messages.success(request, mark_safe(
-                    _('Added member <a href="{url}">{device}</a>').format(
-                        url=device.get_absolute_url(), device=escape(device)
-                    )
-                ))
-
-                if '_addanother' in request.POST and safe_for_redirect(request.get_full_path()):
-                    return redirect(request.get_full_path())
-                return redirect(self.get_return_url(request, device))
+                try:
+                    with transaction.atomic(using=router.db_for_write(Device)):
+                        membership_form.save()
+
+                        # Check that the device still conforms with any assigned object-level permissions
+                        if not Device.objects.restrict(request.user, 'change').filter(pk=device.pk).exists():
+                            raise PermissionsViolation()
+
+                    messages.success(request, mark_safe(
+                        _('Added member <a href="{url}">{device}</a>').format(
+                            url=device.get_absolute_url(), device=escape(device)
+                        )
+                    ))
+
+                    if '_addanother' in request.POST and safe_for_redirect(request.get_full_path()):
+                        return redirect(request.get_full_path())
+                    return redirect(self.get_return_url(request, device))
+
+                except PermissionsViolation as e:
+                    membership_form.add_error(None, e.message)
+                    clear_events.send(sender=self)
 
 
         else:
         else:
             membership_form = forms.DeviceVCMembershipForm(data=request.POST)
             membership_form = forms.DeviceVCMembershipForm(data=request.POST)

+ 4 - 2
netbox/extras/dashboard/utils.py

@@ -5,6 +5,7 @@ from django.core.exceptions import ObjectDoesNotExist
 from django.utils.translation import gettext as _
 from django.utils.translation import gettext as _
 
 
 from extras.constants import DEFAULT_DASHBOARD
 from extras.constants import DEFAULT_DASHBOARD
+from netbox.config import get_config
 from netbox.registry import registry
 from netbox.registry import registry
 
 
 __all__ = (
 __all__ = (
@@ -46,10 +47,11 @@ def get_dashboard(user):
         try:
         try:
             dashboard = user.dashboard
             dashboard = user.dashboard
         except ObjectDoesNotExist:
         except ObjectDoesNotExist:
-            # Create a dashboard for this user
+            # Create a dashboard for this user (unless the database is read-only)
             dashboard = get_default_dashboard()
             dashboard = get_default_dashboard()
             dashboard.user = user
             dashboard.user = user
-            dashboard.save()
+            if not get_config().MAINTENANCE_MODE:
+                dashboard.save()
 
 
     return dashboard
     return dashboard
 
 

+ 1 - 1
netbox/extras/forms/bulk_edit.py

@@ -302,7 +302,7 @@ class EventRuleBulkEditForm(OwnerMixin, NetBoxModelBulkEditForm):
         widget=BulkEditNullBooleanSelect()
         widget=BulkEditNullBooleanSelect()
     )
     )
     event_types = forms.MultipleChoiceField(
     event_types = forms.MultipleChoiceField(
-        choices=get_event_type_choices(),
+        choices=get_event_type_choices,
         required=False,
         required=False,
         label=_('Event types')
         label=_('Event types')
     )
     )

+ 5 - 1
netbox/extras/forms/bulk_import.py

@@ -317,7 +317,6 @@ class EventRuleImportForm(OwnerCSVMixin, NetBoxModelImportForm):
         help_text=_("One or more assigned object types")
         help_text=_("One or more assigned object types")
     )
     )
     event_types = CSVMultipleChoiceField(
     event_types = CSVMultipleChoiceField(
-        choices=get_event_type_choices(),
         label=_('Event types'),
         label=_('Event types'),
         help_text=_('The event type(s) which will trigger this rule')
         help_text=_('The event type(s) which will trigger this rule')
     )
     )
@@ -337,6 +336,11 @@ class EventRuleImportForm(OwnerCSVMixin, NetBoxModelImportForm):
             'owner', 'comments', 'tags'
             'owner', 'comments', 'tags'
         )
         )
 
 
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        # Resolved per instance because plugins register event types after this module is imported
+        self.fields['event_types'].choices = get_event_type_choices()
+
     def clean(self):
     def clean(self):
         super().clean()
         super().clean()
 
 

+ 1 - 1
netbox/extras/forms/model_forms.py

@@ -607,7 +607,7 @@ class EventRuleForm(OwnerMixin, NetBoxModelForm):
         queryset=ObjectType.objects.with_feature('event_rules'),
         queryset=ObjectType.objects.with_feature('event_rules'),
     )
     )
     event_types = MultipleChoiceField(
     event_types = MultipleChoiceField(
-        choices=get_event_type_choices(),
+        choices=get_event_type_choices,
         label=_('Event types')
         label=_('Event types')
     )
     )
     action_choice = ChoiceField(
     action_choice = ChoiceField(

+ 2 - 1
netbox/extras/models/models.py

@@ -287,7 +287,8 @@ class Webhook(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, OwnerMixin, Ch
         blank=True,
         blank=True,
         verbose_name=_('CA File Path'),
         verbose_name=_('CA File Path'),
         help_text=_(
         help_text=_(
-            "The specific CA certificate file to use for SSL verification. Leave blank to use the system defaults."
+            "The specific CA certificate file to use for SSL verification. If blank, verification uses NetBox's "
+            "built-in CA bundle, not the system trust store. A private CA must be specified here."
         )
         )
     )
     )
     timeout = models.PositiveSmallIntegerField(
     timeout = models.PositiveSmallIntegerField(

+ 4 - 0
netbox/extras/tests/test_event_rules.py

@@ -1181,6 +1181,7 @@ class EventRuleTestCase(RQQueueTestMixin, APITestCase):
         with event_tracking(request):
         with event_tracking(request):
             site = Site(name='Site 1', slug='site-1')
             site = Site(name='Site 1', slug='site-1')
             site.save()
             site.save()
+            site.snapshot()
             site.description = 'foo'
             site.description = 'foo'
             site.save()
             site.save()
         self.assertEqual(self.queue.count, 1, msg="Duplicate jobs found in queue")
         self.assertEqual(self.queue.count, 1, msg="Duplicate jobs found in queue")
@@ -1191,8 +1192,10 @@ class EventRuleTestCase(RQQueueTestMixin, APITestCase):
         # Test multiple updates
         # Test multiple updates
         site = Site.objects.create(name='Site 2', slug='site-2')
         site = Site.objects.create(name='Site 2', slug='site-2')
         with event_tracking(request):
         with event_tracking(request):
+            site.snapshot()
             site.description = 'foo'
             site.description = 'foo'
             site.save()
             site.save()
+            site.snapshot()
             site.description = 'bar'
             site.description = 'bar'
             site.save()
             site.save()
         self.assertEqual(self.queue.count, 1, msg="Duplicate jobs found in queue")
         self.assertEqual(self.queue.count, 1, msg="Duplicate jobs found in queue")
@@ -1203,6 +1206,7 @@ class EventRuleTestCase(RQQueueTestMixin, APITestCase):
         # Test update & delete
         # Test update & delete
         site = Site.objects.create(name='Site 3', slug='site-3')
         site = Site.objects.create(name='Site 3', slug='site-3')
         with event_tracking(request):
         with event_tracking(request):
+            site.snapshot()
             site.description = 'foo'
             site.description = 'foo'
             site.save()
             site.save()
             site.delete()
             site.delete()

+ 37 - 0
netbox/extras/tests/test_forms.py

@@ -12,12 +12,14 @@ from dcim.forms import SiteForm
 from dcim.models import Site
 from dcim.models import Site
 from extras.choices import CustomFieldTypeChoices, EventRuleActionChoices
 from extras.choices import CustomFieldTypeChoices, EventRuleActionChoices
 from extras.forms import SavedFilterForm, TableConfigBulkEditForm, TableConfigForm
 from extras.forms import SavedFilterForm, TableConfigBulkEditForm, TableConfigForm
+from extras.forms.bulk_edit import EventRuleBulkEditForm
 from extras.forms.bulk_import import EventRuleImportForm
 from extras.forms.bulk_import import EventRuleImportForm
 from extras.forms.filtersets import EventRuleFilterForm
 from extras.forms.filtersets import EventRuleFilterForm
 from extras.forms.model_forms import CustomFieldChoiceSetForm, EventRuleForm
 from extras.forms.model_forms import CustomFieldChoiceSetForm, EventRuleForm
 from extras.forms.scripts import ScriptFileForm
 from extras.forms.scripts import ScriptFileForm
 from extras.models import CustomField, CustomFieldChoiceSet, EventRule, NotificationGroup, Script, ScriptModule, Webhook
 from extras.models import CustomField, CustomFieldChoiceSet, EventRule, NotificationGroup, Script, ScriptModule, Webhook
 from netbox.event_rules import EventRuleAction, register_event_rule_action
 from netbox.event_rules import EventRuleAction, register_event_rule_action
+from netbox.events import EventType
 from netbox.registry import registry
 from netbox.registry import registry
 from utilities.forms.widgets import HTMXSelect
 from utilities.forms.widgets import HTMXSelect
 
 
@@ -522,6 +524,41 @@ class EventRuleFilterFormTestCase(TestCase):
         self.assertIn(None, choices)  # The blank choice is retained
         self.assertIn(None, choices)  # The blank choice is retained
 
 
 
 
+class EventRuleEventTypeChoicesTestCase(TestCase):
+    """
+    Event types registered after the forms module is imported (e.g. in a plugin's ready()) must be
+    offered by every event rule form.
+    """
+
+    def setUp(self):
+        EventType('test_late_event', 'Late event').register()
+        self.addCleanup(registry['event_types'].pop, 'test_late_event', None)
+
+    def test_model_form_offers_late_event_type(self):
+        choices = dict(EventRuleForm().fields['event_types'].choices)
+        self.assertEqual(choices.get('test_late_event'), 'Late event')
+
+    def test_bulk_edit_form_offers_late_event_type(self):
+        choices = dict(EventRuleBulkEditForm().fields['event_types'].choices)
+        self.assertEqual(choices.get('test_late_event'), 'Late event')
+
+    def test_filter_form_offers_late_event_type(self):
+        choices = dict(EventRuleFilterForm().fields['event_type'].choices)
+        self.assertEqual(choices.get('test_late_event'), 'Late event')
+
+    def test_import_form_accepts_late_event_type(self):
+        webhook = Webhook.objects.create(name='Late Event Webhook', payload_url='http://localhost:9000/')
+        form = EventRuleImportForm(data={
+            'name': 'Late Event Rule',
+            'object_types': 'dcim.site',
+            'event_types': 'test_late_event',
+            'action_type': EventRuleActionChoices.WEBHOOK,
+            'action_object': webhook.name,
+        })
+        self.assertTrue(form.is_valid(), form.errors)
+        self.assertEqual(form.cleaned_data['event_types'], ['test_late_event'])
+
+
 class EventRuleImportFormTestCase(TestCase):
 class EventRuleImportFormTestCase(TestCase):
     """
     """
     EventRuleImportForm resolves action_object via each registered action's resolve_import_object()
     EventRuleImportForm resolves action_object via each registered action's resolve_import_object()

+ 2 - 0
netbox/extras/tests/test_signals.py

@@ -286,8 +286,10 @@ class NotifyObjectChangedSignalTestCase(TestCase):
         # Trigger two updates within a single request; only one Notification should remain.
         # Trigger two updates within a single request; only one Notification should remain.
         request = _build_request(user=self.user)
         request = _build_request(user=self.user)
         with event_tracking(request):
         with event_tracking(request):
+            site.snapshot()
             site.description = 'first'
             site.description = 'first'
             site.save()
             site.save()
+            site.snapshot()
             site.description = 'second'
             site.description = 'second'
             site.save()
             site.save()
 
 

+ 4 - 2
netbox/extras/views.py

@@ -26,6 +26,7 @@ from extras.dashboard.forms import DashboardWidgetAddForm, DashboardWidgetForm
 from extras.dashboard.utils import get_widget_class
 from extras.dashboard.utils import get_widget_class
 from extras.scripts import prepare_script_form
 from extras.scripts import prepare_script_form
 from extras.utils import SharedObjectViewMixin
 from extras.utils import SharedObjectViewMixin
+from netbox.config import get_config
 from netbox.object_actions import *
 from netbox.object_actions import *
 from netbox.ui import layout
 from netbox.ui import layout
 from netbox.ui.panels import (
 from netbox.ui.panels import (
@@ -649,8 +650,9 @@ class NotificationReadView(LoginRequiredMixin, View):
     def get(self, request, pk):
     def get(self, request, pk):
         # Mark the Notification as read
         # Mark the Notification as read
         notification = get_object_or_404(request.user.notifications, pk=pk)
         notification = get_object_or_404(request.user.notifications, pk=pk)
-        notification.read = timezone.now()
-        notification.save()
+        if not get_config().MAINTENANCE_MODE:
+            notification.read = timezone.now()
+            notification.save()
 
 
         # Redirect to the object if it has a URL (deleted objects will not)
         # Redirect to the object if it has a URL (deleted objects will not)
         if hasattr(notification.object, 'get_absolute_url'):
         if hasattr(notification.object, 'get_absolute_url'):

+ 5 - 1
netbox/netbox/api/authentication.py

@@ -110,7 +110,11 @@ class TokenAuthentication(BaseAuthentication):
 
 
             # Load from LDAP if FIND_GROUP_PERMS is active
             # Load from LDAP if FIND_GROUP_PERMS is active
             # Always query LDAP when user is not active, otherwise it is never activated again
             # Always query LDAP when user is not active, otherwise it is never activated again
-            if ldap_backend.settings.FIND_GROUP_PERMS or not token.user.is_active:
+            # Skip this in maintenance mode, as it updates the user in the database
+            if get_config().MAINTENANCE_MODE:
+                logger = logging.getLogger('netbox.auth.login')
+                logger.debug("Maintenance mode enabled: Disabling update of user from LDAP directory")
+            elif ldap_backend.settings.FIND_GROUP_PERMS or not token.user.is_active:
                 ldap_user = ldap_backend.populate_user(token.user.username)
                 ldap_user = ldap_backend.populate_user(token.user.username)
                 # If the user is found in the LDAP directory use it, if not fallback to the local user
                 # If the user is found in the LDAP directory use it, if not fallback to the local user
                 if ldap_user:
                 if ldap_user:

+ 209 - 0
netbox/netbox/graphql/extensions.py

@@ -0,0 +1,209 @@
+import hashlib
+import json
+import logging
+import threading
+import time
+
+from graphql.language import (
+    FloatValueNode,
+    IntValueNode,
+    ListValueNode,
+    StringValueNode,
+    Visitor,
+    print_ast,
+    visit,
+)
+from graphql.utilities import strip_ignored_characters
+from strawberry.extensions import SchemaExtension
+
+from utilities.request import get_client_ip
+
+__all__ = (
+    'QueryLogger',
+    'log_graphql_queries',
+    'normalize_query',
+)
+
+logger = logging.getLogger('netbox.graphql.query')
+
+# Maximum length of the query and variables written to a log record
+MAX_LOGGED_LENGTH = 4096
+
+# Maximum number of normalized queries to cache
+NORMALIZED_QUERY_CACHE_SIZE = 512
+
+# Attribute on the request where QueryLogger leaves records for the view to complete and emit
+REQUEST_ATTR = '_graphql_query_log'
+
+
+class LiteralValueStripper(Visitor):
+    """
+    Replace literal argument values with fixed placeholders, so that queries differing only in the values they pass
+    produce the same document. Variables, enums, booleans and nulls are kept, as are the keys of input objects.
+    """
+    def enter_string_value(self, node, *args):
+        return StringValueNode(value='')
+
+    def enter_int_value(self, node, *args):
+        return IntValueNode(value='0')
+
+    def enter_float_value(self, node, *args):
+        return FloatValueNode(value='0')
+
+    def leave_list_value(self, node, *args):
+        # A list of placeholders collapses to an empty list so that its length doesn't matter. Lists containing any
+        # other values (variables, enums, input objects, etc.) are kept, since those are part of the query shape.
+        if all(isinstance(value, (StringValueNode, IntValueNode, FloatValueNode)) for value in node.values):
+            return ListValueNode(values=())
+        return None
+
+
+def normalize_query(document):
+    """
+    Return the given GraphQL document as a single line, with its literal argument values replaced by placeholders.
+    """
+    return strip_ignored_characters(print_ast(visit(document, LiteralValueStripper())))
+
+
+_normalized_queries = {}
+_normalized_queries_lock = threading.Lock()
+
+
+def _truncate(value):
+    if value is not None and len(value) > MAX_LOGGED_LENGTH:
+        return f'{value[:MAX_LOGGED_LENGTH]}...'
+    return value
+
+
+def _normalize_query_text(query, document):
+    """
+    Return the normalized form of the given query (and its parsed document), truncated for logging, along with the
+    hash of the full normalized query. Clients typically send the same query text repeatedly (passing values as
+    variables), so the result is cached. The cache is keyed on a digest of the query text, so that large queries don't
+    occupy memory.
+    """
+    key = hashlib.sha256(query.encode()).digest()
+    if (cached := _normalized_queries.get(key)) is not None:
+        return cached
+    normalized = normalize_query(document)
+    cached = (_truncate(normalized), hashlib.sha256(normalized.encode()).hexdigest())
+    with _normalized_queries_lock:
+        if len(_normalized_queries) >= NORMALIZED_QUERY_CACHE_SIZE:
+            # Evict the oldest entry
+            _normalized_queries.pop(next(iter(_normalized_queries)), None)
+        _normalized_queries[key] = cached
+    return cached
+
+
+def _emit(record):
+    logger.info(
+        "user=%s token_id=%s client_ip=%s operation_name=%s query_hash=%s duration_ms=%s error_count=%s "
+        "response_size=%s query=%s variables=%s",
+        json.dumps(record['user']),  # Encode to prevent log forging
+        record['token_id'],
+        record['client_ip'],
+        json.dumps(record['operation_name']),  # Client-supplied; encode to prevent log forging
+        record['query_hash'],
+        record['duration_ms'],
+        record['error_count'],
+        record['response_size'],
+        record['query'],
+        _truncate(json.dumps(record['variables'], default=str)),
+        extra={'graphql': record},
+    )
+
+
+def log_graphql_queries(request, response):
+    """
+    Complete and emit any records left on the request by QueryLogger, adding the response size and the total time
+    taken (including serialization of the response).
+    """
+    records = getattr(request, REQUEST_ATTR, None)
+    if not records:
+        return
+    try:
+        response_size = None if getattr(response, 'streaming', False) else len(response.content)
+        end = time.perf_counter()
+        for record, start in records:
+            record['duration_ms'] = round((end - start) * 1000, 1)
+            record['response_size'] = response_size
+            _emit(record)
+    except Exception:
+        # Never let a logging failure affect the response
+        logger.exception("Failed to log GraphQL operation")
+
+
+class QueryLogger(SchemaExtension):
+    """
+    Log each GraphQL operation to the `netbox.graphql.query` logger. Does nothing unless that logger is enabled for
+    INFO messages.
+
+    The record is left on the request, to be emitted by the view once the response has been rendered (see
+    log_graphql_queries()). Operations executed without a request are logged immediately, without a response size.
+    """
+    def on_operation(self):
+        if not logger.isEnabledFor(logging.INFO):
+            yield
+            return
+
+        start = time.perf_counter()
+        try:
+            yield
+        except Exception:
+            # The operation could not be executed (e.g. the requested operation name doesn't exist in the document)
+            self._record(start, failed=True)
+            raise
+        self._record(start)
+
+    def _record(self, start, failed=False):
+        try:
+            record = self._get_record(failed)
+            request = getattr(self.execution_context.context, 'request', None)
+            if request is None:
+                record['duration_ms'] = round((time.perf_counter() - start) * 1000, 1)
+                _emit(record)
+            else:
+                if not hasattr(request, REQUEST_ATTR):
+                    setattr(request, REQUEST_ATTR, [])
+                getattr(request, REQUEST_ATTR).append((record, start))
+        except Exception:
+            # Never let a logging failure affect the operation (or replace the exception it raised)
+            logger.exception("Failed to log GraphQL operation")
+
+    def _get_record(self, failed):
+        """
+        Return the details of the operation to be logged.
+        """
+        execution_context = self.execution_context
+        request = getattr(execution_context.context, 'request', None)
+
+        # Identify the user, token, and client
+        user = getattr(request, 'user', None)
+        token = getattr(request, 'auth', None)
+        try:
+            client_ip = get_client_ip(request) if request is not None else None
+        except ValueError:
+            client_ip = None
+
+        # Normalize the query (if it could be parsed)
+        if execution_context.graphql_document is not None and execution_context.query:
+            query, query_hash = _normalize_query_text(execution_context.query, execution_context.graphql_document)
+        else:
+            query = query_hash = None
+
+        result = execution_context.result
+        errors = (result.errors if result else None) or execution_context.pre_execution_errors or []
+        error_count = len(errors) or int(failed)
+
+        return {
+            'user': user.username if user is not None and user.is_authenticated else None,
+            'token_id': getattr(token, 'pk', None),
+            'client_ip': str(client_ip) if client_ip else None,
+            'operation_name': execution_context.operation_name,
+            'query_hash': query_hash,
+            'query': query,
+            'variables': execution_context.variables,
+            'duration_ms': None,
+            'error_count': error_count,
+            'response_size': None,
+        }

+ 2 - 0
netbox/netbox/graphql/schema.py

@@ -19,6 +19,7 @@ from virtualization.graphql.schema import VirtualizationQuery
 from vpn.graphql.schema import VPNQuery
 from vpn.graphql.schema import VPNQuery
 from wireless.graphql.schema import WirelessQuery
 from wireless.graphql.schema import WirelessQuery
 
 
+from .extensions import QueryLogger
 from .scalars import BigInt, BigIntScalar
 from .scalars import BigInt, BigIntScalar
 from .utils import validate_extension_targets
 from .utils import validate_extension_targets
 
 
@@ -51,6 +52,7 @@ def get_schema_extensions() -> list[SchemaExtensionFactory]:
     max_depth = settings.GRAPHQL_MAX_QUERY_DEPTH
     max_depth = settings.GRAPHQL_MAX_QUERY_DEPTH
 
 
     extensions: list[SchemaExtensionFactory] = [
     extensions: list[SchemaExtensionFactory] = [
+        QueryLogger,
         lambda: DjangoOptimizerExtension(prefetch_custom_queryset=True),
         lambda: DjangoOptimizerExtension(prefetch_custom_queryset=True),
         lambda: MaxAliasesLimiter(max_alias_count=max_aliases),
         lambda: MaxAliasesLimiter(max_alias_count=max_aliases),
     ]
     ]

+ 6 - 1
netbox/netbox/graphql/views.py

@@ -8,6 +8,7 @@ from strawberry.django.views import GraphQLView
 
 
 from netbox.api.authentication import TokenAuthentication
 from netbox.api.authentication import TokenAuthentication
 from netbox.config import get_config
 from netbox.config import get_config
+from netbox.graphql.extensions import log_graphql_queries
 
 
 
 
 class NetBoxGraphQLView(GraphQLView):
 class NetBoxGraphQLView(GraphQLView):
@@ -30,6 +31,7 @@ class NetBoxGraphQLView(GraphQLView):
                 auth_info = authenticator.authenticate(request)
                 auth_info = authenticator.authenticate(request)
                 if auth_info is not None:
                 if auth_info is not None:
                     request.user = auth_info[0]  # User object
                     request.user = auth_info[0]  # User object
+                    request.auth = auth_info[1]  # Token object
             except AuthenticationFailed as exc:
             except AuthenticationFailed as exc:
                 return HttpResponseForbidden(exc.detail)
                 return HttpResponseForbidden(exc.detail)
 
 
@@ -39,4 +41,7 @@ class NetBoxGraphQLView(GraphQLView):
                 return redirect_to_login(reverse('graphql'))
                 return redirect_to_login(reverse('graphql'))
             return HttpResponseForbidden("No credentials provided.")
             return HttpResponseForbidden("No credentials provided.")
 
 
-        return super().dispatch(request, *args, **kwargs)
+        response = super().dispatch(request, *args, **kwargs)
+        log_graphql_queries(request, response)
+
+        return response

+ 20 - 7
netbox/netbox/middleware.py

@@ -6,10 +6,11 @@ from django.contrib import auth, messages
 from django.contrib.auth.middleware import RemoteUserMiddleware as RemoteUserMiddleware_
 from django.contrib.auth.middleware import RemoteUserMiddleware as RemoteUserMiddleware_
 from django.core.exceptions import ImproperlyConfigured
 from django.core.exceptions import ImproperlyConfigured
 from django.core.signals import got_request_exception
 from django.core.signals import got_request_exception
-from django.db import ProgrammingError, connection
+from django.db import Error, ProgrammingError, connection
 from django.db.utils import InternalError
 from django.db.utils import InternalError
-from django.http import Http404, HttpResponseRedirect
+from django.http import Http404, HttpResponse, HttpResponseRedirect
 from django.middleware.common import CommonMiddleware as DjangoCommonMiddleware
 from django.middleware.common import CommonMiddleware as DjangoCommonMiddleware
+from django.template import loader
 from django.utils.translation import gettext_lazy as _
 from django.utils.translation import gettext_lazy as _
 from django_prometheus import middleware
 from django_prometheus import middleware
 from social_django.middleware import SocialAuthExceptionMiddleware as SocialAuthExceptionMiddleware_
 from social_django.middleware import SocialAuthExceptionMiddleware as SocialAuthExceptionMiddleware_
@@ -267,12 +268,20 @@ class MaintenanceModeMiddleware:
         self.get_response = get_response
         self.get_response = get_response
 
 
     def __call__(self, request):
     def __call__(self, request):
-        if get_config().MAINTENANCE_MODE:
-            self._set_session_type(
-                allow_write=request.path_info.startswith(settings.MAINTENANCE_EXEMPT_PATHS)
-            )
+        if not get_config().MAINTENANCE_MODE or request.path_info.startswith(settings.MAINTENANCE_EXEMPT_PATHS):
+            return self.get_response(request)
 
 
-        return self.get_response(request)
+        # The read-only setting persists on the connection, so restore read/write access once the request has been
+        # handled. This also lets outer middleware (e.g. saving the session) write to the database.
+        self._set_session_type(allow_write=False)
+        try:
+            return self.get_response(request)
+        finally:
+            try:
+                self._set_session_type(allow_write=True)
+            except Error:
+                # Never leave a read-only connection to be reused by a later request
+                connection.close()
 
 
     @staticmethod
     @staticmethod
     def _set_session_type(allow_write):
     def _set_session_type(allow_write):
@@ -297,6 +306,10 @@ class MaintenanceModeMiddleware:
             if is_api_request(request) or is_graphql_request(request):
             if is_api_request(request) or is_graphql_request(request):
                 return handle_rest_api_exception(request, error=error_message)
                 return handle_rest_api_exception(request, error=error_message)
 
 
+            # Redirecting a read-only request (e.g. GET) back to the same URL would fail the same way again
+            if request.method in ('GET', 'HEAD', 'OPTIONS'):
+                return HttpResponse(loader.render_to_string('exceptions/maintenance_mode.html'), status=503)
+
             messages.error(request, error_message)
             messages.error(request, error_message)
             return HttpResponseRedirect(request.path_info)
             return HttpResponseRedirect(request.path_info)
         return None
         return None

+ 23 - 0
netbox/netbox/models/features.py

@@ -1,4 +1,5 @@
 import json
 import json
+import logging
 from collections import defaultdict
 from collections import defaultdict
 from functools import cached_property
 from functools import cached_property
 
 
@@ -50,6 +51,8 @@ __all__ = (
     'register_models',
     'register_models',
 )
 )
 
 
+logger = logging.getLogger('netbox.models.features')
+
 
 
 #
 #
 # Feature mixins
 # Feature mixins
@@ -102,6 +105,21 @@ class ChangeLoggingMixin(DeleteMixin, models.Model):
         self._prechange_snapshot = self.serialize_object(exclude=exclude_fields)
         self._prechange_snapshot = self.serialize_object(exclude=exclude_fields)
     snapshot.alters_data = True
     snapshot.alters_data = True
 
 
+    def snapshot_from_db(self, using=None):
+        """
+        Snapshot the stored copy of an object being saved without a snapshot. The snapshot is discarded once the
+        save has been logged.
+        """
+        model = self.__class__
+        db = using or router.db_for_write(model, instance=self)
+        if (original := model._base_manager.using(db).filter(pk=self.pk).first()) is None:
+            return
+        logger.warning(f"No pre-change snapshot taken for {model._meta.label} {self.pk}; reading it from the database")
+        original.snapshot()
+        self._prechange_snapshot = original._prechange_snapshot
+        self._prechange_snapshot_from_db = True
+    snapshot_from_db.alters_data = True
+
     def to_objectchange(self, action):
     def to_objectchange(self, action):
         """
         """
         Return a new ObjectChange representing a change made to this object. This will typically be called automatically
         Return a new ObjectChange representing a change made to this object. This will typically be called automatically
@@ -702,10 +720,15 @@ class SyncedDataMixin(models.Model):
 
 
         :param save: If true, save() will be called after data has been synchronized
         :param save: If true, save() will be called after data has been synchronized
         """
         """
+        # ManagedFile is not change-logged and so has no snapshot(); keep any snapshot already taken
+        if save and hasattr(self, 'snapshot') and not hasattr(self, '_prechange_snapshot'):
+            self.snapshot()
         self.sync_data()
         self.sync_data()
         self.data_synced = timezone.now()
         self.data_synced = timezone.now()
         if save:
         if save:
             self.save()
             self.save()
+            # Discard the snapshot so that a later save of this object takes a fresh one
+            self.__dict__.pop('_prechange_snapshot', None)
     sync.alters_data = True
     sync.alters_data = True
 
 
     def sync_data(self):
     def sync_data(self):

+ 4 - 3
netbox/netbox/settings.py

@@ -671,10 +671,11 @@ EXEMPT_EXCLUDE_MODELS = (
 
 
 # All URLs starting with a string listed here are exempt from maintenance mode enforcement
 # All URLs starting with a string listed here are exempt from maintenance mode enforcement
 MAINTENANCE_EXEMPT_PATHS = (
 MAINTENANCE_EXEMPT_PATHS = (
-    f'/{BASE_PATH}extras/config-revisions/',  # Allow modifying the configuration
+    f'/{BASE_PATH}core/config-revisions/',  # Allow modifying the configuration
     LOGIN_URL,
     LOGIN_URL,
-    LOGIN_REDIRECT_URL,
-    LOGOUT_REDIRECT_URL
+    f'/{BASE_PATH}logout/',
+    f'/{BASE_PATH}oauth/',  # Single sign-on
+    f'/{BASE_PATH}api/users/tokens/provision/',  # Allow provisioning API tokens
 )
 )
 
 
 
 

+ 12 - 0
netbox/netbox/tests/test_authentication.py

@@ -1074,6 +1074,18 @@ class SSOLoginButtonTestCase(DjangoTestCase):
             self.assertEqual(auth_backend['params'].get('next'), '/dcim/sites/')
             self.assertEqual(auth_backend['params'].get('next'), '/dcim/sites/')
 
 
 
 
+class LoginViewTestCase(DjangoTestCase):
+
+    def test_login_missing_username(self):
+        """
+        A login form submission which omits the username field must be rejected as invalid (see #23665).
+        """
+        response = self.client.post(reverse('login'), {'password': 'wrongpassword'})
+
+        self.assertEqual(response.status_code, 200)
+        self.assertTrue(response.context['form'].errors.get('username'))
+
+
 class SocialAuthBeginViewTestCase(DjangoTestCase):
 class SocialAuthBeginViewTestCase(DjangoTestCase):
     """
     """
     Verify the view which initiates an SSO login. Chromium-based browsers evaluate the CSP
     Verify the view which initiates an SSO login. Chromium-based browsers evaluate the CSP

+ 269 - 0
netbox/netbox/tests/test_graphql.py

@@ -1,4 +1,6 @@
+import hashlib
 import json
 import json
+import logging
 import re
 import re
 from types import SimpleNamespace
 from types import SimpleNamespace
 from unittest import mock, skipIf
 from unittest import mock, skipIf
@@ -13,6 +15,7 @@ from django.test import override_settings
 from django.test.utils import CaptureQueriesContext
 from django.test.utils import CaptureQueriesContext
 from django.urls import reverse
 from django.urls import reverse
 from django.utils import timezone
 from django.utils import timezone
+from graphql import parse
 from rest_framework import status
 from rest_framework import status
 from strawberry.extensions import QueryDepthLimiter
 from strawberry.extensions import QueryDepthLimiter
 from strawberry.schema.config import StrawberryConfig
 from strawberry.schema.config import StrawberryConfig
@@ -38,6 +41,12 @@ from dcim.models import (
 from extras.choices import CustomFieldTypeChoices
 from extras.choices import CustomFieldTypeChoices
 from extras.models import CustomField, ExportTemplate, JournalEntry, TableConfig, Tag
 from extras.models import CustomField, ExportTemplate, JournalEntry, TableConfig, Tag
 from ipam.models import ASN, RIR, VLAN, Aggregate, IPAddress, Prefix
 from ipam.models import ASN, RIR, VLAN, Aggregate, IPAddress, Prefix
+from netbox.graphql.extensions import (
+    MAX_LOGGED_LENGTH,
+    _normalize_query_text,
+    _normalized_queries,
+    normalize_query,
+)
 from netbox.graphql.pagination import apply_distinct_window_pagination
 from netbox.graphql.pagination import apply_distinct_window_pagination
 from netbox.graphql.scalars import BigInt, BigIntScalar
 from netbox.graphql.scalars import BigInt, BigIntScalar
 from netbox.graphql.schema import Query, get_schema_extensions, schema
 from netbox.graphql.schema import Query, get_schema_extensions, schema
@@ -1512,6 +1521,266 @@ class GraphQLAPITestCase(APITestCase):
         self.assertEqual(data['errors'][0]['message'], 'Cannot specify both `start` and `offset` in pagination.')
         self.assertEqual(data['errors'][0]['message'], 'Cannot specify both `start` and `offset` in pagination.')
 
 
 
 
+class GraphQLQueryLoggerTestCase(APITestCase):
+
+    @classmethod
+    def setUpTestData(cls):
+        Site.objects.create(name='Site 1', slug='site-1')
+
+    def setUp(self):
+        super().setUp()
+        self.add_permissions('dcim.view_site')
+
+    def _post(self, data, **kwargs):
+        return self.client.post(reverse('graphql'), data=data, format='json', **kwargs)
+
+    def test_operation_logged(self):
+        """
+        Each operation is logged with the user, token, client, normalized query and result summary.
+        """
+        query = (
+            'query SiteNames($limit: Int) { '
+            'site_list(filters: {name: {exact: "Site 1"}}, pagination: {limit: $limit}) { name } }'
+        )
+        with self.assertLogs('netbox.graphql.query', level='INFO') as cm:
+            response = self._post({'query': query, 'variables': {'limit': 5}}, **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+
+        self.assertEqual(len(cm.records), 1)
+        data = cm.records[0].graphql
+        expected_query = (
+            'query SiteNames($limit:Int){site_list(filters:{name:{exact:""}}pagination:{limit:$limit}){name}}'
+        )
+        self.assertEqual(data['user'], self.user.username)
+        self.assertEqual(data['token_id'], self.token.pk)
+        self.assertEqual(data['client_ip'], '127.0.0.1')
+        self.assertEqual(data['operation_name'], 'SiteNames')
+        self.assertEqual(data['query'], expected_query)
+        self.assertEqual(data['query_hash'], hashlib.sha256(expected_query.encode()).hexdigest())
+        self.assertEqual(data['variables'], {'limit': 5})
+        self.assertEqual(data['error_count'], 0)
+        self.assertEqual(data['response_size'], len(response.content))
+        self.assertGreaterEqual(data['duration_ms'], 0)
+        self.assertIn(f'user={json.dumps(self.user.username)}', cm.output[0])
+        self.assertIn('operation_name="SiteNames"', cm.output[0])
+        self.assertNotIn('Site 1', cm.output[0])
+
+    def test_session_authentication_has_no_token(self):
+        """
+        Operations from a session-authenticated user are logged without a token ID.
+        """
+        self.client.force_login(self.user)
+        with self.assertLogs('netbox.graphql.query', level='INFO') as cm:
+            self._post({'query': '{ site_list { name } }'})
+
+        data = cm.records[0].graphql
+        self.assertEqual(data['user'], self.user.username)
+        self.assertIsNone(data['token_id'])
+        self.assertIsNone(data['operation_name'])
+
+    def test_errors_counted(self):
+        """
+        Errors raised before execution (e.g. validation failures) are counted.
+        """
+        with self.assertLogs('netbox.graphql.query', level='INFO') as cm:
+            response = self._post({'query': '{ site_list { name invalid_field } }'}, **self.header)
+
+        data = cm.records[0].graphql
+        self.assertEqual(data['error_count'], 1)
+        self.assertEqual(data['response_size'], len(response.content))
+        self.assertEqual(data['query'], '{site_list{name invalid_field}}')
+
+    def test_unparseable_query(self):
+        """
+        A query which can't be parsed is logged without a normalized query.
+        """
+        with self.assertLogs('netbox.graphql.query', level='INFO') as cm:
+            self._post({'query': '{ site_list {'}, **self.header)
+
+        data = cm.records[0].graphql
+        self.assertEqual(data['error_count'], 1)
+        self.assertIsNone(data['query'])
+        self.assertIsNone(data['query_hash'])
+
+    def test_operation_name_encoded(self):
+        """
+        A client-supplied operation name can't inject additional lines into the log.
+        """
+        operation_name = 'x\nuser=admin token_id=1 operation_name=ok'
+        with self.assertLogs('netbox.graphql.query', level='INFO') as cm:
+            # The supplied operation name is reported as-is when the query can't be parsed
+            self._post({'query': '{ site_list {', 'operationName': operation_name}, **self.header)
+
+        self.assertEqual(cm.records[0].graphql['operation_name'], operation_name)
+        self.assertNotIn('\n', cm.output[0])
+        self.assertIn(f'operation_name={json.dumps(operation_name)}', cm.output[0])
+
+    def test_unknown_operation_name(self):
+        """
+        An operation which can't be executed (here, because the named operation doesn't exist) is still logged.
+        """
+        with self.assertLogs('netbox.graphql.query', level='INFO') as cm:
+            response = self._post({'query': 'query A { site_list { name } }', 'operationName': 'B'}, **self.header)
+        self.assertHttpStatus(response, status.HTTP_400_BAD_REQUEST)
+
+        data = cm.records[0].graphql
+        self.assertEqual(data['operation_name'], 'B')
+        self.assertEqual(data['query'], 'query A{site_list{name}}')
+        self.assertEqual(data['error_count'], 1)
+        self.assertEqual(data['response_size'], len(response.content))
+
+    def test_long_values_truncated(self):
+        """
+        Long queries and variables are truncated in the log message.
+        """
+        name = 'x' * (MAX_LOGGED_LENGTH * 2)
+        query = f'query ($name: [String!]) {{ site_list(filters: {{name: {{in_list: $name}}}}) {{ {name}: name }} }}'
+        with self.assertLogs('netbox.graphql.query', level='INFO') as cm:
+            self._post({'query': query, 'variables': {'name': [name]}}, **self.header)
+
+        data = cm.records[0].graphql
+        self.assertEqual(len(data['query']), MAX_LOGGED_LENGTH + 3)
+        self.assertTrue(data['query'].endswith('...'))
+        self.assertLess(len(cm.output[0]), MAX_LOGGED_LENGTH * 3)
+
+    def test_normalization_cached(self):
+        """
+        Repeated queries are normalized once.
+        """
+        query = '{ site_list(filters: {name: {exact: "cache test"}}) { name } }'
+        with self.assertLogs('netbox.graphql.query', level='INFO'):
+            self._post({'query': query}, **self.header)
+            with mock.patch('netbox.graphql.extensions.normalize_query') as normalize_query:
+                self._post({'query': query}, **self.header)
+        normalize_query.assert_not_called()
+
+    def test_operation_without_request(self):
+        """
+        Operations executed without a request are logged immediately, without a response size.
+        """
+        with self.assertLogs('netbox.graphql.query', level='INFO') as cm:
+            schema.execute_sync('{ __typename }', context_value=SimpleNamespace())
+
+        data = cm.records[0].graphql
+        self.assertEqual(data['query'], '{__typename}')
+        self.assertIsNone(data['response_size'])
+        self.assertIsNotNone(data['duration_ms'])
+
+    def test_disabled_logger_does_nothing(self):
+        """
+        The extension does no work when the logger isn't enabled for INFO messages.
+        """
+        logger = logging.getLogger('netbox.graphql.query')
+        level = logger.level
+        logger.setLevel(logging.WARNING)
+        try:
+            with (
+                mock.patch('netbox.graphql.extensions._normalize_query_text') as normalize_query_text,
+                mock.patch('netbox.graphql.extensions.get_client_ip') as get_client_ip,
+            ):
+                response = self._post({'query': '{ site_list { name } }'}, **self.header)
+        finally:
+            logger.setLevel(level)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        normalize_query_text.assert_not_called()
+        get_client_ip.assert_not_called()
+
+    def test_logging_failure_does_not_affect_operation(self):
+        """
+        An error while logging an operation is logged, and doesn't affect the response.
+        """
+        with (
+            self.assertLogs('netbox.graphql.query', level='INFO') as cm,
+            mock.patch('netbox.graphql.extensions._normalize_query_text', side_effect=RuntimeError),
+        ):
+            response = self._post({'query': '{ site_list { name } }'}, **self.header)
+            # An operation which fails keeps its own error
+            failed_response = self._post(
+                {'query': 'query A { site_list { name } }', 'operationName': 'B'}, **self.header
+            )
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        self.assertEqual(response.json()['data'], {'site_list': [{'name': 'Site 1'}]})
+        self.assertHttpStatus(failed_response, status.HTTP_400_BAD_REQUEST)
+        self.assertEqual(
+            [record.getMessage() for record in cm.records],
+            ['Failed to log GraphQL operation', 'Failed to log GraphQL operation'],
+        )
+
+    def test_emit_failure_does_not_affect_response(self):
+        with (
+            self.assertLogs('netbox.graphql.query', level='INFO') as cm,
+            mock.patch('netbox.graphql.extensions._emit', side_effect=RuntimeError),
+        ):
+            response = self._post({'query': '{ site_list { name } }'}, **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        self.assertEqual(cm.records[0].getMessage(), 'Failed to log GraphQL operation')
+
+
+class NormalizeQueryTestCase(TestCase):
+
+    def test_literals_replaced(self):
+        query = (
+            '{ site_list(filters: {name: {exact: "Site 1"}, id: {in_list: [1, 2, 3]}, status: STATUS_ACTIVE}, '
+            'pagination: {limit: 10, offset: 2}) { id } }'
+        )
+        self.assertEqual(
+            normalize_query(parse(query)),
+            '{site_list(filters:{name:{exact:""}id:{in_list:[]}status:STATUS_ACTIVE}'
+            'pagination:{limit:0 offset:0}){id}}',
+        )
+
+    def test_values_do_not_affect_shape(self):
+        query_a = '{ site_list(filters: {name: {exact: "Site 1"}, id: {in_list: [1, 2, 3]}}) { id } }'
+        query_b = '{ site_list(filters: {name: {exact: "Site 2"}, id: {in_list: [4]}}) { id } }'
+        self.assertEqual(normalize_query(parse(query_a)), normalize_query(parse(query_b)))
+
+    def test_structure_affects_shape(self):
+        query_a = '{ site_list(filters: {name: {exact: "Site 1"}}) { id } }'
+        query_b = '{ site_list(filters: {slug: {exact: "Site 1"}}) { id } }'
+        self.assertNotEqual(normalize_query(parse(query_a)), normalize_query(parse(query_b)))
+
+    def test_lists_of_objects_kept(self):
+        query = '{ site_list(filters: {OR: [{name: {exact: "a"}}, {slug: {exact: "b"}}]}) { id } }'
+        self.assertEqual(
+            normalize_query(parse(query)),
+            '{site_list(filters:{OR:[{name:{exact:""}}{slug:{exact:""}}]}){id}}',
+        )
+
+    def test_lists_of_variables_and_enums_kept(self):
+        query = (
+            'query ($status: String) { site_list(filters: {status: {in_list: [$status]}}) { id } '
+            'location_list(filters: {status: {in_list: [STATUS_ACTIVE, STATUS_PLANNED]}}) { id } }'
+        )
+        self.assertEqual(
+            normalize_query(parse(query)),
+            'query($status:String){site_list(filters:{status:{in_list:[$status]}}){id}'
+            'location_list(filters:{status:{in_list:[STATUS_ACTIVE STATUS_PLANNED]}}){id}}',
+        )
+
+    def test_cache_bounded(self):
+        queries = [f'{{ {alias}: site_list {{ id }} }}' for alias in ('a', 'b', 'c')]
+        with (
+            mock.patch('netbox.graphql.extensions.NORMALIZED_QUERY_CACHE_SIZE', 2),
+            mock.patch.dict(_normalized_queries, clear=True),
+        ):
+            for query in queries:
+                _normalize_query_text(query, parse(query))
+            self.assertEqual(
+                list(_normalized_queries), [hashlib.sha256(query.encode()).digest() for query in queries[1:]]
+            )
+
+    def test_cache_holds_truncated_query(self):
+        """
+        The cache holds the normalized query truncated for logging, and the hash of the full normalized query.
+        """
+        query = f'{{ site_list {{ {"x" * MAX_LOGGED_LENGTH * 2}: name }} }}'
+        with mock.patch.dict(_normalized_queries, clear=True):
+            normalized, query_hash = _normalize_query_text(query, parse(query))
+            self.assertEqual(len(normalized), MAX_LOGGED_LENGTH + 3)
+            self.assertEqual(query_hash, hashlib.sha256(normalize_query(parse(query)).encode()).hexdigest())
+            self.assertEqual(list(_normalized_queries.values()), [(normalized, query_hash)])
+
+
 class GraphQLDeferredColumnTestCase(APITestCase):
 class GraphQLDeferredColumnTestCase(APITestCase):
     """
     """
     A GraphQL field backed by a custom resolver is opaque to the query optimizer, which narrows column
     A GraphQL field backed by a custom resolver is opaque to the query optimizer, which narrows column

+ 296 - 2
netbox/netbox/tests/test_middleware.py

@@ -4,13 +4,23 @@ from contextlib import contextmanager
 from types import SimpleNamespace
 from types import SimpleNamespace
 from unittest.mock import Mock, patch
 from unittest.mock import Mock, patch
 
 
+from django.contrib.messages import get_messages
+from django.core.cache import cache
 from django.core.signals import got_request_exception
 from django.core.signals import got_request_exception
-from django.db.utils import InternalError
-from django.test import RequestFactory, override_settings
+from django.db import connection
+from django.db.utils import InterfaceError, InternalError
+from django.test import RequestFactory, TransactionTestCase, override_settings
 from django.urls import reverse
 from django.urls import reverse
 from rest_framework import status
 from rest_framework import status
 
 
+from core.events import OBJECT_CREATED
+from core.models import ConfigRevision, ObjectType
+from dcim.models import Site
+from extras.models import ConfigContext, Dashboard, Notification, TableConfig
+from netbox.config import clear_config
 from netbox.middleware import CoreMiddleware, MaintenanceModeMiddleware
 from netbox.middleware import CoreMiddleware, MaintenanceModeMiddleware
+from users.constants import TOKEN_PREFIX
+from users.models import Token, User
 from utilities.testing import TestCase, disable_warnings
 from utilities.testing import TestCase, disable_warnings
 
 
 
 
@@ -141,6 +151,29 @@ class CoreMiddlewareTestCase(TestCase):
 
 
         self.assert_json_500_response(response)
         self.assert_json_500_response(response)
 
 
+    def test_maintenance_mode_handles_ui_post_request(self):
+        request = self.factory.post('/dcim/sites/add/')
+        request._messages = Mock()
+
+        with patch('netbox.middleware.get_config', return_value=SimpleNamespace(MAINTENANCE_MODE=True)):
+            response = self.process_internal_error(request, 'Simulated maintenance mode UI error')
+
+        self.assertEqual(response.status_code, 302)
+        self.assertEqual(response.url, '/dcim/sites/add/')
+
+    def test_maintenance_mode_handles_ui_get_request(self):
+        """
+        A failed write during a GET request must not redirect back to the same URL, which would fail again.
+        """
+        request = self.factory.get('/')
+
+        with patch('netbox.middleware.get_config', return_value=SimpleNamespace(MAINTENANCE_MODE=True)):
+            response = self.process_internal_error(request, 'Simulated maintenance mode UI error')
+
+        self.assertEqual(response.status_code, 503)
+        self.assertIn('maintenance mode', response.content.decode())
+        self.assertNotIn('Server Error', response.content.decode())
+
     def test_maintenance_mode_handles_graphql_json_request(self):
     def test_maintenance_mode_handles_graphql_json_request(self):
         request = self.factory.post(
         request = self.factory.post(
             reverse('graphql'),
             reverse('graphql'),
@@ -159,6 +192,267 @@ class CoreMiddlewareTestCase(TestCase):
         self.assert_json_500_response(response)
         self.assert_json_500_response(response)
 
 
 
 
+def is_read_only():
+    with connection.cursor() as cursor:
+        cursor.execute('SHOW transaction_read_only')
+        return cursor.fetchone()[0] == 'on'
+
+
+@override_settings(MAINTENANCE_MODE=True)
+class MaintenanceModeTestCase(TransactionTestCase):
+    """
+    Maintenance mode is enforced on the database session, which has no effect on writes within the transaction that
+    wraps each TestCase test, so these tests run against a real connection.
+    """
+
+    def setUp(self):
+        self.user = User.objects.create_user(username='testuser', password='testpassword', is_superuser=True)
+
+    def tearDown(self):
+        # Don't leave a read-only connection behind for other tests
+        with connection.cursor() as cursor:
+            cursor.execute('SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE')
+
+    def get_read_only_during_request(self, path):
+        """
+        Return whether the database connection was read-only while handling a request for the given path.
+        """
+        read_only = []
+
+        def get_response(request):
+            read_only.append(is_read_only())
+
+        MaintenanceModeMiddleware(get_response)(RequestFactory().get(path))
+        return read_only[0]
+
+    def test_exempt_paths(self):
+        exempt_paths = (
+            reverse('login'),
+            reverse('logout'),
+            reverse('social:begin', kwargs={'backend': 'github'}),
+            reverse('social:complete', kwargs={'backend': 'github'}),
+            reverse('core:configrevision_list'),
+            reverse('core:configrevision_add'),
+            reverse('users-api:token_provision'),
+        )
+        for path in exempt_paths:
+            with self.subTest(path=path):
+                self.assertFalse(self.get_read_only_during_request(path))
+                self.assertFalse(is_read_only())
+
+    def test_restricted_paths(self):
+        restricted_paths = (
+            reverse('home'),
+            reverse('dcim:site_add'),
+            reverse('account:preferences'),
+            reverse('api-root'),
+            reverse('graphql'),
+        )
+        for path in restricted_paths:
+            with self.subTest(path=path):
+                self.assertTrue(self.get_read_only_during_request(path))
+                self.assertFalse(is_read_only(), "Connection was left read-only after the request")
+
+    def test_maintenance_mode_disabled(self):
+        with override_settings(MAINTENANCE_MODE=False):
+            self.assertFalse(self.get_read_only_during_request(reverse('dcim:site_add')))
+
+    def test_ui_write_refused(self):
+        self.client.force_login(self.user)
+        url = reverse('dcim:site_add')
+
+        response = self.client.post(url, {'name': 'Site 1', 'slug': 'site-1', 'status': 'active'})
+
+        self.assertRedirects(response, url, fetch_redirect_response=False)
+        self.assertIn('maintenance mode', str(list(get_messages(response.wsgi_request))[0]))
+        self.assertFalse(Site.objects.exists())
+
+    def test_api_write_refused(self):
+        token = Token.objects.create(user=self.user)
+        header = {'HTTP_AUTHORIZATION': f'Bearer {TOKEN_PREFIX}{token.key}.{token.token}'}
+
+        response = self.client.post(
+            reverse('dcim-api:site-list'),
+            {'name': 'Site 1', 'slug': 'site-1', 'status': 'active'},
+            content_type='application/json',
+            **header,
+        )
+
+        self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)
+        self.assertIn('maintenance mode', response.json()['error'])
+        self.assertFalse(Site.objects.exists())
+
+    def test_api_user_config_write_refused(self):
+        """
+        Explicitly saving a user's preferences is refused, unlike the incidental changes made while viewing a page.
+        """
+        token = Token.objects.create(user=self.user)
+        header = {'HTTP_AUTHORIZATION': f'Bearer {TOKEN_PREFIX}{token.key}.{token.token}'}
+
+        response = self.client.patch(
+            reverse('users-api:userconfig-list'),
+            {'data_format': 'yaml'},
+            content_type='application/json',
+            **header,
+        )
+
+        self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)
+        self.assertIn('maintenance mode', response.json()['error'])
+        self.user.config.refresh_from_db()
+        self.assertIsNone(self.user.config.get('data_format'))
+
+    def test_writes_resume_when_maintenance_mode_disabled(self):
+        self.client.force_login(self.user)
+        data = {'name': 'Site 1', 'slug': 'site-1', 'status': 'active'}
+        self.client.post(reverse('dcim:site_add'), data)
+
+        with override_settings(MAINTENANCE_MODE=False):
+            response = self.client.post(reverse('dcim:site_add'), data)
+
+        self.assertEqual(response.status_code, 302)
+        self.assertTrue(Site.objects.filter(slug='site-1').exists())
+
+    @override_settings(SESSION_SAVE_EVERY_REQUEST=True)
+    def test_session_saved_on_every_request(self):
+        """
+        LOGIN_PERSISTENCE saves the session on every request.
+        """
+        self.client.force_login(self.user)
+
+        response = self.client.get(reverse('dcim:site_list'))
+
+        self.assertEqual(response.status_code, 200)
+
+    def test_login_and_logout(self):
+        response = self.client.post(reverse('login'), {'username': 'testuser', 'password': 'testpassword'})
+        self.assertEqual(response.status_code, 302)
+        self.assertEqual(int(self.client.session['_auth_user_id']), self.user.pk)
+
+        # The login time isn't recorded in maintenance mode
+        self.user.refresh_from_db()
+        self.assertIsNone(self.user.last_login)
+
+        response = self.client.get(reverse('logout'))
+        self.assertEqual(response.status_code, 302)
+        self.assertNotIn('_auth_user_id', self.client.session)
+
+        # The login time is recorded once maintenance mode is disabled
+        with override_settings(MAINTENANCE_MODE=False):
+            self.client.post(reverse('login'), {'username': 'testuser', 'password': 'testpassword'})
+        self.user.refresh_from_db()
+        self.assertIsNotNone(self.user.last_login)
+
+    @override_settings(REMOTE_AUTH_ENABLED=True, LOGIN_REQUIRED=True)
+    def test_remote_auth_login(self):
+        User.objects.create(username='remoteuser1')
+
+        # A refused write must not leave the connection read-only for the next request
+        self.client.force_login(self.user)
+        self.client.post(reverse('dcim:site_add'), {'name': 'Site 1', 'slug': 'site-1', 'status': 'active'})
+        self.client.logout()
+
+        response = self.client.get(reverse('home'), follow=True, HTTP_REMOTE_USER='remoteuser1')
+
+        self.assertEqual(response.status_code, 200)
+        self.assertEqual(self.client.session['_auth_user_id'], str(User.objects.get(username='remoteuser1').pk))
+
+    # Use a per-process cache, so that activating the new revision doesn't affect other tests
+    @override_settings(CACHES={
+        'default': {
+            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
+            'LOCATION': 'netbox-maintenance-mode-tests',
+        },
+    })
+    def test_modify_configuration(self):
+        self.addCleanup(cache.clear)
+        self.addCleanup(clear_config)
+        self.client.force_login(self.user)
+
+        response = self.client.post(reverse('core:configrevision_add'), {'comment': 'Disable maintenance mode'})
+
+        self.assertEqual(response.status_code, 302)
+        self.assertTrue(ConfigRevision.objects.filter(comment='Disable maintenance mode').exists())
+
+    def test_connection_closed_if_restore_fails(self):
+        middleware = MaintenanceModeMiddleware(lambda request: None)
+
+        # Simulate losing the connection before read/write access is restored
+        with (
+            patch.object(MaintenanceModeMiddleware, '_set_session_type', side_effect=[None, InterfaceError]),
+            patch('netbox.middleware.connection') as mock_connection,
+        ):
+            middleware(RequestFactory().get(reverse('home')))
+
+        mock_connection.close.assert_called_once()
+
+    def test_table_ordering_not_saved(self):
+        self.client.force_login(self.user)
+
+        response = self.client.get(reverse('dcim:site_list'), {'sort': 'name'})
+
+        self.assertEqual(response.status_code, 200)
+        self.user.config.refresh_from_db()
+        self.assertIsNone(self.user.config.get('tables.SiteTable.ordering'))
+
+    def test_table_config_not_saved(self):
+        tableconfig = TableConfig.objects.create(
+            name='Table Config 1',
+            object_type=ObjectType.objects.get_for_model(Site),
+            table='SiteTable',
+            user=self.user,
+            columns=['name', 'status'],
+            ordering=['name'],
+        )
+        self.client.force_login(self.user)
+
+        response = self.client.get(reverse('dcim:site_list'), {'tableconfig_id': tableconfig.pk})
+
+        self.assertEqual(response.status_code, 200)
+        self.user.config.refresh_from_db()
+        self.assertIsNone(self.user.config.get('tables.SiteTable.columns'))
+
+    def test_data_format_not_saved(self):
+        configcontext = ConfigContext.objects.create(name='Config Context 1', data={'foo': 'bar'})
+        self.client.force_login(self.user)
+
+        response = self.client.get(configcontext.get_absolute_url(), {'format': 'yaml'})
+
+        self.assertEqual(response.status_code, 200)
+        self.user.config.refresh_from_db()
+        self.assertIsNone(self.user.config.get('data_format'))
+
+    def test_default_dashboard_not_saved(self):
+        self.client.force_login(self.user)
+
+        response = self.client.get(reverse('home'))
+
+        self.assertEqual(response.status_code, 200)
+        self.assertEqual(list(get_messages(response.wsgi_request)), [])
+        self.assertFalse(Dashboard.objects.filter(user=self.user).exists())
+
+    def test_notification_not_marked_read(self):
+        site = Site.objects.create(name='Site 1', slug='site-1')
+        notification = Notification.objects.create(user=self.user, object=site, event_type=OBJECT_CREATED)
+        self.client.force_login(self.user)
+
+        response = self.client.get(reverse('extras:notification_read', kwargs={'pk': notification.pk}))
+
+        self.assertRedirects(response, site.get_absolute_url(), fetch_redirect_response=False)
+        notification.refresh_from_db()
+        self.assertIsNone(notification.read)
+
+    @override_settings(REMOTE_AUTH_BACKEND=['netbox.authentication.LDAPBackend'])
+    def test_api_ldap_user_not_updated(self):
+        token = Token.objects.create(user=self.user)
+        header = {'HTTP_AUTHORIZATION': f'Bearer {TOKEN_PREFIX}{token.key}.{token.token}'}
+
+        with patch('netbox.authentication.LDAPBackend') as mock_backend:
+            response = self.client.get(reverse('dcim-api:site-list'), **header)
+
+        self.assertEqual(response.status_code, status.HTTP_200_OK)
+        mock_backend.return_value.populate_user.assert_not_called()
+
+
 @override_settings(SENTRY_ENABLED=True)
 @override_settings(SENTRY_ENABLED=True)
 class SentryNotFoundReportingTestCase(TestCase):
 class SentryNotFoundReportingTestCase(TestCase):
 
 

+ 69 - 2
netbox/netbox/tests/test_model_features.py

@@ -1,15 +1,17 @@
 import hashlib
 import hashlib
+import uuid
 from unittest import skipIf
 from unittest import skipIf
+from unittest.mock import patch
 
 
 from django.apps import apps
 from django.apps import apps
 from django.conf import settings
 from django.conf import settings
 from django.contrib.contenttypes.models import ContentType
 from django.contrib.contenttypes.models import ContentType
 from django.core.exceptions import ValidationError
 from django.core.exceptions import ValidationError
-from django.test import TestCase
+from django.test import RequestFactory, TestCase
 from django.utils.timezone import now
 from django.utils.timezone import now
 from taggit.models import Tag
 from taggit.models import Tag
 
 
-from core.models import AutoSyncRecord, DataFile, DataSource
+from core.models import AutoSyncRecord, DataFile, DataSource, ManagedFile, ObjectChange
 from dcim.models import Site
 from dcim.models import Site
 from extras.models import (
 from extras.models import (
     ConfigContext,
     ConfigContext,
@@ -20,7 +22,9 @@ from extras.models import (
 )
 )
 from ipam.models import Prefix
 from ipam.models import Prefix
 from netbox.constants import CORE_APPS
 from netbox.constants import CORE_APPS
+from netbox.context_managers import event_tracking
 from netbox.models.features import CloningMixin, get_model_features, has_feature, model_is_public
 from netbox.models.features import CloningMixin, get_model_features, has_feature, model_is_public
+from users.models import User
 
 
 
 
 class ModelFeaturesTestCase(TestCase):
 class ModelFeaturesTestCase(TestCase):
@@ -149,6 +153,69 @@ class ModelFeaturesTestCase(TestCase):
                 obj.refresh_from_db()
                 obj.refresh_from_db()
                 self.assertEqual(getattr(obj, field_name), {})
                 self.assertEqual(getattr(obj, field_name), {})
 
 
+    def test_synceddatamixin_sync_records_prechange(self):
+        """Saving a sync records the object's state before the synchronized data was applied. Ref: #23617"""
+        datafile = self._create_data_file('template.j2', b'original\n')
+        obj = ConfigTemplate(name='Test', data_file=datafile)
+        obj.clean()
+        obj.save()
+        DataFile.objects.filter(pk=datafile.pk).update(data=b'updated\n')
+        request = RequestFactory().get('/')
+        request.id = uuid.uuid4()
+        request.user = User.objects.create_user(username='testuser')
+
+        template = ConfigTemplate.objects.get(pk=obj.pk)
+        with event_tracking(request):
+            template.sync(save=True)
+
+        change = ObjectChange.objects.get(
+            changed_object_type=ContentType.objects.get_for_model(ConfigTemplate),
+            changed_object_id=obj.pk,
+        )
+        self.assertEqual(change.prechange_data['template_code'], 'original\n')
+        self.assertEqual(change.postchange_data['template_code'], 'updated\n')
+        self.assertFalse(hasattr(template, '_prechange_snapshot'))
+
+    def test_synceddatamixin_sync_keeps_existing_snapshot(self):
+        """Saving a sync records a snapshot taken by the caller, then discards it. Ref: #23617"""
+        datafile = self._create_data_file('template.j2', b'original\n')
+        obj = ConfigTemplate(name='Test', data_file=datafile)
+        obj.clean()
+        obj.save()
+        DataFile.objects.filter(pk=datafile.pk).update(data=b'updated\n')
+        request = RequestFactory().get('/')
+        request.id = uuid.uuid4()
+        request.user = User.objects.create_user(username='testuser')
+
+        template = ConfigTemplate.objects.get(pk=obj.pk)
+        with self.assertNoLogs('netbox.models.features', level='WARNING'), event_tracking(request):
+            template.snapshot()
+            template.description = 'updated'
+            # Without save, sync() leaves the caller's snapshot for its own save
+            template.sync()
+            self.assertTrue(hasattr(template, '_prechange_snapshot'))
+            template.sync(save=True)
+
+        change = ObjectChange.objects.get(
+            changed_object_type=ContentType.objects.get_for_model(ConfigTemplate),
+            changed_object_id=obj.pk,
+        )
+        self.assertEqual(change.prechange_data['description'], '')
+        self.assertEqual(change.postchange_data['description'], 'updated')
+        self.assertFalse(hasattr(template, '_prechange_snapshot'))
+
+    @patch.object(ManagedFile, 'sync_data')
+    def test_synceddatamixin_sync_without_change_logging(self, mock_sync_data):
+        """Saving a sync succeeds for models which are not change-logged. Ref: #23617"""
+        datafile = self._create_data_file('script.py', b'# script\n')
+        obj = ManagedFile.objects.create(file_root='scripts', file_path='script.py', data_file=datafile)
+
+        obj.sync(save=True)
+
+        mock_sync_data.assert_called_once()
+        obj.refresh_from_db()
+        self.assertIsNotNone(obj.data_synced)
+
     def test_synceddatamixin_accepts_plain_text_template(self):
     def test_synceddatamixin_accepts_plain_text_template(self):
         """Text which is not a YAML document is still valid template content."""
         """Text which is not a YAML document is still valid template content."""
         datafile = self._create_data_file('comment-only.j2', b'{# nothing here #}\n')
         datafile = self._create_data_file('comment-only.j2', b'{# nothing here #}\n')

+ 5 - 5
netbox/netbox/tests/test_search.py

@@ -218,11 +218,11 @@ class SearchBackendTestCase(TestCase):
         device_type = DeviceType.objects.create(manufacturer=manufacturer, model='Device Type 1', slug='device-type-1')
         device_type = DeviceType.objects.create(manufacturer=manufacturer, model='Device Type 1', slug='device-type-1')
         role = DeviceRole.objects.create(name='Device Role 1', slug='device-role-1')
         role = DeviceRole.objects.create(name='Device Role 1', slug='device-role-1')
 
 
-        def render_results(sites):
+        def render_results(sites, offset):
             # Unnamed devices render as "<manufacturer> <model> (<pk>)"; prefixes display their scope (a site)
             # Unnamed devices render as "<manufacturer> <model> (<pk>)"; prefixes display their scope (a site)
-            for site in sites:
+            for i, site in enumerate(sites, start=offset):
                 Device.objects.create(site=site, device_type=device_type, role=role, description='Batched')
                 Device.objects.create(site=site, device_type=device_type, role=role, description='Batched')
-                Prefix.objects.create(prefix=f'10.0.{site.pk}.0/24', scope=site, description='Batched')
+                Prefix.objects.create(prefix=f'10.0.{i}.0/24', scope=site, description='Batched')
             search_backend.cache(Device.objects.all())
             search_backend.cache(Device.objects.all())
             search_backend.cache(Prefix.objects.all())
             search_backend.cache(Prefix.objects.all())
 
 
@@ -233,9 +233,9 @@ class SearchBackendTestCase(TestCase):
             return rendered, len(queries)
             return rendered, len(queries)
 
 
         sites = list(Site.objects.order_by('name'))
         sites = list(Site.objects.order_by('name'))
-        rendered, query_count = render_results(sites[:1])
+        rendered, query_count = render_results(sites[:1], 0)
         self.assertEqual(len(rendered), 2)
         self.assertEqual(len(rendered), 2)
-        rendered, more_query_count = render_results(sites[1:])
+        rendered, more_query_count = render_results(sites[1:], 1)
         self.assertEqual(len(rendered), 6)
         self.assertEqual(len(rendered), 6)
         self.assertEqual(more_query_count, query_count)
         self.assertEqual(more_query_count, query_count)
 
 

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 0 - 0
netbox/project-static/dist/netbox.js


Filskillnaden har hållts tillbaka eftersom den är för stor
+ 0 - 0
netbox/project-static/dist/netbox.js.map


+ 33 - 2
netbox/project-static/src/htmx.ts

@@ -8,6 +8,12 @@ import { initMessages } from './messages';
 import { initQuickAdd } from './quickAdd';
 import { initQuickAdd } from './quickAdd';
 import { focusFirstFormError } from './forms/errors';
 import { focusFirstFormError } from './forms/errors';
 
 
+type HtmxConfigRequestDetail = {
+  elt: Element;
+  verb: string;
+  formData: FormData;
+};
+
 type HtmxSettleDetail = {
 type HtmxSettleDetail = {
   elt?: Element;
   elt?: Element;
   target?: Element;
   target?: Element;
@@ -28,6 +34,30 @@ function initDepedencies(): void {
   initMessages();
   initMessages();
 }
 }
 
 
+/**
+ * On an object edit form refresh (see HTMXSelect), send each cleared multiple select as an empty
+ * value, so the server does not render its saved selection again.
+ */
+function includeClearedMultipleSelects(event: Event): void {
+  const { elt, verb, formData } = (event as CustomEvent<HtmxConfigRequestDetail>).detail;
+  const include = elt.getAttribute('hx-include');
+  if (verb !== 'get' || !include?.startsWith('#') || !elt.closest('form.object-edit')) return;
+
+  // htmx applies hx-params before this event, so leave filtered requests as they are
+  const params = elt.closest('[hx-params], [data-hx-params]');
+  const filter = params?.getAttribute('hx-params') ?? params?.getAttribute('data-hx-params');
+  if (params && filter !== '*') return;
+
+  const container = document.getElementById(include.slice(1));
+  const selects = container?.querySelectorAll<HTMLSelectElement>('select[multiple]');
+  for (const select of selects ?? []) {
+    const empty = !select.selectedOptions.length;
+    if (select.name && empty && !select.matches(':disabled') && !formData.has(select.name)) {
+      formData.append(select.name, '');
+    }
+  }
+}
+
 /**
 /**
  * Reveal validation errors only for a swapped-in form submission, scoped to the swapped content.
  * Reveal validation errors only for a swapped-in form submission, scoped to the swapped content.
  * Dependent-field refreshes post on `change` and re-render a bound form, so gating on the verb
  * Dependent-field refreshes post on `change` and re-render a bound form, so gating on the verb
@@ -48,10 +78,11 @@ function revealSubmissionErrors(event: Event): void {
 }
 }
 
 
 /**
 /**
- * Hook into HTMX's event system to reinitialize specific native event listeners when HTMX swaps
- * elements.
+ * Hook into HTMX's event system to complete object edit form refreshes, and to reinitialize specific
+ * native event listeners when HTMX swaps elements.
  */
  */
 export function initHtmx(): void {
 export function initHtmx(): void {
+  document.addEventListener('htmx:configRequest', includeClearedMultipleSelects);
   document.addEventListener('htmx:afterSettle', event => {
   document.addEventListener('htmx:afterSettle', event => {
     initDepedencies();
     initDepedencies();
     revealSubmissionErrors(event);
     revealSubmissionErrors(event);

+ 2 - 1
netbox/templates/500.html

@@ -5,6 +5,7 @@
 
 
 <head>
 <head>
   <title>{% trans "Server Error" %}</title>
   <title>{% trans "Server Error" %}</title>
+  <link rel="stylesheet" href="{% static 'netbox-external.css' %}" />
   <link rel="stylesheet" href="{% static 'netbox.css'%}" />
   <link rel="stylesheet" href="{% static 'netbox.css'%}" />
   <meta charset="UTF-8">
   <meta charset="UTF-8">
 </head>
 </head>
@@ -15,7 +16,7 @@
       <div class="col col-md-6 offset-md-3">
       <div class="col col-md-6 offset-md-3">
         <div class="card border-danger mt-5">
         <div class="card border-danger mt-5">
           <h2 class="card-header text-bg-danger">
           <h2 class="card-header text-bg-danger">
-            <i class="mdi mdi-alert"></i> {% trans "Server Error" %}
+            <i class="mdi mdi-alert me-1"></i> {% trans "Server Error" %}
           </h2>
           </h2>
           <div class="card-body">
           <div class="card-body">
             {% block message %}
             {% block message %}

+ 35 - 0
netbox/templates/exceptions/maintenance_mode.html

@@ -0,0 +1,35 @@
+{% load i18n %}
+{% load static %}
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+  <title>{% trans "Maintenance Mode" %}</title>
+  <link rel="stylesheet" href="{% static 'netbox-external.css' %}" />
+  <link rel="stylesheet" href="{% static 'netbox.css'%}" />
+  <meta charset="UTF-8">
+</head>
+
+<body>
+  <div class="container-fluid">
+    <div class="row">
+      <div class="col col-md-6 offset-md-3">
+        <div class="card border-warning mt-5">
+          <h2 class="card-header text-bg-warning">
+            <i class="mdi mdi-wrench me-1"></i> {% trans "Maintenance Mode" %}
+          </h2>
+          <div class="card-body">
+            <p>
+              {% trans "NetBox is currently operating in maintenance mode and is unable to perform write operations. Please try again later." %}
+            </p>
+            <div class="text-end">
+              <a href="{% url 'home' %}" class="btn btn-primary">{% trans "Home Page" %}</a>
+            </div>
+          </div>
+        </div>
+      </div>
+    </div>
+  </div>
+</body>
+
+</html>

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 174 - 174
netbox/translations/en/LC_MESSAGES/django.po


+ 12 - 4
netbox/users/models/preferences.py

@@ -81,7 +81,8 @@ class UserConfig(models.Model):
 
 
         :param path: Dotted path to the configuration key. For example, 'foo.bar' sets self.data['foo']['bar'].
         :param path: Dotted path to the configuration key. For example, 'foo.bar' sets self.data['foo']['bar'].
         :param value: The value to be written. This can be any type supported by JSON.
         :param value: The value to be written. This can be any type supported by JSON.
-        :param commit: If true, the UserConfig instance will be saved once the new value has been applied.
+        :param commit: If true, the UserConfig instance will be saved once the new value has been applied. (The save
+            is skipped while maintenance mode is enabled, since the database may be read-only.)
         """
         """
         d = self.data
         d = self.data
         keys = path.split('.')
         keys = path.split('.')
@@ -112,7 +113,7 @@ class UserConfig(models.Model):
             d[key] = value
             d[key] = value
 
 
         if commit:
         if commit:
-            self.save()
+            self._commit()
     set.alters_data = True
     set.alters_data = True
 
 
     def clear(self, path, commit=False):
     def clear(self, path, commit=False):
@@ -125,7 +126,8 @@ class UserConfig(models.Model):
         Invalid keys will be ignored silently.
         Invalid keys will be ignored silently.
 
 
         :param path: Dotted path to the configuration key. For example, 'foo.bar' deletes self.data['foo']['bar'].
         :param path: Dotted path to the configuration key. For example, 'foo.bar' deletes self.data['foo']['bar'].
-        :param commit: If true, the UserConfig instance will be saved once the new value has been applied.
+        :param commit: If true, the UserConfig instance will be saved once the new value has been applied. (The save
+            is skipped while maintenance mode is enabled, since the database may be read-only.)
         """
         """
         d = self.data
         d = self.data
         keys = path.split('.')
         keys = path.split('.')
@@ -140,5 +142,11 @@ class UserConfig(models.Model):
         d.pop(key, None)  # Avoid a KeyError on invalid keys
         d.pop(key, None)  # Avoid a KeyError on invalid keys
 
 
         if commit:
         if commit:
-            self.save()
+            self._commit()
     clear.alters_data = True
     clear.alters_data = True
+
+    def _commit(self):
+        # Don't save the change while maintenance mode is enabled: the database may be read-only, and these changes
+        # are typically incidental to a read-only request (e.g. a table's ordering).
+        if not get_config().MAINTENANCE_MODE:
+            self.save()

+ 18 - 0
netbox/users/signals.py

@@ -1,6 +1,7 @@
 import copy
 import copy
 import logging
 import logging
 
 
+from django.contrib.auth.models import update_last_login as django_update_last_login
 from django.contrib.auth.signals import user_logged_in, user_login_failed
 from django.contrib.auth.signals import user_logged_in, user_login_failed
 from django.db.models.signals import post_save
 from django.db.models.signals import post_save
 from django.dispatch import receiver
 from django.dispatch import receiver
@@ -24,6 +25,23 @@ def log_user_login_failed(sender, credentials, request, **kwargs):
         logger.info(f"Failed login attempt for username: {username}")
         logger.info(f"Failed login attempt for username: {username}")
 
 
 
 
+# Replace Django's receiver, which always records the login time
+user_logged_in.disconnect(dispatch_uid='update_last_login')
+
+
+@receiver(user_logged_in, dispatch_uid='update_last_login')
+def update_last_login(sender, user, **kwargs):
+    """
+    Record the user's login time, unless maintenance mode is enabled. This allows users to log in while the database
+    is read-only, whichever authentication method they use.
+    """
+    if get_config().MAINTENANCE_MODE:
+        logger = logging.getLogger('netbox.auth.login')
+        logger.debug("Maintenance mode enabled: disabling update of most recent login time")
+        return
+    django_update_last_login(sender, user, **kwargs)
+
+
 @receiver(user_logged_in)
 @receiver(user_logged_in)
 def set_language_on_login(sender, user, request, **kwargs):
 def set_language_on_login(sender, user, request, **kwargs):
     """
     """

+ 14 - 0
netbox/users/tests/test_models.py

@@ -233,6 +233,20 @@ class UserConfigTestCase(TestCase):
         # Clear a non-existing value; should fail silently
         # Clear a non-existing value; should fail silently
         userconfig.clear('invalid')
         userconfig.clear('invalid')
 
 
+    @override_settings(MAINTENANCE_MODE=True)
+    def test_commit_skipped_in_maintenance_mode(self):
+        userconfig = User.objects.get(username='testuser').config
+
+        # The change is applied, but not saved
+        userconfig.set('a', 'def', commit=True)
+        userconfig.clear('b.foo', commit=True)
+        self.assertEqual(userconfig.data['a'], 'def')
+        self.assertNotIn('foo', userconfig.data['b'])
+
+        userconfig.refresh_from_db()
+        self.assertEqual(userconfig.data['a'], True)
+        self.assertEqual(userconfig.data['b']['foo'], 101)
+
 
 
 class RestrictedQuerySetTestCase(TestCase):
 class RestrictedQuerySetTestCase(TestCase):
     """
     """

+ 5 - 1
netbox/utilities/forms/fields/dynamic.py

@@ -145,7 +145,11 @@ class DynamicModelChoiceMixin:
                 if value:
                 if value:
                     filter_kwargs[kwarg] = value
                     filter_kwargs[kwarg] = value
             if filter_kwargs:
             if filter_kwargs:
-                queryset = self.queryset.filter(**filter_kwargs)
+                try:
+                    queryset = self.queryset.filter(**filter_kwargs)
+                except (TypeError, ValueError):
+                    # Catch any error caused by invalid initial data passed from the user
+                    queryset = self.queryset.none()
                 if isinstance(self, forms.ModelMultipleChoiceField):
                 if isinstance(self, forms.ModelMultipleChoiceField):
                     # A lookup across a reverse relation yields one row per matching child
                     # A lookup across a reverse relation yields one row per matching child
                     self.initial = list(queryset.distinct())
                     self.initial = list(queryset.distinct())

+ 10 - 2
netbox/utilities/tests/test_forms.py

@@ -766,7 +766,7 @@ class DynamicModelChoiceFieldTestCase(TestCase):
         )
         )
         Rack.objects.bulk_create(cls.racks)
         Rack.objects.bulk_create(cls.racks)
 
 
-    def _make_form(self, site_field_class, data=None, rack_context=None):
+    def _make_form(self, site_field_class, data=None, rack_context=None, rack_initial=None):
         class TestForm(forms.Form):
         class TestForm(forms.Form):
             rack = DynamicModelMultipleChoiceField(queryset=Rack.objects.all(), required=False, context=rack_context)
             rack = DynamicModelMultipleChoiceField(queryset=Rack.objects.all(), required=False, context=rack_context)
             site = site_field_class(
             site = site_field_class(
@@ -774,7 +774,9 @@ class DynamicModelChoiceFieldTestCase(TestCase):
                 required=False,
                 required=False,
                 initial_params={'racks__in': '$rack'},
                 initial_params={'racks__in': '$rack'},
             )
             )
-        return TestForm(data=data, initial={'rack': [rack.pk for rack in self.racks]})
+        if rack_initial is None:
+            rack_initial = [rack.pk for rack in self.racks]
+        return TestForm(data=data, initial={'rack': rack_initial})
 
 
     def test_multiple_choice_field_selects_every_matching_object(self):
     def test_multiple_choice_field_selects_every_matching_object(self):
         """A multiple-choice parent field selects every distinct object matched by initial_params."""
         """A multiple-choice parent field selects every distinct object matched by initial_params."""
@@ -801,6 +803,12 @@ class DynamicModelChoiceFieldTestCase(TestCase):
         self.assertIn(field.initial, self.sites)
         self.assertIn(field.initial, self.sites)
         self.assertEqual(field.queryset.count(), 1)
         self.assertEqual(field.queryset.count(), 1)
 
 
+    def test_invalid_child_value_leaves_initial_unset(self):
+        """An invalid child value leaves a parent field without an initial value."""
+        field = self._make_form(DynamicModelMultipleChoiceField, rack_initial=[''])['site'].field
+
+        self.assertFalse(field.initial)
+
     def test_options_name_their_parent(self):
     def test_options_name_their_parent(self):
         """Each rendered option names its parent object."""
         """Each rendered option names its parent object."""
         html = str(self._make_form(DynamicModelMultipleChoiceField, rack_context={'parent': 'site'})['rack'])
         html = str(self._make_form(DynamicModelMultipleChoiceField, rack_context={'parent': 'site'})['rack'])

+ 8 - 0
netbox/wireless/signals.py

@@ -27,12 +27,20 @@ def update_connected_interfaces(instance, created, raw=False, **kwargs):
 
 
     if instance.interface_a.wireless_link != instance:
     if instance.interface_a.wireless_link != instance:
         logger.debug(f"Updating interface A for wireless link {instance}")
         logger.debug(f"Updating interface A for wireless link {instance}")
+        # Keep any snapshot the caller took before making unsaved changes to the interface
+        if not hasattr(instance.interface_a, '_prechange_snapshot'):
+            instance.interface_a.snapshot()
         instance.interface_a.wireless_link = instance
         instance.interface_a.wireless_link = instance
         instance.interface_a.save()
         instance.interface_a.save()
+        # Discard the snapshot so that a later save of the interface takes a fresh one
+        instance.interface_a.__dict__.pop('_prechange_snapshot', None)
     if instance.interface_b.wireless_link != instance:
     if instance.interface_b.wireless_link != instance:
         logger.debug(f"Updating interface B for wireless link {instance}")
         logger.debug(f"Updating interface B for wireless link {instance}")
+        if not hasattr(instance.interface_b, '_prechange_snapshot'):
+            instance.interface_b.snapshot()
         instance.interface_b.wireless_link = instance
         instance.interface_b.wireless_link = instance
         instance.interface_b.save()
         instance.interface_b.save()
+        instance.interface_b.__dict__.pop('_prechange_snapshot', None)
 
 
     # Create/update cable paths
     # Create/update cable paths
     if created:
     if created:

+ 48 - 0
netbox/wireless/tests/test_models.py

@@ -66,6 +66,54 @@ class WirelessLinkTestCase(TestCase):
         cls.device = create_test_device('Device 1')
         cls.device = create_test_device('Device 1')
         cls.user = User.objects.create_user(username='testuser')
         cls.user = User.objects.create_user(username='testuser')
 
 
+    # Regression test for #23617
+    def test_creating_wireless_link_records_interface_prechange(self):
+        interfaces = [
+            Interface.objects.create(device=self.device, name=name, type=InterfaceTypeChoices.TYPE_80211AC)
+            for name in ('radio0', 'radio1')
+        ]
+        request = RequestFactory().post('/')
+        request.id = uuid4()
+        request.user = self.user
+
+        with event_tracking(request):
+            wireless_link = WirelessLink.objects.create(
+                interface_a=interfaces[0],
+                interface_b=interfaces[1],
+                ssid='LINK1',
+            )
+
+        for interface in interfaces:
+            change = ObjectChange.objects.get(
+                changed_object_type=ContentType.objects.get_for_model(Interface),
+                changed_object_id=interface.pk,
+            )
+            self.assertIsNone(change.prechange_data['wireless_link'])
+            self.assertEqual(change.postchange_data['wireless_link'], wireless_link.pk)
+            self.assertFalse(hasattr(interface, '_prechange_snapshot'))
+
+    # Regression test for #23617
+    def test_creating_wireless_link_keeps_existing_interface_snapshot(self):
+        interfaces = [
+            Interface.objects.create(device=self.device, name=name, type=InterfaceTypeChoices.TYPE_80211AC)
+            for name in ('radio0', 'radio1')
+        ]
+        request = RequestFactory().post('/')
+        request.id = uuid4()
+        request.user = self.user
+
+        with event_tracking(request):
+            interfaces[0].snapshot()
+            interfaces[0].description = 'updated'
+            WirelessLink.objects.create(interface_a=interfaces[0], interface_b=interfaces[1], ssid='LINK1')
+
+        change = ObjectChange.objects.get(
+            changed_object_type=ContentType.objects.get_for_model(Interface),
+            changed_object_id=interfaces[0].pk,
+        )
+        self.assertEqual(change.prechange_data['description'], '')
+        self.assertEqual(change.postchange_data['description'], 'updated')
+
     def test_resaving_wireless_link_does_not_log_connected_interfaces(self):
     def test_resaving_wireless_link_does_not_log_connected_interfaces(self):
         interface_a = Interface.objects.create(
         interface_a = Interface.objects.create(
             device=self.device,
             device=self.device,

Vissa filer visades inte eftersom för många filer har ändrats