Ver Fonte

Merge branch 'main' into feature

Jeremy Stretch há 17 horas atrás
pai
commit
6bc41a8dce
100 ficheiros alterados com 3560 adições e 976 exclusões
  1. 8 1
      .github/PULL_REQUEST_TEMPLATE.md
  2. 4 0
      .github/VOUCHED.td
  3. 1 1
      .github/workflows/ci.yml
  4. 1 1
      .pre-commit-config.yaml
  5. 35 34
      AGENTS.md
  6. 5 3
      AI_POLICY.md
  7. 1 1
      CONTRIBUTING.md
  8. 3 1
      THREAT_MODEL.md
  9. 6 726
      contrib/openapi.json
  10. 298 0
      docs/best-practices/modeling-servers.md
  11. 14 1
      docs/configuration/miscellaneous.md
  12. 1 0
      docs/configuration/system.md
  13. 43 2
      docs/development/getting-started.md
  14. 4 4
      docs/development/git-cheat-sheet.md
  15. 30 0
      docs/integrations/graphql-api.md
  16. 1 1
      docs/models/dcim/moduletype.md
  17. 3 1
      docs/models/extras/webhook.md
  18. 5 0
      docs/reference/filtering.md
  19. 3 0
      docs/release-notes/version-4.6.md
  20. 47 0
      docs/release-notes/version-4.7.md
  21. 1 0
      mkdocs.yml
  22. 1 9
      netbox/account/views.py
  23. 1 1
      netbox/circuits/forms/filtersets.py
  24. 2 1
      netbox/circuits/tables/circuits.py
  25. 2 1
      netbox/circuits/tables/virtual_circuits.py
  26. 4 0
      netbox/circuits/tests/test_models.py
  27. 22 8
      netbox/circuits/tests/test_tables.py
  28. 1 1
      netbox/core/data_backends.py
  29. 6 1
      netbox/core/forms/filtersets.py
  30. 7 0
      netbox/core/management/commands/upgrade.py
  31. 1 1
      netbox/core/models/files.py
  32. 1 1
      netbox/core/models/jobs.py
  33. 1 1
      netbox/core/models/object_types.py
  34. 18 1
      netbox/core/signals.py
  35. 6 0
      netbox/core/tests/test_filtersets.py
  36. 3 2
      netbox/core/tests/test_management_commands.py
  37. 12 2
      netbox/core/tests/test_models.py
  38. 50 0
      netbox/core/tests/test_signals.py
  39. 16 0
      netbox/core/tests/test_views.py
  40. 1 1
      netbox/dcim/api/serializers_/devicetypes.py
  41. 1 1
      netbox/dcim/api/serializers_/racks.py
  42. 6 2
      netbox/dcim/filtersets.py
  43. 71 38
      netbox/dcim/forms/bulk_import.py
  44. 3 7
      netbox/dcim/graphql/filters.py
  45. 51 25
      netbox/dcim/models/cables.py
  46. 2 1
      netbox/dcim/models/device_component_templates.py
  47. 1 0
      netbox/dcim/models/devices.py
  48. 5 0
      netbox/dcim/signals.py
  49. 4 2
      netbox/dcim/tables/devices.py
  50. 4 2
      netbox/dcim/tables/devicetypes.py
  51. 1 1
      netbox/dcim/tests/query_counts.json
  52. 39 2
      netbox/dcim/tests/test_api.py
  53. 522 0
      netbox/dcim/tests/test_cablepaths.py
  54. 208 0
      netbox/dcim/tests/test_cablepaths2.py
  55. 19 1
      netbox/dcim/tests/test_filtersets.py
  56. 75 0
      netbox/dcim/tests/test_forms.py
  57. 191 0
      netbox/dcim/tests/test_models.py
  58. 245 1
      netbox/dcim/tests/test_tables.py
  59. 164 3
      netbox/dcim/tests/test_views.py
  60. 5 2
      netbox/dcim/utils.py
  61. 60 11
      netbox/dcim/views.py
  62. 1 1
      netbox/extras/dashboard/forms.py
  63. 4 2
      netbox/extras/dashboard/utils.py
  64. 1 1
      netbox/extras/forms/bulk_edit.py
  65. 5 1
      netbox/extras/forms/bulk_import.py
  66. 1 1
      netbox/extras/forms/model_forms.py
  67. 10 0
      netbox/extras/models/customfields.py
  68. 2 1
      netbox/extras/models/models.py
  69. 1 1
      netbox/extras/tables/columns.py
  70. 3 0
      netbox/extras/tables/tables.py
  71. 37 0
      netbox/extras/tests/test_customfields.py
  72. 4 0
      netbox/extras/tests/test_event_rules.py
  73. 2 0
      netbox/extras/tests/test_filtersets.py
  74. 72 2
      netbox/extras/tests/test_forms.py
  75. 2 0
      netbox/extras/tests/test_signals.py
  76. 10 2
      netbox/extras/tests/test_tables.py
  77. 4 2
      netbox/extras/views.py
  78. 1 1
      netbox/ipam/api/serializers_/services.py
  79. 4 8
      netbox/ipam/forms/bulk_import.py
  80. 7 0
      netbox/ipam/tests/test_filtersets.py
  81. 5 1
      netbox/netbox/api/authentication.py
  82. 1 1
      netbox/netbox/api/fields.py
  83. 24 21
      netbox/netbox/api/viewsets/__init__.py
  84. 1 4
      netbox/netbox/api/viewsets/mixins.py
  85. 1 0
      netbox/netbox/filtersets/__init__.py
  86. 2 1
      netbox/netbox/forms/mixins.py
  87. 209 0
      netbox/netbox/graphql/extensions.py
  88. 2 0
      netbox/netbox/graphql/schema.py
  89. 6 1
      netbox/netbox/graphql/views.py
  90. 31 7
      netbox/netbox/middleware.py
  91. 23 0
      netbox/netbox/models/features.py
  92. 4 3
      netbox/netbox/settings.py
  93. 11 0
      netbox/netbox/tables/columns.py
  94. 1 0
      netbox/netbox/tables/tables.py
  95. 1 1
      netbox/netbox/tests/dummy_plugin/navigation.py
  96. 51 2
      netbox/netbox/tests/test_api.py
  97. 12 0
      netbox/netbox/tests/test_authentication.py
  98. 45 1
      netbox/netbox/tests/test_forms.py
  99. 269 0
      netbox/netbox/tests/test_graphql.py
  100. 344 3
      netbox/netbox/tests/test_middleware.py

+ 8 - 1
.github/PULL_REQUEST_TEMPLATE.md

@@ -14,5 +14,12 @@
 ### Closes: #1234
 
 <!--
-    Please include a summary of the proposed changes below.
+    Briefly explain what this PR changes and the resulting behavior. One or
+    two short paragraphs are usually enough. Include only the context needed
+    to understand the change. Leave the full problem statement in the linked
+    issue.
+
+    Avoid repeating the issue, narrating the diff, or listing every test.
+    Include design decisions, compatibility notes, and meaningful validation
+    results where they help reviewers.
 -->

+ 4 - 0
.github/VOUCHED.td

@@ -19,6 +19,7 @@
 
 991jo
 9er-tom
+aaronaxvig
 abhirupmandal
 abrahamvegh
 abubnalitic-nbl
@@ -51,6 +52,7 @@ corencas
 corubba
 cory-kantar
 dansheps
+danshinde
 dfex
 dianbofa
 dkrasthi
@@ -69,6 +71,7 @@ guibi1
 haeki
 harryajc
 hblandford
+himanchalkaushale
 ianb-mp
 ifoughal
 ipb-devops
@@ -136,6 +139,7 @@ rodvand
 sebb0
 sensiblecoder
 sergiolpzgmz
+somiljain2006
 stalker-nn
 studioussagar
 stuntguy3000

+ 1 - 1
.github/workflows/ci.yml

@@ -85,7 +85,7 @@ jobs:
       - name: Check Python linting & PEP8 compliance
         uses: astral-sh/ruff-action@278981a28ce3188b1e39527901f38254bf3aac89  # v4.1.0
         with:
-          version: "0.17.4"
+          version: "0.17.6"
           args: "check --output-format=github"
           src: "netbox/"
 

+ 1 - 1
.pre-commit-config.yaml

@@ -1,6 +1,6 @@
 repos:
 - repo: https://github.com/astral-sh/ruff-pre-commit
-  rev: v0.17.4
+  rev: v0.17.6
   hooks:
     - id: ruff
       name: "Ruff linter"

+ 35 - 34
AGENTS.md

@@ -4,7 +4,7 @@
 
 NetBox is an extensible open-source network source-of-truth application powering network automation. It manages network infrastructure data including data center infrastructure (DCIM), IP address management (IPAM), circuits, virtualization, wireless, VPNs, and more. It supports a plugin ecosystem and exposes both a REST API and GraphQL API.
 
-NetBox is the core product maintained by NetBox Labs. The current version is 4.6 (Python 3.12+, Django 6.x).
+NetBox is the core product maintained by NetBox Labs. The current version is defined in `netbox/release.yaml`.
 
 ## Tech Stack
 
@@ -114,7 +114,7 @@ Use `register_model_view()` to register model views by action (e.g. "add", "list
 
 ### REST API
 
-DRF serializers live in `<app>/api/serializers.py`; viewsets in `<app>/api/views.py`; URLs auto-registered in `<app>/api/urls.py`. `NetBoxModelSerializer` provides standard fields including `url`, `display`, `tags`, and `custom_fields`. drf-spectacular generates the OpenAPI schema automatically. REST API views typically don't need to add `select_related()` or `prefetch_related()` — prefetching is handled dynamically by the serializer.
+DRF serializers live in `<app>/api/serializers.py`; viewsets in `<app>/api/views.py`; URLs auto-registered in `<app>/api/urls.py`. `NetBoxModelSerializer` provides standard fields including `url`, `display`, `tags`, and `custom_fields`. drf-spectacular generates the OpenAPI schema automatically. REST API views typically don't need to add `select_related()` or `prefetch_related()`. The base viewset resolves prefetches dynamically from the serializer's fields.
 
 ### GraphQL
 
@@ -162,8 +162,8 @@ source ~/.venv/netbox/bin/activate
 pip install -r requirements.txt
 
 # Copy and configure
-cp netbox/netbox/configuration.example.py netbox/netbox/configuration.py
-# Edit configuration.py: set DATABASE, REDIS, SECRET_KEY, ALLOWED_HOSTS
+cp netbox/netbox/configuration_example.py netbox/netbox/configuration.py
+# Edit configuration.py: set DATABASES, REDIS, SECRET_KEY, ALLOWED_HOSTS
 
 cd netbox/
 python manage.py migrate
@@ -202,15 +202,7 @@ Additional specialized test modules exist in some apps (e.g., `test_cablepaths.p
 
 ## CI/CD
 
-GitHub Actions workflows in `.github/workflows/`:
-
-- **`ci.yml`** — Main CI pipeline: runs on every PR. Executes linting (ruff) and the full test suite across the supported Python version matrix.
-- **`codeql.yml`** — CodeQL security scanning.
-- **`claude.yml`** — Claude Code automation hook; triggers on issue/PR comments mentioning `@claude`.
-- **`claude-issue-triage.yml`** — Automated issue triage via Claude AI.
-- **`close-stale-issues.yml`** / **`close-incomplete-issues.yml`** — Issue hygiene automation.
-- **`lock-threads.yml`** — Locks closed issue/PR threads after a period.
-- **`update-translation-strings.yml`** — Extracts and updates i18n translation strings.
+GitHub Actions workflows live in `.github/workflows/`. See `ci.yml` for its checks and the events and path filters that trigger them.
 
 ## Common Tasks
 
@@ -245,15 +237,12 @@ GitHub Actions workflows in `.github/workflows/`:
 
 ### Cut a release
 
-1. Bump `version` in `pyproject.toml`.
-2. Update `docs/release-notes/`.
-3. Tag and publish a GitHub release.
+The version is defined in `netbox/release.yaml`. Follow the [release checklist](docs/development/release-checklist.md), which is the authoritative process. The `prepare-release`, `draft-release-notes`, and `publish-release` skills in `.claude/skills/` automate most of the patch release process.
 
 ## Conventions and Patterns
 
 - **Apps**: Each app owns its models, views, serializers, filtersets, forms, and tests. Don't reach across app boundaries except via FK relations and public APIs.
-- **Views**: Use `register_model_view()`. List views don't need manual `select_related()`/`prefetch_related()` — the table handles it.
-- **REST API**: Serializers don't need manual `select_related()`/`prefetch_related()` — handled dynamically.
+- **REST API**: The base viewset resolves prefetches from the serializer's fields, so API views usually don't need manual `select_related()`/`prefetch_related()`. Declare `field_prefetches` on the viewset for relations it cannot infer, such as those read by method fields or model properties.
 - **New models**: Inherit from `NetBoxModel`; include `created` and `last_updated` fields.
 - **Every UI model**: Needs model, serializer, filterset, form, table, views, URL route, and tests.
 - **API serializers**: Must include a `url` field (absolute URL of the object).
@@ -263,7 +252,6 @@ GitHub Actions workflows in `.github/workflows/`:
 - **No manual migrations**: Prompt the user to run `manage.py makemigrations`.
 - **No `ruff format`** on existing files — tends to introduce unnecessary style changes.
 - **Linting**: Ruff config in `pyproject.toml`. Line length 120, single quotes. Enabled rules: E/W/F/I/RET/UP/RUF022. Ignored: F403, F405, RET504, UP032.
-- **Extras**: Cross-cutting features (custom fields, tags, webhooks, scripts) belong in the `extras` app.
 - **Plugin API**: Only documented public APIs are stable. Internal code may change without notice.
 
 ## AI Policy
@@ -272,7 +260,8 @@ All contributions must comply with the project's [AI policy](AI_POLICY.md). In s
 
 - AI tools may be used to explore the codebase and to generate code.
 - The contributor must fully understand, and be able to explain, every change submitted.
-- Issues, pull request descriptions, and comments must be written in the contributor's own voice. Anything you draft for these is a starting point for the contributor to review and rewrite: keep it brief and plain, and say so when handing it over.
+- Issues and comments must be written in the contributor's own voice. Anything you draft for these is a starting point for the contributor to review and rewrite: keep it brief and plain, and say so when handing it over.
+- Pull request descriptions may be AI-generated, as long as the contributor reviews them and they follow the [PR description guidance](#pr-descriptions).
 - Never open a GitHub issue on the contributor's behalf (e.g. via `gh issue create` or the API). The contributor must submit it themselves using one of the [issue forms](https://github.com/netbox-community/netbox/issues/new/choose); issues opened any other way are closed automatically.
 
 ## Branch & PR Conventions
@@ -282,6 +271,29 @@ All contributions must comply with the project's [AI policy](AI_POLICY.md). In s
 - Every PR must reference an approved GitHub issue.
 - PRs must include tests for new functionality.
 
+### PR Descriptions
+
+Follow [the PR template](.github/PULL_REQUEST_TEMPLATE.md). Summarize what changes and the resulting behavior, usually in one or two short paragraphs. Include only the context needed to understand the change, and leave the full problem statement in the linked issue. Avoid repeating the issue, narrating the diff, or listing every test. Include design decisions, compatibility notes, and meaningful validation results where they help reviewers.
+
+### Commit Messages and PR Titles
+
+For issue-linked changes, use the [commit message conventions](docs/development/getting-started.md#commit-messages-and-pr-titles). They follow the traditional [Git commit-message guidelines](https://cbea.ms/git-commit/) with NetBox's issue-prefixed subject format:
+
+- Use `Fixes #<issue-id>: <summary>` for bug fixes and `Closes #<issue-id>: <summary>` for all other issue types, such as features, housekeeping, and documentation. Use the same wording for the PR title and final commit subject.
+- Write the summary in the imperative, starting with a capital letter and without a trailing period. It should work as a release note entry. Aim for about 50 characters for the whole subject, including the issue prefix, while keeping the meaning clear.
+- When a body is needed, separate it from the subject with a blank line. Briefly explain what changes and why, rather than walking through the implementation. Wrap prose at 72 characters.
+- Omit a duplicate `Fixes` or `Closes` reference from the commit footer. Keep the required `Closes: #<issue-id>` line in the PR description.
+- When applicable, add a `Co-authored-by: Name <email>` trailer for each co-author, using their preferred attribution details. Separate the trailer block from the body with a blank line.
+
+For example:
+
+```text
+Fixes #1234: Keep cleared fields empty on refresh
+
+Refreshing an edit form restored the saved value of any field the user
+had cleared, discarding that edit. Cleared fields now stay empty.
+```
+
 ## PR Submission Requirements
 
 **Do not open a PR unless all the following conditions are met:**
@@ -308,23 +320,12 @@ Reject the PR submission and report the problem if the issue is closed, unassign
 
 Do not include an entry in the release notes for the PR unless explicitly instructed to do so. (Release notes are typically generated in aggregate as part of the release process to avoid merge conflicts.)
 
-## Troubleshooting
-
-- **Wrong directory for `manage.py`** — `manage.py` lives in `netbox/`, not the repo root. Always `cd netbox/` first or use the full path.
-- **Wrong configuration loaded** — Set `NETBOX_CONFIGURATION=netbox.configuration_testing` for tests.
-- **`configuration.py` not found** — Copy `configuration.example.py` to `configuration.py` and fill in DATABASE, REDIS, SECRET_KEY, ALLOWED_HOSTS. This file is gitignored and must never be committed.
-- **Migration errors** — Never write migrations manually. Run `python manage.py makemigrations` and let Django generate them.
-- **Plugin issues** — Only documented public APIs are stable. Internal NetBox code may change without notice.
-
 ## Gotchas
 
-- `configuration.py` is gitignored — never commit it.
-- `manage.py` lives in `netbox/`, NOT the repo root. Running from the wrong directory is a common mistake.
-- `NETBOX_CONFIGURATION` env var controls which settings module loads; set to `netbox.configuration_testing` for tests.
-- The `extras` app is a catch-all for cross-cutting features (custom fields, tags, webhooks, scripts).
-- Plugins API: only documented public APIs are stable. Internal NetBox code is subject to change without notice.
+- `manage.py` lives in `netbox/`, not the repo root. Run commands from `netbox/` or use the full path.
+- The `NETBOX_CONFIGURATION` environment variable selects the settings module. Set it to `netbox.configuration_testing` for tests.
+- `configuration.py` is gitignored and must never be committed. To create it, copy `configuration_example.py` and fill in `DATABASES`, `REDIS`, `SECRET_KEY`, and `ALLOWED_HOSTS`.
 - `netbox/templates/rest_framework/api.html`, `netbox/templates/drf_spectacular/swagger_ui.html` and `netbox/templates/drf_spectacular/redoc.html` copy upstream script blocks to add CSP nonces. Re-sync them whenever djangorestframework or drf-spectacular is upgraded.
-- See `docs/development/` for the full contributing guide and code style details.
 
 ## References
 

+ 5 - 3
AI_POLICY.md

@@ -4,9 +4,10 @@ This project **welcomes the thoughtful use of AI tools** when contributing, yet
 
 ## Never let an LLM speak for you
 
-When maintainers read a comment, an issue, or a pull request from you, they want to know they are hearing your words. Grammar and spelling do not matter. What matters is real connection.
+When maintainers read a comment or an issue from you, they want to know they are hearing your words. Grammar and spelling do not matter. What matters is real connection.
 
-- All comments, issues, and pull request descriptions should be written in your own voice
+- All comments and issues should be written in your own voice
+- Pull request descriptions may be AI-generated, as long as you review them and they follow our [description guidelines](docs/development/getting-started.md#pull-request-descriptions)
 - We value clear, human communication over perfect grammar or spelling
 - Avoid copy-pasting AI-generated summaries that don't reflect your own understanding
 
@@ -27,7 +28,8 @@ Our aim is ensuring quality and maintaining the joy of collaborating and communi
 ## Summary
 
 - AI may be used to generate code or explore ideas
-- Comments, issues, and pull request descriptions must be written in your own voice
+- Comments and issues must be written in your own voice
+- AI-generated pull request descriptions must be reviewed by the contributor
 - Contributions must be fully understood and explainable by the contributor
 - Contribution guidelines must still be followed
 

+ 1 - 1
CONTRIBUTING.md

@@ -38,7 +38,7 @@ NetBox users are welcome to participate in either role, on stage or in the crowd
 > We do not currently accept issues submitted via GitHub's API: All issues must be submitted using one of the [provided templates](https://github.com/netbox-community/netbox/issues/new/choose). In addition to ensuring high-quality submissions, these templates automatically assign issue types and labels for categorization to help expedite triage. This does not happen when issues are submitted via the API.
 
 > [!IMPORTANT]
-> Every issue submitted to this repository is afforded consideration by a human reviewer. Please review our [AI policy](AI_POLICY.md) before contributing: While AI tools may be used to help write code, all issues, pull request descriptions, and comments must be written in your own words. Issues which appear to be completely authored by an AI may be rejected without further discussion.
+> Every issue submitted to this repository is afforded consideration by a human reviewer. Please review our [AI policy](AI_POLICY.md) before contributing: While AI tools may be used to help write code, all issues and comments must be written in your own words. Issues which appear to be completely authored by an AI may be rejected without further discussion.
 
 ## :bug: Reporting Bugs
 

+ 3 - 1
THREAT_MODEL.md

@@ -32,6 +32,7 @@ The central question when evaluating any NetBox security report is: **does the a
 | PostgreSQL database, Redis | **Trusted** | Assumed reachable only by the application. |
 | Infrastructure operators | **Trusted** | Shell/filesystem/DB access implies total control by design. |
 | Superusers (`is_superuser`) | **Trusted** | An active superuser bypasses all object-level permission checks. This is intentional. |
+| Users permitted to manage users (`users.add_user` or `users.change_user`) | **Trusted** | Can assign groups, object permissions, and superuser status to users, including themselves. Equivalent to a superuser by design. |
 | Users permitted to author code-bearing objects | **Trusted** | Holders of permissions to create/modify custom scripts, export templates, config templates, custom links, or webhooks (see below). |
 | Authenticated users **without** those permissions | **Untrusted** | Subject to full object-based permission enforcement. |
 | Unauthenticated / network-adjacent parties | **Untrusted** | Outside the supported deployment model entirely. |
@@ -96,6 +97,7 @@ The following are **not** treated as NetBox vulnerabilities. Most describe a pri
 | --- | --- |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
 | A permitted user runs code via a custom script, Jinja template, custom link, or webhook | Not a vulnerability | These features exist to execute user-authored logic; the required permission is trusted, operator-tier by design.                                                                                               |
 | A superuser modifies the database, reads secrets, or creates another superuser | Not a vulnerability | Superusers and infrastructure operators are trusted by design.                                                                                                                                                  |
+| A user permitted to add or change users grants themselves (or another user) superuser status or additional permissions | Not a vulnerability | User management permissions are administrative by design.                                                                                                                                                       |
 | A template author reads NetBox data they are otherwise permitted to view | Not a vulnerability | Template rendering with objects in scope is the purpose of the feature; the sandbox, not permission scoping, is the boundary.                                                                                   |
 | Missing login/request rate limiting | Out of scope | A deployment-layer concern, handled by the reverse proxy rather than the application.                                                                                                                           |
 | Client IP spoofing via `X-Forwarded-For` and similar headers | Out of scope | NetBox trusts the headers the reverse proxy sets; trustworthy client IP is a proxy responsibility ([`HTTP_CLIENT_IP_HEADERS`](https://netboxlabs.com/docs/netbox/configuration/system/#http_client_ip_headers)). |
@@ -112,7 +114,7 @@ The following are **not** treated as NetBox vulnerabilities. Most describe a pri
 | **R**epudiation | Changes are recorded via the changelog and journaling; event rules can emit notifications. |
 | **I**nformation disclosure | Object-based view permissions filter every queryset. Cross-boundary disclosure (e.g. API/GraphQL filter injection) is in scope; data legitimately visible to a template author is not. |
 | **D**enial of service | Request rate limiting and resource controls are a deployment/reverse-proxy responsibility, not the application's. |
-| **E**levation of privilege | The superuser flag is all-or-nothing and trusted. Any *unintended* escalation across the permission system (constraint bypass, action bypass) is in scope. |
+| **E**levation of privilege | The superuser flag is all-or-nothing and trusted, as are user management permissions. Any *unintended* escalation across the permission system (constraint bypass, action bypass) is in scope. |
 
 ## Triage & Severity
 

+ 6 - 726
contrib/openapi.json

@@ -2,7 +2,7 @@
     "openapi": "3.0.3",
     "info": {
         "title": "NetBox REST API",
-        "version": "4.7.5",
+        "version": "4.7.6",
         "license": {
             "name": "Apache v2 License"
         }
@@ -160594,66 +160594,6 @@
                         "explode": true,
                         "style": "form"
                     },
-                    {
-                        "in": "query",
-                        "name": "object_type__ic",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__ie",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__iew",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__iregex",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__isw",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
                     {
                         "in": "query",
                         "name": "object_type__n",
@@ -160666,66 +160606,6 @@
                         "explode": true,
                         "style": "form"
                     },
-                    {
-                        "in": "query",
-                        "name": "object_type__nic",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__nie",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__niew",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__nisw",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__regex",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
                     {
                         "in": "query",
                         "name": "object_type_id",
@@ -163621,66 +163501,6 @@
                         "explode": true,
                         "style": "form"
                     },
-                    {
-                        "in": "query",
-                        "name": "object_type__ic",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__ie",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__iew",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__iregex",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__isw",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
                     {
                         "in": "query",
                         "name": "object_type__n",
@@ -163693,66 +163513,6 @@
                         "explode": true,
                         "style": "form"
                     },
-                    {
-                        "in": "query",
-                        "name": "object_type__nic",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__nie",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__niew",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__nisw",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__regex",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
                     {
                         "in": "query",
                         "name": "object_type_id",
@@ -165627,66 +165387,6 @@
                         "explode": true,
                         "style": "form"
                     },
-                    {
-                        "in": "query",
-                        "name": "object_type__ic",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__ie",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__iew",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__iregex",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__isw",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
                     {
                         "in": "query",
                         "name": "object_type__n",
@@ -165699,66 +165399,6 @@
                         "explode": true,
                         "style": "form"
                     },
-                    {
-                        "in": "query",
-                        "name": "object_type__nic",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__nie",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__niew",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__nisw",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__regex",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
                     {
                         "in": "query",
                         "name": "object_type_id",
@@ -167779,66 +167419,6 @@
                         "explode": true,
                         "style": "form"
                     },
-                    {
-                        "in": "query",
-                        "name": "object_type__ic",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__ie",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__iew",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__iregex",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__isw",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
                     {
                         "in": "query",
                         "name": "object_type__n",
@@ -167851,66 +167431,6 @@
                         "explode": true,
                         "style": "form"
                     },
-                    {
-                        "in": "query",
-                        "name": "object_type__nic",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__nie",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__niew",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__nisw",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__regex",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
                     {
                         "in": "query",
                         "name": "object_type_id",
@@ -173311,66 +172831,6 @@
                         "explode": true,
                         "style": "form"
                     },
-                    {
-                        "in": "query",
-                        "name": "object_type__ic",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__ie",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__iew",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__iregex",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__isw",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
                     {
                         "in": "query",
                         "name": "object_type__n",
@@ -173383,66 +172843,6 @@
                         "explode": true,
                         "style": "form"
                     },
-                    {
-                        "in": "query",
-                        "name": "object_type__nic",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__nie",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__niew",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__nisw",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__regex",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
                     {
                         "in": "query",
                         "name": "object_type_id",
@@ -228213,66 +227613,6 @@
                         "explode": true,
                         "style": "form"
                     },
-                    {
-                        "in": "query",
-                        "name": "object_type__ic",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__ie",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__iew",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__iregex",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__isw",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
                     {
                         "in": "query",
                         "name": "object_type__n",
@@ -228285,66 +227625,6 @@
                         "explode": true,
                         "style": "form"
                     },
-                    {
-                        "in": "query",
-                        "name": "object_type__nic",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__nie",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__niew",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__nisw",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
-                    {
-                        "in": "query",
-                        "name": "object_type__regex",
-                        "schema": {
-                            "type": "array",
-                            "items": {
-                                "type": "string"
-                            }
-                        },
-                        "explode": true,
-                        "style": "form"
-                    },
                     {
                         "in": "query",
                         "name": "object_type_id",
@@ -292100,7 +291380,7 @@
                     "ca_file_path": {
                         "type": "string",
                         "nullable": true,
-                        "description": "The specific CA certificate file to use for SSL verification. Leave blank to use the system defaults.",
+                        "description": "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.",
                         "maxLength": 4096
                     },
                     "timeout": {
@@ -333978,7 +333258,7 @@
                     "ca_file_path": {
                         "type": "string",
                         "nullable": true,
-                        "description": "The specific CA certificate file to use for SSL verification. Leave blank to use the system defaults.",
+                        "description": "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.",
                         "maxLength": 4096
                     },
                     "timeout": {
@@ -337901,7 +337181,7 @@
                     "ca_file_path": {
                         "type": "string",
                         "nullable": true,
-                        "description": "The specific CA certificate file to use for SSL verification. Leave blank to use the system defaults.",
+                        "description": "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.",
                         "maxLength": 4096
                     },
                     "timeout": {
@@ -361918,7 +361198,7 @@
                     "ca_file_path": {
                         "type": "string",
                         "nullable": true,
-                        "description": "The specific CA certificate file to use for SSL verification. Leave blank to use the system defaults.",
+                        "description": "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.",
                         "maxLength": 4096
                     },
                     "timeout": {
@@ -362028,7 +361308,7 @@
                     "ca_file_path": {
                         "type": "string",
                         "nullable": true,
-                        "description": "The specific CA certificate file to use for SSL verification. Leave blank to use the system defaults.",
+                        "description": "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.",
                         "maxLength": 4096
                     },
                     "timeout": {

+ 298 - 0
docs/best-practices/modeling-servers.md

@@ -0,0 +1,298 @@
+# Modeling Servers
+
+## Use Case
+
+A physical server is a chassis that holds field-replaceable components: processors, memory modules, drives, expansion cards, and power supplies. Two servers of the same model often ship with very different configurations, and their components get replaced, upgraded, and moved between servers over the life of the hardware.
+
+These components were historically recorded as inventory items, which have been deprecated since NetBox v4.3. Existing inventory items continue to function, and NetBox does not convert them to modules automatically. Once a component has been recorded as a module, delete its inventory item so that it isn't recorded twice. This guide captures the recommended strategy for modeling servers and their components on NetBox v4.7 and later.
+
+## Modeling Strategy
+
+Each server is represented as a [device](../models/dcim/device.md), and each field-replaceable component is represented as a [module](../models/dcim/module.md) installed within a [module bay](../models/dcim/modulebay.md) on that device. A [module type profile](../models/dcim/moduletypeprofile.md) assigned to each [module type](../models/dcim/moduletype.md) records the attributes relevant to its kind of component, such as the size and class of a memory module or the capacity of a drive.
+
+A module does not need to deliver any components to the device. A memory module or a CPU is a module with no interfaces or other components. A network adapter, by contrast, delivers its interfaces to the device when installed, and a power supply delivers its power port.
+
+```mermaid
+flowchart BT
+    cpu1[CPU] --> socket1[Socket CPU1]
+    dimm1[32GB DDR5 RDIMM] --> slot1[DIMM A1]
+    disk1[3.84TB NVMe SSD] --> bay1[Drive Bay Drive0]
+    interface1[Interface Slot1-port1] & interface2[Interface Slot1-port2] --> nic1[Network Adapter]
+    nic1 --> pcie1[PCIe Slot Slot1]
+    powerport1[Power Port] --> psu1[Power Supply]
+    psu1 --> psubay1[PSU Bay PSU1]
+    socket1 & slot1 & bay1 & pcie1 & psubay1 --> device[Device]
+```
+
+### Before You Start
+
+List every slot and replaceable part in the chassis, using the vendor's technical documentation and the labels printed on the chassis. Then check the community [Device Type Library](https://github.com/netbox-community/devicetype-library): it publishes ready-made definitions for many device types and module types, including their module bays, which can be imported into NetBox rather than built by hand.
+
+### Choosing What to Model
+
+If a chassis holds complete servers, each with its own processors, memory, and operating system (such as a blade enclosure, or a multi-node chassis holding four servers in 2U), model each server as a child device installed in a [device bay](../models/dcim/devicebay.md) on the chassis, not as a module. Set the chassis device type's parent/child status to **Parent** and give it a device bay for each node. Set each node's device type to **Child**, with a height of 0U, and model it as described in this guide. Install a node from the chassis's **Device Bays** tab. Components shared by all the nodes, such as power supplies and fans, belong to the chassis.
+
+Model the components you replace, upgrade, track by serial number, or need to find later. A part that is never serviced on its own, such as a fixed chassis fan, can be left out. Hardware built into the chassis, such as onboard network ports or the management controller's port, belongs on the device type as ordinary component templates rather than as modules.
+
+A module's type can carry module bays of its own, so that other modules are installed within it rather than directly in a bay on the device. This is called nesting: a GPU installed in a bay on a GPU tray, which is in turn installed in a bay on the chassis, is a nested module. Nest modules only where an assembly that holds other components is itself replaced or tracked as a unit, such as a GPU tray. Nest only as deep as you track: if a tray simply carries a baseboard that holds the GPUs, and the tray is not tracked on its own, model the baseboard alone, installed directly in the chassis. A riser or cage that is never tracked on its own can be left out: model its slots as module bays on the device type. Conversely, when a chassis is sold with different drive backplanes, modeling the backplane as a module that holds the drive bays lets a single device type cover every configuration.
+
+When a component physically blocks a neighboring bay, such as a double-wide GPU covering the adjacent PCIe slot, disable the blocked module bay (clear its **Enabled** setting) so that nothing can be installed in it. Disabling a bay does not remove a module already installed in it.
+
+### 1. Select Module Type Profiles
+
+NetBox includes default module type profiles for the most common server components:
+
+| Profile        | Attributes                                                   |
+|----------------|--------------------------------------------------------------|
+| CPU            | Architecture, cores, speed (GHz)                             |
+| Memory         | Class (DDR3, DDR4, DDR5), size (GB), data rate (MT/s), ECC   |
+| Hard disk      | Type (HD, SSD, NVME), size (GB), speed (RPM)                 |
+| GPU            | GPU, interface (PCIe generation and width), memory (GB)      |
+| Expansion card | Connector type, bandwidth                                    |
+| Power supply   | Current type (AC, DC), voltage, wattage, hot-swappable       |
+| Fan            | RPM                                                          |
+
+These profiles are created when NetBox's database is first set up, or when it is upgraded to v4.3. Profiles added in later releases are not created on existing installations: for example, an installation that reached v4.3 before v4.3.4 has no Expansion card profile. If any of these profiles are not present, or if you need a different set of attributes, create your own profiles instead. Attributes are defined by editing a profile's [JSON schema](https://json-schema.org/) (the [module type profile documentation](../models/dcim/moduletypeprofile.md) includes an example schema), and can be added or changed at a later point. A profile does not need a schema at all: for parts such as RAID controllers or host bus adapters, a profile with no schema can serve purely to classify module types. Assigning a profile to a module type is optional, but recommended: attribute values are validated against the profile's schema, and module types can be filtered by them. If a schema defines default values (the default Memory, Hard disk and Power supply profiles do), the module type form fills them in, so review them before saving.
+
+### 2. Create Module Bay Types
+
+Create a [module bay type](../models/dcim/modulebaytype.md) for each kind of slot found in your servers, such as `LGA4677 Socket`, `DDR5 DIMM Slot`, `U.2 Drive Bay`, `PCIe x16 Slot`, and `PSU Bay`. When both a module bay and a module type declare bay types, NetBox will permit a module to be installed in the bay only if they share at least one type. This prevents, for example, a memory module from being installed in a drive bay. Bay types exist only to restrict which module types fit where, so create as few as you need: a single `PCIe Slot` type may be enough, or you might split it by slot width if cards must be checked against their slots.
+
+Assign bay types to module types and module bays before installing modules, so that compatibility is checked as each module is installed.
+
+!!! note
+    Module bay types are optional. Skip this step if you do not need NetBox to enforce compatibility.
+
+### 3. Create a Module Type for Each Component Model
+
+Next, create a module type to represent each unique component model in your servers (creating its manufacturer first, if needed). Each module type should define a manufacturer and a unique model name, assign the appropriate profile, and fill in the profile's attributes. Bulk import identifies module types by model alone, so avoid reusing a model name under two manufacturers. Whether you put the vendor's orderable part number in the model name or in the separate part number field, do it consistently. If you created bay types in the previous step, assign each module type the bay type(s) it fits. For example:
+
+| Manufacturer | Model                | Profile        | Attributes                   | Bay Type        |
+|--------------|----------------------|----------------|------------------------------|-----------------|
+| Intel        | Xeon Gold 6430       | CPU            | x86_64, 32 cores, 2.1 GHz    | LGA4677 Socket  |
+| Samsung      | M321R4GA3BB6-CQK     | Memory         | DDR5, 32 GB, 4800 MT/s, ECC  | DDR5 DIMM Slot  |
+| Micron       | 7450 PRO 3.84TB U.3  | Hard disk      | NVME, 3840 GB                | U.2 Drive Bay   |
+| NVIDIA       | MCX623106AN-CDAT     | Expansion card | PCIe x16                     | PCIe x16 Slot   |
+
+Other add-in hardware follows the same pattern: a GPU, for example, takes the GPU profile and a PCIe bay type. Profile attributes are defined on the module type, so every module of the same type shares them. Values that vary per unit, such as a serial number or asset tag, belong on the module itself.
+
+### 4. Add Components to Module Types (Where Applicable)
+
+Most server components deliver nothing to the device, so their module types need no component templates (the interfaces, power ports, and other components a module creates when installed). Add them only where the component exposes something you want to track:
+
+* **Network adapters** need an interface template for each port. Use the `{module}` token in each name so that adapters in different slots produce unique interface names: the token is replaced with the position of the module bay the adapter is installed in. For example, interface templates named `{module}-port1` and `{module}-port2` on an adapter installed in the bay with position `Slot1` become `Slot1-port1` and `Slot1-port2`.
+* **Power supplies** need a power port template, which allows each supply to be cabled to a power outlet or feed.
+* **Assemblies that hold other components**, such as a drive cage or a GPU baseboard, need module bay templates. If the same assembly can be installed in more than one bay, use the `{module}` token in these templates' names and positions as well. For example, a drive cage with module bay templates named `{module}-Bay1` through `{module}-Bay8` (added at once as `{module}-Bay[1-8]`), installed in the bay with position `Box1`, creates bays named `Box1-Bay1` through `Box1-Bay8`, so every bay name on the device stays unique. Such assemblies usually need no profile, or a profile with no schema that only classifies them.
+* **Network adapters with pluggable cages** can carry their own module bays. Transceivers installed in them follow the approach described in [Modeling Pluggable Transceivers](./modeling-pluggable-transceivers.md).
+
+### 5. Create Device Types
+
+If you haven't already, create a [device type](../models/dcim/devicetype.md) to represent each server model in your environment. Create one device type per chassis model, not one per configuration. A server's configuration is expressed through the modules installed in it.
+
+!!! note
+    Skip this step if you've already created the necessary device types.
+
+### 6. Add Module Bays to the Device Type
+
+Add a module bay template to the device type for every slot in the chassis, and assign each one or more bay types. The form for adding module bay templates accepts alphanumeric ranges for names and positions (e.g. `A[1-16]`), so a row of identical slots can be added at once. For example, a two-socket server might have:
+
+| Bays              | Count | Names and Positions          | Bay Type        |
+|-------------------|-------|------------------------------|-----------------|
+| CPU sockets       | 2     | `CPU1`, `CPU2`               | LGA4677 Socket  |
+| DIMM slots        | 32    | `A1` to `A16`, `B1` to `B16` | DDR5 DIMM Slot  |
+| Drive bays        | 24    | `Drive0` to `Drive23`        | U.2 Drive Bay   |
+| PCIe slots        | 4     | `Slot1` to `Slot4`           | PCIe x16 Slot   |
+| Power supply bays | 2     | `PSU1`, `PSU2`               | PSU Bay         |
+
+Be sure to define both the name **and position** of each module bay with a value that is unique across the entire device, including bays nested within other modules. Bulk import finds a module bay by its name within the device, and the position determines the names of the components a module creates. If a module type's templates use the `{module}` token, NetBox will not install the module in a bay that has no position. This example uses the same value for each bay's name and position. (A chassis sold with interchangeable drive backplanes would carry its drive bays on a backplane module instead, as described under [Choosing What to Model](#choosing-what-to-model).) Matching the labels printed on the chassis keeps the names in NetBox consistent with what a technician sees on site.
+
+### 7. Create a Device
+
+Create a new device using the device type added in the previous step. The module bays defined on the device type, along with their bay types, will be instantiated on the new device automatically.
+
+!!! note
+    Module bay templates are instantiated only when a device is created. If you've already created the necessary devices in NetBox, you'll need to add their module bays manually. You can add multiple module bays at once by selecting the desired devices from the device list and selecting **Add Components > Module Bays** at the bottom of the page. Give both the name and the position a range of the same length (e.g. `Drive[0-23]` for each), or every new bay will receive the same position. Bay types are not assigned by this form: select the new bays from the module bay list and use bulk edit to add them.
+
+### 8. Install the Modules
+
+Finally, record each component by installing a new module of the appropriate type in each occupied module bay, and assign each module its serial number and asset tag. Bays left without a module appear empty on the device's **Module Bays** tab, which shows the server's unused capacity.
+
+A fully populated server can contain dozens of modules. When adding many at once, you may find it helpful to use NetBox's bulk import functionality to create them from CSV, JSON, or YAML data. Each row identifies its device by name, its module bay by name within that device, and its module type by model, so these must be unambiguous. For example:
+
+```no-highlight
+device,module_bay,module_type,status,serial
+server01,A1,M321R4GA3BB6-CQK,active,S0A1B2C3
+server01,A2,M321R4GA3BB6-CQK,active,S0A1B2C4
+server01,Drive0,7450 PRO 3.84TB U.3,active,MC5D6E7F
+```
+
+Once installed, modules can be filtered by profile (e.g. all memory modules) and by serial number. Module types can be filtered by profile attribute, using the attribute's key from the profile's schema (e.g. `?profile=Memory&attr_class=DDR4`).
+
+## Moving and Removing Components
+
+An installed module can be moved to another module bay, including a bay on a different device, along with its serial number, asset tag, and change history. Moving a module also moves any modules installed within it, and deleting a module deletes them. A module must always be installed in a module bay, so a component removed from service must be either deleted or moved elsewhere. See the [module documentation](../models/dcim/module.md) for the conditions under which a module can be moved between devices.
+
+## Example: Commodity Server (Dell PowerEdge R760)
+
+The PowerEdge R760 is a 2U two-socket server, documented in Dell's [Installation and Service Manual](https://www.dell.com/support/manuals/en-us/oth-r760/per760_ism_pub/). Nearly all of its slots (CPU sockets, DIMM slots, PCIe slots, and power supply and fan bays) are defined as module bays on the device type, and each component is installed directly in one of them. The exceptions are the front drive backplane, the optional rear drive module, and the boot module: each is a module that carries module bays of its own, and the drives and the front PERC are installed in those. The component models shown in this and the following example are examples. Substitute the parts actually installed in your servers.
+
+```mermaid
+flowchart BT
+    drive[24x U.2 Drive] & perc[Front PERC] --> bp[Front Backplane]
+    reardrive[Rear Drives] --> rear[Rear Drive Module]
+    m2[2x M.2 SSD] --> boss[BOSS-N1]
+    cpu[2x CPU, 32x DIMM] & cards[PCIe, OCP, and LOM Cards] & power[2x PSU, 6x Fan] --> device[PowerEdge R760]
+    bp & rear & boss --> device
+```
+
+### Device Type
+
+| Bays                | Count | Names and Positions          | Bay Type        |
+|---------------------|-------|------------------------------|-----------------|
+| CPU sockets         | 2     | `CPU1`, `CPU2`               | LGA4677 Socket  |
+| DIMM slots          | 32    | `A1` to `A16`, `B1` to `B16` | DDR5 DIMM Slot  |
+| PCIe slots          | 8     | `Slot1` to `Slot8`           | PCIe Slot       |
+| OCP NIC slot        | 1     | `OCP`                        | OCP NIC 3.0     |
+| LOM card slot       | 1     | `LOM`                        | Dell LOM Slot   |
+| Front backplane     | 1     | `BACKPLANE`                  | Dell Backplane  |
+| Rear drive module   | 1     | `REAR-BACKPLANE`             | Dell Rear Drive Module |
+| Boot module         | 1     | `BOSS`                       | Dell BOSS Slot  |
+| Power supply bays   | 2     | `PSU1`, `PSU2`               | PSU Bay         |
+| Fans                | 6     | `FAN1` to `FAN6`             | Dell Fan Bay    |
+
+The CPU, DIMM, PCIe slot, and power supply names follow Dell's labels. The fan names are our own (Dell labels the fan connectors `FAN_2U1` to `FAN_2U6`).
+
+The dedicated iDRAC management port is part of the chassis, so it belongs on the device type as an interface template (named `iDRAC` and marked as management only) rather than in a module bay.
+
+### Risers and PCIe Slots
+
+The R760's eight PCIe slots are carried on four replaceable risers, and the width of each slot (and whether it exists at all) depends on the risers installed. This example leaves the risers out and gives every slot a single `PCIe Slot` bay type. If you need NetBox to check that a card fits its slot, create a bay type for each slot width instead. If you track risers individually, model each as a module with its slots as nested bays, as in the [Grand Teton example](#example-nested-modules-meta-grand-teton).
+
+Double-wide GPUs are supported only on risers that carry a single slot, so in those configurations slot 1 or slot 8 does not exist. Disable the module bay for the missing slot (clear its **Enabled** setting) so that nothing can be installed in it.
+
+### Drive Backplanes
+
+The R760 is offered with several front drive configurations, such as 8, 16, or 24 2.5" bays, or 12 3.5" bays. Rather than creating a device type for each configuration, model the backplane as a module whose module type carries the drive bays. A single device type then covers servers with different backplanes: the backplane installed in each server determines which drive bays it has. Each backplane's drive bays take a bay type matching its drives, such as `U.2 Drive Bay` for the NVMe backplane below, or separate types for 2.5" SAS/SATA and 3.5" backplanes. The optional rear drive module is modeled the same way, with its own drive bay names (e.g. `Rear0` to `Rear3`) so that every bay name on the device stays unique, and its bay is left empty on servers without one. The rear drive module takes the place of riser 3, so on servers that have one, disable the module bays for slots 4 and 5.
+
+Deleting a backplane module also deletes the drive modules installed in it. To record a like-for-like backplane replacement, update the existing module's serial number rather than deleting it.
+
+The front PERC storage controller plugs into the drive backplane, so the backplane's module type also carries a `PERC` module bay for it. (An adapter PERC, by contrast, installs in a PCIe slot like any other card.)
+
+### Module Types
+
+| Manufacturer | Model                              | Profile        | Bay Type       | Component Templates                    |
+|--------------|------------------------------------|----------------|----------------|----------------------------------------|
+| Dell         | 24 x 2.5" NVMe Gen5 Switched Backplane | (none)     | Dell Backplane | Module bays `Drive0` to `Drive23`, `PERC` |
+| Micron       | 7450 PRO 3.84TB U.3                | Hard disk      | U.2 Drive Bay  | None                                   |
+| Dell         | Broadcom 5720 Dual Port 1GbE LOM   | Expansion card | Dell LOM Slot  | Interfaces `{module}-1`, `{module}-2`  |
+| Dell         | BOSS-N1                            | (none)         | Dell BOSS Slot | Module bays `M.2-1`, `M.2-2`           |
+| Dell         | BOSS-N1 M.2 NVMe SSD               | Hard disk      | M.2 Slot       | None                                   |
+| Dell         | 1400W Platinum PSU                 | Power supply   | PSU Bay        | Power port `{module}`                  |
+| Dell         | HPR Gold Fan                       | Fan            | Dell Fan Bay   | None                                   |
+
+The backplane's drive bays (names and positions `Drive0` to `Drive23`) take the `U.2 Drive Bay` bay type. The BOSS-N1 boot module holds two M.2 drives, each replaceable on its own, in bays with names and positions `M.2-1` and `M.2-2` and bay type `M.2 Slot`. The LOM card installed in bay `LOM` creates interfaces named `LOM-1` and `LOM-2`, and the power supply in bay `PSU1` creates a power port named `PSU1`.
+
+### Installing the Modules
+
+The drive bays exist only once the backplane has been installed, and the M.2 bays only once the boot module has, so install those first. With bulk import, list them ahead of the modules installed in them, or import in two passes as shown here:
+
+```no-highlight
+device,module_bay,module_type,status,serial
+r760-01,BACKPLANE,"24 x 2.5"" NVMe Gen5 Switched Backplane",active,BP00001
+r760-01,BOSS,BOSS-N1,active,BOSS00001
+r760-01,LOM,Broadcom 5720 Dual Port 1GbE LOM,active,LOM00001
+r760-01,PSU1,1400W Platinum PSU,active,PSU00001
+r760-01,PSU2,1400W Platinum PSU,active,PSU00002
+```
+
+```no-highlight
+device,module_bay,module_type,status,serial
+r760-01,Drive0,7450 PRO 3.84TB U.3,active,DRV00001
+r760-01,Drive1,7450 PRO 3.84TB U.3,active,DRV00002
+r760-01,M.2-1,BOSS-N1 M.2 NVMe SSD,active,M2-00001
+```
+
+The backplane's model name contains a double quote, so it is quoted in the CSV and the quote inside it is doubled.
+
+### Replacing a Failed Drive
+
+When a drive reports a fault, search for its serial number (in the global search, or by filtering the modules list on serial) to find the server and the bay it is installed in. Set the module's status to **Failed** until the drive has been swapped. Once the replacement is in, edit the module, enter the new drive's serial number, and set its status back to **Active**. The module's change log keeps the failed drive's serial number.
+
+If you track failed parts in NetBox until they are returned to the vendor, install the replacement as a new module instead, and move the failed one to a module bay on a device that holds parts awaiting return.
+
+## Example: Nested Modules (Meta Grand Teton)
+
+Some servers group their components into trays or baseboards that are themselves replaced as a unit. These can be modeled with nested modules: each tray is a module installed in the chassis, and each component is a module installed in a tray.
+
+[Grand Teton](https://www.opencompute.org/documents/grand-teton-platform-specification-v1-0-pdf/) is an AI training platform published through the Open Compute Project (Grand Teton Platform Specification v1.0). Its chassis holds three trays: a CPU tray, a switch tray, and an accelerator tray built on the [HGX baseboard](https://www.opencompute.org/documents/open-compute-specification-hgx-baseboard-contribution-r1-v0-1-pdf), which carries eight GPUs. Any server with a removable GPU tray or baseboard can be modeled the same way.
+
+```mermaid
+flowchart BT
+    gpu[8x GPU] --> at[Accelerator Tray]
+    nic[8x OCP NIC] & e1s[16x E1.S Drive] --> sw[Switch Tray]
+    cpu[2x CPU] & dimm[32x DIMM] & boot[2x Boot Drive] & cpunic[2x OCP NIC] --> ct[CPU Tray]
+    at & sw & ct --> device[Grand Teton]
+```
+
+### Device Type
+
+The Grand Teton device type has a module bay for each tray:
+
+| Name and Position | Bay Type       |
+|-------------------|----------------|
+| `GPU-TRAY`        | GT Tray Slot   |
+| `SWITCH-TRAY`     | GT Tray Slot   |
+| `CPU-TRAY`        | GT Tray Slot   |
+
+### Tray Module Types
+
+Each tray is a module type with its own module bay templates, and each takes the `GT Tray Slot` bay type so that it fits the chassis bays. When a tray is installed in the chassis, its bays (and their bay types) are created on the device automatically. Bay names are unique across all three trays, as described in [step 6](#6-add-module-bays-to-the-device-type).
+
+| Module Type         | Bay Names and Positions  | Bay Type        |
+|---------------------|--------------------------|-----------------|
+| GT Accelerator Tray | `GPU1` to `GPU8`         | SXM5 Socket     |
+| GT Switch Tray      | `NIC1` to `NIC8`         | OCP NIC 3.0     |
+|                     | `E1S0` to `E1S15`        | E1.S Bay        |
+| GT CPU Tray         | `CPU1`, `CPU2`           | LGA4677 Socket  |
+|                     | `DIMM1` to `DIMM32`      | DDR5 DIMM Slot  |
+|                     | `BOOT0`, `BOOT1`         | E1.S Bay        |
+|                     | `CPU-NIC0`, `CPU-NIC1`   | OCP NIC 3.0     |
+
+This example models only the components a technician installs into a tray. The CPU tray's boot drives may be either E1.S or M.2 devices. E1.S is shown here.
+
+### Component Module Types
+
+| Manufacturer | Model                | Profile        | Attributes                   | Bay Type        | Component Templates     |
+|--------------|----------------------|----------------|------------------------------|-----------------|-------------------------|
+| NVIDIA       | H100 SXM5 80GB       | GPU            | 80 GB memory                 | SXM5 Socket     | None                    |
+| NVIDIA       | ConnectX-7 400G OCP  | Expansion card | OCP NIC 3.0                  | OCP NIC 3.0     | Interface `{module}-p1` |
+| Intel        | Xeon Platinum 8480+  | CPU            | x86_64, 56 cores, 2.0 GHz    | LGA4677 Socket  | None                    |
+| Samsung      | 64GB DDR5-4800 RDIMM | Memory         | DDR5, 64 GB, 4800 MT/s, ECC  | DDR5 DIMM Slot  | None                    |
+| Micron       | 7450 PRO 3.84TB E1.S | Hard disk      | NVME, 3840 GB                | E1.S Bay        | None                    |
+
+The default GPU profile's interface attribute lists only PCIe options, so it is left blank for SXM GPUs. A NIC installed in bay `NIC3` creates an interface named `NIC3-p1`, and one installed in `CPU-NIC0` creates `CPU-NIC0-p1`.
+
+### Installing the Modules
+
+A tray's bays exist only once the tray has been installed, so install the trays first. With bulk import, list the trays ahead of their components, or import them separately as shown here:
+
+```no-highlight
+device,module_bay,module_type,status,serial
+gt01,GPU-TRAY,GT Accelerator Tray,active,AT00001
+gt01,SWITCH-TRAY,GT Switch Tray,active,SW00001
+gt01,CPU-TRAY,GT CPU Tray,active,CT00001
+```
+
+```no-highlight
+device,module_bay,module_type,status,serial
+gt01,GPU1,H100 SXM5 80GB,active,GPU00001
+gt01,NIC1,ConnectX-7 400G OCP,active,NIC00001
+gt01,E1S0,7450 PRO 3.84TB E1.S,active,DRV00001
+gt01,DIMM1,64GB DDR5-4800 RDIMM,active,DIMM00001
+```
+
+### Moving a Tray
+
+When a chassis fails, its accelerator tray can be moved to a spare chassis as a unit. Edit the tray's module and select the spare device and its `GPU-TRAY` bay, which must be enabled and empty. The eight GPUs installed in the tray move with it, keeping their serial numbers and change history.
+
+A tray can be moved to another device only while none of its components carry connections or device-specific configuration. The switch tray's NIC interfaces, for example, block the move while they are cabled or have IP addresses assigned. The [module documentation](../models/dcim/module.md) lists every condition.

+ 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`
 
-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.api.views.*` - Views which handle business logic for the REST API
 * `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.reports.*` - Report execution (`module.name`)
 * `netbox.scripts.*` - Custom script execution (`module.name`)

+ 43 - 2
docs/development/getting-started.md

@@ -211,16 +211,57 @@ Only the value `1` enables this mode. Unlike `UPDATE_QUERY_COUNTS` mode, it work
 !!! note "Vouched contributors"
     Pull requests are accepted only from contributors who have been vouched for by a maintainer. If you aren't yet listed in [`.github/VOUCHED.td`](https://github.com/netbox-community/netbox/blob/main/.github/VOUCHED.td) (for example, if you're contributing for the first time), introduce yourself by [starting a discussion](https://github.com/netbox-community/netbox/discussions/new?category=vouch-request) in the **Vouch Request** category before submitting your first pull request. Pull requests from contributors who have not been vouched for are closed automatically. See the [contributing guide](https://github.com/netbox-community/netbox/blob/main/CONTRIBUTING.md) for details.
 
-Once you're happy with your work and have verified that all tests pass, commit your changes and push it upstream to your fork. Always provide descriptive (but not excessively verbose) commit messages. Be sure to prefix your commit message with the word "Fixes" or "Closes" and the relevant issue number (with a hash mark). This tells GitHub to automatically close the referenced issue once the commit has been merged.
+Once you're happy with your work and have verified that all tests pass, commit your changes using the [format below](#commit-messages-and-pr-titles) and push them upstream to your fork.
 
 ```no-highlight
 git commit -m "Closes #1234: Add IPv5 support"
 git push origin
 ```
 
-Once your fork has the new commit, submit a [pull request](https://github.com/netbox-community/netbox/compare) to the NetBox repo to propose the changes. Be sure to provide a detailed accounting of the changes being made and the reasons for doing so.
+Once your fork has the new commit, submit a [pull request](https://github.com/netbox-community/netbox/compare) to the NetBox repo to propose the changes. Follow the title and description guidance below.
 
 Once submitted, a maintainer will review your pull request and either merge it or request changes. If changes are needed, you can make them via new commits to your fork: The pull request will update automatically.
 
 !!! warning
     Remember, pull requests are permitted only for **accepted** issues. If an issue you want to work on hasn't been approved by a maintainer yet, it's best to avoid risking your time and effort on a change that might not be accepted. (The one exception to this is trivial changes to the documentation or other non-critical resources.)
+
+### Commit Messages and PR Titles
+
+For issue-linked changes, use one of these subject formats:
+
+* `Fixes #<issue-id>: <summary>` for bug fixes.
+* `Closes #<issue-id>: <summary>` for all other issue types, such as features, housekeeping, and documentation.
+
+GitHub closes the referenced issue automatically once the commit is merged into the default branch.
+
+Use the same wording for the PR title and final commit subject. Write the summary in the imperative (e.g. "Keep cleared fields empty on refresh"), starting with a capital letter and without a trailing period. It should describe the change clearly enough to serve as a release note entry. Aim for about 50 characters for the whole subject, including the issue prefix, while keeping the meaning clear.
+
+When a body is needed, separate it from the subject with a blank line. Briefly explain what changes and why, rather than walking through the implementation, and wrap prose at 72 characters. For example:
+
+```no-highlight
+Fixes #1234: Keep cleared fields empty on refresh
+
+Refreshing an edit form restored the saved value of any field the user
+had cleared, discarding that edit. Cleared fields now stay empty.
+```
+
+The issue reference in the subject is sufficient, so omit a duplicate `Fixes` or `Closes` reference from the commit footer. When applicable, add a `Co-authored-by: Name <email>` trailer for each co-author, using their preferred attribution details. Separate the trailer block from the body with a blank line.
+
+These conventions follow the traditional [Git commit-message guidelines](https://cbea.ms/git-commit/) with NetBox's issue-prefixed subject format.
+
+### Pull Request Descriptions
+
+Use the [PR template](https://github.com/netbox-community/netbox/blob/main/.github/PULL_REQUEST_TEMPLATE.md), including its `Closes: #<issue-id>` line even when the issue is referenced in the title.
+
+Briefly explain what the PR changes and the resulting behavior, usually in one or two short paragraphs. Include only the context needed to understand the change, and leave the full problem statement in the linked issue. Avoid repeating the issue, narrating the diff, or listing every test. Include design decisions, compatibility notes, and meaningful validation results where they help reviewers.
+
+For example:
+
+```markdown
+### Closes: #1234
+
+Keeps cleared fields empty when an edit form refreshes, so saved values
+are no longer restored.
+```
+
+Read through the description before submitting and check that it accurately describes your changes.

+ 4 - 4
docs/development/git-cheat-sheet.md

@@ -208,18 +208,18 @@ index 000000000..e69de29bb
 The `git commit` command records your changes to the current branch. Specify a commit message with the `-m` argument. (If omitted, a file editor will be opened to provide a message.
 
 ``` title="Command"
-git commit -m "Fixes #123: Fixed the thing that was broken"
+git commit -m "Fixes #123: Validate device names"
 ```
 
 ``` title="Example"
-$ git commit -m "Fixes #123: Fixed the thing that was broken"
-[123-fix-foo 9a12b5b5f] Fixes #123: Fixed the thing that was broken
+$ git commit -m "Fixes #123: Validate device names"
+[123-fix-foo 9a12b5b5f] Fixes #123: Validate device names
  2 files changed, 5 insertions(+)
  create mode 100644 foo.py
 ```
 
 !!! tip "Automatically Closing Issues"
-    GitHub will [automatically close](https://github.blog/2013-01-22-closing-issues-via-commit-messages/) any issues referenced in a commit message by `Fixes:` or `Closes:` when the commit is merged into the repository's default branch. Contributors are strongly encouraged to follow this convention when forming commit messages. (Use "Closes" for feature requests and "Fixes" for bugs.)
+    GitHub will [automatically close](https://github.blog/2013-01-22-closing-issues-via-commit-messages/) any issues referenced in a commit message by `Fixes` or `Closes` when the commit is merged into the repository's default branch. See the [commit message conventions](getting-started.md#commit-messages-and-pr-titles) for NetBox's subject format and examples.
 
 ### Push a Commit Upstream
 

+ 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.
 
+## 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
 
 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.

+ 1 - 1
docs/models/dcim/moduletype.md

@@ -95,7 +95,7 @@ The assigned [profile](./moduletypeprofile.md) for the type of module. Profiles
 
 Zero or more [module bay types](./modulebaytype.md) that this module type is compatible with. When at least one bay type is set, the module type may only be installed into bays that share a common type. Leave empty to allow installation into any bay.
 
-Bay types are included, by name, in a module type's exported YAML definition, but are not currently importable back through it; re-importing an exported definition leaves this field unset.
+Bay types are exported and imported by name. On import, a bay type belonging to the module type's manufacturer takes precedence over a global bay type with the same name; a name matching only another manufacturer's bay type is rejected.
 
 ### Attributes
 

+ 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
 
-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
 

+ 5 - 0
docs/reference/filtering.md

@@ -107,6 +107,11 @@ Here is an example of a lookup expression on a string field that will return all
 GET /api/dcim/devices/?name__ic=switch
 ```
 
+!!! note "Filtering for null values"
+    The value `null` always matches a NULL value, regardless of the lookup expression. For
+    example, `name__ic=null` returns devices with no name, not devices whose name contains the
+    string "null".
+
 !!! note "Case-insensitive matching depends on the field's collation"
     Most `name` fields use a database collation which sorts them in natural order, so that
     `device-2` precedes `device-10`. Case-insensitive matching on those fields follows the

+ 3 - 0
docs/release-notes/version-4.6.md

@@ -63,6 +63,9 @@
 
 ## v4.6.8 (2026-08-11)
 
+!!! warning "Custom Script REST API Changes"
+    Custom scripts can no longer be created, modified, or deleted directly via the `/api/extras/scripts/` endpoint: `POST` requests to `/api/extras/scripts/` and `PUT`, `PATCH`, and `DELETE` requests to `/api/extras/scripts/{id}/` now return a 405 response. Scripts are managed through their modules instead; upload a new module to `/api/extras/scripts/upload/` or replace an existing one at `/api/extras/scripts/upload/{id}/`, and NetBox will add or remove scripts to match the classes it defines. Running a script via a `POST` request to `/api/extras/scripts/{id}/` is unaffected. See [#22745](https://github.com/netbox-community/netbox/issues/22745) for details.
+
 ### Performance Improvements
 
 * [#22787](https://github.com/netbox-community/netbox/issues/22787) - Avoid N+1 queries when resolving generic relations (e.g. assigned objects) via the GraphQL API

+ 47 - 0
docs/release-notes/version-4.7.md

@@ -1,5 +1,52 @@
 # NetBox v4.7
 
+## v4.7.6 (2026-11-24)
+
+!!! note "Retracing Split Cable Paths"
+    The fixes for [#21960](https://github.com/netbox-community/netbox/issues/21960) and [#23490](https://github.com/netbox-community/netbox/issues/23490) don't update cable paths which have already been recorded: these remain marked as split until one of their cables is saved again. To retrace them, run `manage.py trace_paths --force` after upgrading. On large installations, you can instead delete only the split paths in `nbshell` (`CablePath.objects.filter(is_split=True).delete()`), then run `manage.py trace_paths`.
+
+### Enhancements
+
+* [#23531](https://github.com/netbox-community/netbox/issues/23531) - Preserve the `color`, `length`, and `length_unit` values when cloning a cable or using "Create & Add Another"
+* [#23656](https://github.com/netbox-community/netbox/issues/23656) - Add the `netbox.graphql.query` logger, which logs each GraphQL API operation (including the user, client IP, operation name, query, duration, and error count) at the INFO level
+* [#23757](https://github.com/netbox-community/netbox/issues/23757) - Add an object ID field to the change log filter form, to find the changes recorded for a specific object (including deleted objects)
+
+### Performance Improvements
+
+* [#23349](https://github.com/netbox-community/netbox/issues/23349) - Batch the loading of related objects for the contact assignment, circuit group assignment, and port mapping table columns, rather than querying them for each row
+* [#23721](https://github.com/netbox-community/netbox/issues/23721) - Avoid a slow query when filtering devices by whether they have interfaces (`interfaces`), which could time out on installations with many devices that have none
+
+### Bug Fixes
+
+* [#21960](https://github.com/netbox-community/netbox/issues/21960) - Fix cable tracing from a multi-position front port whose rear ports converge on the same remote endpoint, which was reported as a split path with no `connected_endpoints`
+* [#23199](https://github.com/netbox-community/netbox/issues/23199) - Require permission to change a device (in addition to the virtual chassis) when adding it as a member of a virtual chassis
+* [#23398](https://github.com/netbox-community/netbox/issues/23398) - Restrict the dependent objects listed when an object can't be deleted (in the UI and in REST API 409 responses) to those the user is permitted to view
+* [#23471](https://github.com/netbox-community/netbox/issues/23471) - Avoid reporting a 404 error to Sentry for requests redirected to add a missing trailing slash
+* [#23490](https://github.com/netbox-community/netbox/issues/23490) - Fix cable tracing through a partially connected profiled cable (e.g. a `1C4P:4C1P` breakout with fewer than four legs connected), which was reported as a split path with no endpoints
+* [#23493](https://github.com/netbox-community/netbox/issues/23493) - Fix exception when creating a device whose device type has an inventory item template assigned to a component template named with `{vc_position}`
+* [#23552](https://github.com/netbox-community/netbox/issues/23552) - Prevent database writes while `MAINTENANCE_MODE` is enabled, which previously permitted them on most paths
+* [#23583](https://github.com/netbox-community/netbox/issues/23583) - Prevent the object delete view from redirecting to an external site via a protocol-relative `return_url` (e.g. `//example.com`)
+* [#23603](https://github.com/netbox-community/netbox/issues/23603) - Prevent cleared multiple-selection fields (e.g. tags) from being restored when an edit form refreshes
+* [#23608](https://github.com/netbox-community/netbox/issues/23608) - Fix the editing of tags and other objects whose color is a custom value rather than one of the predefined colors
+* [#23617](https://github.com/netbox-community/netbox/issues/23617) - Record pre-change data in the change log for objects updated as a side effect of other changes, such as cables, wireless link interfaces, primary MAC addresses, synced templates, and child devices
+* [#23632](https://github.com/netbox-community/netbox/issues/23632) - Fix `ValueError` exception when passing `null` to a substring or regex lookup filter (e.g. `name__ic=null`)
+* [#23635](https://github.com/netbox-community/netbox/issues/23635) - Reject a custom field `related_object_filter` with nested values, which could be saved but raised an exception on list and edit views
+* [#23637](https://github.com/netbox-community/netbox/issues/23637) - Support the `module_bay_types` field when importing module types
+* [#23652](https://github.com/netbox-community/netbox/issues/23652) - Include event types registered by plugins in the event rule add, edit, bulk edit, and import forms
+* [#23665](https://github.com/netbox-community/netbox/issues/23665) - Fix `AttributeError` exception when the login form is submitted without a `username` field
+* [#23691](https://github.com/netbox-community/netbox/issues/23691) - Fix negated (`__n`) object type filters (e.g. `changed_object_type__n`) returning matching objects instead of excluding them, and remove the text lookups (e.g. `object_type__ic`), which had no effect, from many-to-many object type filters
+* [#23696](https://github.com/netbox-community/netbox/issues/23696) - Rebuild the config context cache when running `netbox upgrade`
+* [#23702](https://github.com/netbox-community/netbox/issues/23702) - Translate the "Owner" and "Owner group" form field labels, and other labels which always rendered in English
+* [#23711](https://github.com/netbox-community/netbox/issues/23711) - Restore the action to add an IP address on the IP addresses panel of the interface view
+* [#23746](https://github.com/netbox-community/netbox/issues/23746) - Prevent closed toast messages from reappearing when a table is paginated or otherwise refreshed
+* [#23747](https://github.com/netbox-community/netbox/issues/23747) - Fix exception when creating a device whose device type has a child interface template named with `{vc_position}`
+* [#23751](https://github.com/netbox-community/netbox/issues/23751) - Translate the Markdown hint shown under comments fields
+* [#23752](https://github.com/netbox-community/netbox/issues/23752) - Translate the "Changelog message" field label on object edit forms
+* [#23753](https://github.com/netbox-community/netbox/issues/23753) - Translate the "Created by" column header in journal entry tables
+* [#23758](https://github.com/netbox-community/netbox/issues/23758) - Fix filtering device types by `front_image` and `rear_image` via GraphQL
+
+---
+
 ## v4.7.5 (2026-11-10)
 
 ### Enhancements

+ 1 - 0
mkdocs.yml

@@ -130,6 +130,7 @@ nav:
         - Custom Scripts: 'customization/custom-scripts.md'
     - Best Practices:
         - Modeling Pluggable Transceivers: 'best-practices/modeling-pluggable-transceivers.md'
+        - Modeling Servers: 'best-practices/modeling-servers.md'
         - Performance Handbook: 'best-practices/performance-handbook.md'
     - Integrations:
         - REST API: 'integrations/rest-api.md'

+ 1 - 9
netbox/account/views.py

@@ -9,8 +9,6 @@ from django.contrib.auth import update_session_auth_hash
 from django.contrib.auth.decorators import login_not_required
 from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm
 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.shortcuts import get_object_or_404, redirect, render, resolve_url
 from django.urls import reverse, reverse_lazy
@@ -119,12 +117,6 @@ class LoginView(View):
         if form.is_valid():
             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
             auth_login(request, form.get_user())
             logger.info(f"User {request.user} successfully authenticated")
@@ -149,7 +141,7 @@ class LoginView(View):
 
             return response
 
-        username = form['username'].value()
+        username = form['username'].value() or ''
         logger.debug(f"Login form validation failed for username: {remove_linebreaks(username)}")
 
         return render(request, self.template_name, {

+ 1 - 1
netbox/circuits/forms/filtersets.py

@@ -1,5 +1,5 @@
 from django import forms
-from django.utils.translation import gettext as _
+from django.utils.translation import gettext_lazy as _
 
 from circuits.choices import (
     CircuitCommitRateChoices,

+ 2 - 1
netbox/circuits/tables/circuits.py

@@ -84,7 +84,8 @@ class CircuitTable(TenancyColumnsMixin, ContactsColumnMixin, PrimaryModelTable):
     assignments = columns.ManyToManyColumn(
         accessor='group_assignments',
         verbose_name=_('Assignments'),
-        linkify_item=True
+        linkify_item=True,
+        prefetch_related=('group_assignments__group',)
     )
 
     class Meta(PrimaryModelTable.Meta):

+ 2 - 1
netbox/circuits/tables/virtual_circuits.py

@@ -69,7 +69,8 @@ class VirtualCircuitTable(TenancyColumnsMixin, ContactsColumnMixin, PrimaryModel
     assignments = columns.ManyToManyColumn(
         accessor='group_assignments',
         verbose_name=_('Assignments'),
-        linkify_item=True
+        linkify_item=True,
+        prefetch_related=('group_assignments__group',)
     )
 
     class Meta(PrimaryModelTable.Meta):

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

@@ -418,6 +418,7 @@ class CircuitTerminationChangeLoggingTestCase(TestCase):
         ObjectChange.objects.all().delete()
 
         def _move():
+            termination.snapshot()
             termination.circuit = self.circuits[1]
             termination.save()
 
@@ -443,6 +444,7 @@ class CircuitTerminationChangeLoggingTestCase(TestCase):
         ObjectChange.objects.all().delete()
 
         def _flip():
+            termination.snapshot()
             termination.term_side = 'Z'
             termination.save()
 
@@ -489,6 +491,7 @@ class CircuitTerminationChangeLoggingTestCase(TestCase):
         ))
         ObjectChange.objects.all().delete()
 
+        termination.snapshot()
         self._tracked(termination.save)
 
         self.assertFalse(self._circuit_changes(self.circuits[0]).exists())
@@ -502,6 +505,7 @@ class CircuitTerminationChangeLoggingTestCase(TestCase):
         ObjectChange.objects.all().delete()
 
         def _move():
+            termination.snapshot()
             termination.circuit = self.circuits[1]
             termination.save(update_fields=('circuit',))
 

+ 22 - 8
netbox/circuits/tests/test_tables.py

@@ -50,12 +50,15 @@ class CircuitTableTestCase(TableTestCases.StandardTableTestCase):
 
     @tag('regression')  # Ref: #23342
     def test_assignments_column(self):
-        """The assignments column links the group assignments of each circuit."""
+        """The assignments column links the group assignments of each circuit without further queries."""
         url1, url2, url3 = (assignment.get_absolute_url() for assignment in self.assignments)
         self.user.config.set('tables.CircuitTable.columns', ['cid', 'assignments'], commit=True)
         table = CircuitTable(Circuit.objects.all())
         table.configure(self.get_request())
-        cells = {row.record.cid: row.get_cell('assignments') for row in table.rows}
+        rows = list(table.rows)
+
+        with self.assertNumQueries(0):
+            cells = {row.record.cid: row.get_cell('assignments') for row in rows}
 
         self.assertHTMLEqual(
             cells['Circuit 1'],
@@ -66,12 +69,15 @@ class CircuitTableTestCase(TableTestCases.StandardTableTestCase):
 
     @tag('regression')  # Ref: #23342
     def test_assignments_export(self):
-        """An export lists the group assignments of each circuit."""
+        """An export lists the group assignments of each circuit without further queries."""
         table = CircuitTable(Circuit.objects.all())
         table.configure(self.get_request())
         # An "All Data" export prefetches for every column, hidden or not
         table._apply_prefetching(columns=table.columns.names())
-        values = {row.record.cid: row.get_cell_value('assignments') for row in table.rows}
+        rows = list(table.rows)
+
+        with self.assertNumQueries(0):
+            values = {row.record.cid: row.get_cell_value('assignments') for row in rows}
 
         self.assertEqual(values, {
             'Circuit 1': 'Circuit Group 1 (Primary), Circuit Group 2',
@@ -140,13 +146,17 @@ class VirtualCircuitTableTestCase(TableTestCases.StandardTableTestCase):
         )
         CircuitGroupAssignment.objects.bulk_create(cls.assignments)
 
+    @tag('regression')  # Ref: #23349
     def test_assignments_column(self):
-        """The assignments column links the group assignments of each virtual circuit."""
+        """The assignments column links the group assignments of each virtual circuit without further queries."""
         url1, url2, url3 = (assignment.get_absolute_url() for assignment in self.assignments)
         self.user.config.set('tables.VirtualCircuitTable.columns', ['cid', 'assignments'], commit=True)
         table = VirtualCircuitTable(VirtualCircuit.objects.all())
         table.configure(self.get_request())
-        cells = {row.record.cid: row.get_cell('assignments') for row in table.rows}
+        rows = list(table.rows)
+
+        with self.assertNumQueries(0):
+            cells = {row.record.cid: row.get_cell('assignments') for row in rows}
 
         self.assertHTMLEqual(
             cells['Virtual Circuit 1'],
@@ -155,13 +165,17 @@ class VirtualCircuitTableTestCase(TableTestCases.StandardTableTestCase):
         self.assertHTMLEqual(cells['Virtual Circuit 2'], f'<a href="{url3}">Circuit Group 1 (Secondary)</a>')
         self.assertEqual(cells['Virtual Circuit 3'], table.columns['assignments'].default)
 
+    @tag('regression')  # Ref: #23349
     def test_assignments_export(self):
-        """An export lists the group assignments of each virtual circuit."""
+        """An export lists the group assignments of each virtual circuit without further queries."""
         table = VirtualCircuitTable(VirtualCircuit.objects.all())
         table.configure(self.get_request())
         # An "All Data" export prefetches for every column, hidden or not
         table._apply_prefetching(columns=table.columns.names())
-        values = {row.record.cid: row.get_cell_value('assignments') for row in table.rows}
+        rows = list(table.rows)
+
+        with self.assertNumQueries(0):
+            values = {row.record.cid: row.get_cell_value('assignments') for row in rows}
 
         self.assertEqual(values, {
             'Virtual Circuit 1': 'Circuit Group 1 (Primary), Circuit Group 2',

+ 1 - 1
netbox/core/data_backends.py

@@ -7,7 +7,7 @@ from urllib.parse import urlparse
 
 from django import forms
 from django.core.exceptions import ImproperlyConfigured
-from django.utils.translation import gettext as _
+from django.utils.translation import gettext_lazy as _
 
 from netbox.data_backends import DataBackend, register_data_backend
 from utilities.constants import HTTP_PROXY_SUPPORTED_SCHEMAS, HTTP_PROXY_SUPPORTED_SOCK_SCHEMAS

+ 6 - 1
netbox/core/forms/filtersets.py

@@ -12,6 +12,7 @@ from utilities.forms.fields import (
     ContentTypeChoiceField,
     ContentTypeMultipleChoiceField,
     DynamicModelMultipleChoiceField,
+    PositiveBigIntegerField,
     TagFilterField,
 )
 from utilities.forms.rendering import FieldSet
@@ -163,7 +164,7 @@ class ObjectChangeFilterForm(SavedFiltersMixin, FilterForm):
     fieldsets = (
         FieldSet('q', 'filter_id'),
         FieldSet('time_before', 'time_after', name=_('Time')),
-        FieldSet('action', 'user_id', 'changed_object_type_id', name=_('Attributes')),
+        FieldSet('action', 'user_id', 'changed_object_type_id', 'changed_object_id', name=_('Attributes')),
     )
     time_after = forms.DateTimeField(
         required=False,
@@ -190,6 +191,10 @@ class ObjectChangeFilterForm(SavedFiltersMixin, FilterForm):
         required=False,
         label=_('Object Type'),
     )
+    changed_object_id = PositiveBigIntegerField(
+        label=_('Object ID'),
+        required=False,
+    )
 
 
 class ConfigRevisionFilterForm(SavedFiltersMixin, FilterForm):

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

@@ -60,6 +60,13 @@ class Command(BaseCommand):
             out.write("Checking for missing cable paths...")
             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)
         if options['readonly'] and options['build_docs']:
             out.write("Skipping documentation build.")

+ 1 - 1
netbox/core/models/files.py

@@ -6,7 +6,7 @@ from django.conf import settings
 from django.core.exceptions import ValidationError
 from django.core.files.storage import storages
 from django.db import models
-from django.utils.translation import gettext as _
+from django.utils.translation import gettext_lazy as _
 
 from extras.storage import ScriptFileSystemStorage
 from netbox.models.features import SyncedDataMixin

+ 1 - 1
netbox/core/models/jobs.py

@@ -13,7 +13,7 @@ from django.core.validators import MinValueValidator
 from django.db import models, router, transaction
 from django.urls import reverse
 from django.utils import timezone
-from django.utils.translation import gettext as _
+from django.utils.translation import gettext_lazy as _
 from rq.exceptions import InvalidJobOperation
 
 from core.choices import JobAccessChoices, JobNotificationChoices, JobStatusChoices

+ 1 - 1
netbox/core/models/object_types.py

@@ -7,7 +7,7 @@ from django.contrib.postgres.indexes import GinIndex
 from django.core.exceptions import ObjectDoesNotExist
 from django.db import connection, models
 from django.db.models import Q
-from django.utils.translation import gettext as _
+from django.utils.translation import gettext_lazy as _
 
 from netbox.context import query_cache
 from netbox.plugins import PluginConfig

+ 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.models import CASCADE, RESTRICT
 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.utils.translation import gettext_lazy as _
 from django.utils.translation import ngettext
@@ -90,6 +90,19 @@ def update_object_types(sender, **kwargs):
 _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))
 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)
     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
     if event_type == OBJECT_CREATED:
         model_inserts.labels(instance._meta.model_name).inc()

+ 6 - 0
netbox/core/tests/test_filtersets.py

@@ -255,6 +255,12 @@ class ObjectChangeTestCase(TestCase, BaseFilterSetTestMixin):
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 3)
         params = {'changed_object_type_id': [ContentType.objects.get_by_natural_key('dcim', 'site').pk]}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 3)
+        params = {'changed_object_type__n': ['dcim.site']}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 3)
+        params = {'changed_object_type__n': ['dcim.site', 'ipam.ipaddress']}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 0)
+        params = {'changed_object_type__n': ['dcim.no-such-value']}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 6)
 
 
 class JobTestCase(TestCase, BaseFilterSetTestMixin):

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

@@ -334,7 +334,7 @@ class UpgradeCommandTest(TestCase):
     def test_full_sequence_order(self):
         seq, _, sub, _ = self._run()
         self.assertEqual(seq, [
-            'migrate', 'trace_paths',
+            'migrate', 'trace_paths', 'rebuild_config_context_cache',
             'collectstatic', 'remove_stale_contenttypes', 'reindex', 'clearsessions',
         ])
         sub.assert_not_called()  # docs not built by default
@@ -346,6 +346,7 @@ class UpgradeCommandTest(TestCase):
         sub.assert_not_called()
         self.assertIn('Skipping database migrations.', 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 stale content type removal.', 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)
         self.assertEqual(
             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):

+ 12 - 2
netbox/core/tests/test_models.py

@@ -11,10 +11,12 @@ from django.contrib.contenttypes.models import ContentType
 from django.core.exceptions import ObjectDoesNotExist
 from django.core.management import call_command
 from django.db import IntegrityError, connection
-from django.test import TestCase, override_settings
+from django.test import TestCase, override_settings, tag
 from django.test.utils import CaptureQueriesContext
 from django.urls import reverse
-from django.utils import timezone
+from django.utils import timezone, translation
+from django.utils.functional import Promise
+from django.utils.translation import gettext
 
 from core.choices import (
     DataSourceStatusChoices,
@@ -680,6 +682,14 @@ class JobTestCase(TestCase):
         job = Job(pk=123, name='Test Job', object_type=ObjectType.objects.get_for_model(Script), object_id=1)
         self.assertEqual(job.get_absolute_url(), reverse('extras:script_result', kwargs={'job_pk': 123}))
 
+    @tag('regression')  # Ref: #23702
+    def test_verbose_name_translation(self):
+        # Meta labels are set at import, so eager gettext keeps them in DEFAULT_LANGUAGE (#23702)
+        verbose_name = Job._meta.verbose_name
+        self.assertIsInstance(verbose_name, Promise)
+        with translation.override('nl'):
+            self.assertEqual(str(verbose_name), gettext('job'))
+
 
 class JobAccessTestCase(TestCase):
     """

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

@@ -78,6 +78,7 @@ class HandleChangedObjectSignalTestCase(TestCase):
         request = _build_request(self.user)
 
         with event_tracking(request):
+            site.snapshot()
             site.description = 'updated'
             site.save()
 
@@ -87,6 +88,55 @@ class HandleChangedObjectSignalTestCase(TestCase):
         ).order_by('-pk')
         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):
         # Saving outside a request context (no event_tracking) should not record any
         # ObjectChange entries.

+ 16 - 0
netbox/core/tests/test_views.py

@@ -365,6 +365,22 @@ class ObjectChangeTestCase(TestCase):
         response = self.client.get('{}?{}'.format(url, urllib.parse.urlencode(params)))
         self.assertHttpStatus(response, 200)
 
+    def test_objectchange_list_filter_by_object_id(self):
+        """Filter the change log by the ID of a deleted object."""
+        site = Site.objects.get(slug='site-1')
+        site_pk = site.pk
+        site.delete()
+        url = reverse('core:objectchange_list')
+
+        response = self.client.get(url, {'changed_object_id': site_pk})
+        self.assertHttpStatus(response, 200)
+        self.assertContains(response, f'Object ID: {site_pk}')
+        self.assertEqual(len(response.context['table'].rows), 3)
+
+        response = self.client.get(url, {'changed_object_id': site_pk + 1})
+        self.assertHttpStatus(response, 200)
+        self.assertEqual(len(response.context['table'].rows), 0)
+
     def test_objectchange(self):
 
         objectchange = ObjectChange.objects.first()

+ 1 - 1
netbox/dcim/api/serializers_/devicetypes.py

@@ -1,6 +1,6 @@
 import decimal
 
-from django.utils.translation import gettext as _
+from django.utils.translation import gettext_lazy as _
 from rest_framework import serializers
 
 from dcim.choices import *

+ 1 - 1
netbox/dcim/api/serializers_/racks.py

@@ -1,4 +1,4 @@
-from django.utils.translation import gettext as _
+from django.utils.translation import gettext_lazy as _
 from drf_spectacular.types import OpenApiTypes
 from drf_spectacular.utils import extend_schema_field
 from rest_framework import serializers

+ 6 - 2
netbox/dcim/filtersets.py

@@ -1,7 +1,7 @@
 import django_filters
 import netaddr
 from django.contrib.contenttypes.models import ContentType
-from django.db.models import Func, IntegerField, Q
+from django.db.models import Exists, Func, IntegerField, OuterRef, Q
 from django.utils.translation import gettext as _
 from drf_spectacular.types import OpenApiTypes
 from drf_spectacular.utils import extend_schema_field
@@ -1701,7 +1701,11 @@ class DeviceFilterSet(
         return queryset.exclude(poweroutlets__isnull=value)
 
     def _interfaces(self, queryset, name, value):
-        return queryset.exclude(interfaces__isnull=value)
+        # Query Interface directly. Excluding on interfaces__isnull self-joins Device, which
+        # PostgreSQL can plan very poorly when most devices have no interfaces (#23721).
+        # False uses ~Exists too: a pk__in subquery would negate to NOT IN, which PostgreSQL can't run as an anti join.
+        has_interfaces = Exists(Interface.objects.filter(device=OuterRef('pk')))
+        return queryset.filter(has_interfaces if value else ~has_interfaces)
 
     def _pass_through_ports(self, queryset, name, value):
         return queryset.exclude(

+ 71 - 38
netbox/dcim/forms/bulk_import.py

@@ -198,7 +198,7 @@ class LocationImportForm(NestedGroupModelImportForm):
 
         if data:
             # Limit location queryset by assigned site
-            params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
+            params = self.get_related_filter('site', 'site', data.get('site'))
             self.fields['parent'].queryset = self.fields['parent'].queryset.filter(**params)
 
 
@@ -370,7 +370,7 @@ class RackImportForm(PrimaryModelImportForm):
         if data:
 
             # Limit location queryset by assigned site
-            params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
+            params = self.get_related_filter('site', 'site', data.get('site'))
             self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
 
     def clean(self):
@@ -433,13 +433,13 @@ class RackReservationImportForm(PrimaryModelImportForm):
         if data:
 
             # Limit location queryset by assigned site
-            params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
+            params = self.get_related_filter('site', 'site', data.get('site'))
             self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
 
             # Limit rack queryset by assigned site and group
             params = {
-                f"site__{self.fields['site'].to_field_name}": data.get('site'),
-                f"location__{self.fields['location'].to_field_name}": data.get('location'),
+                **self.get_related_filter('site', 'site', data.get('site')),
+                **self.get_related_filter('location', 'location', data.get('location')),
             }
             self.fields['rack'].queryset = self.fields['rack'].queryset.filter(**params)
 
@@ -511,6 +511,12 @@ class ModuleTypeProfileImportForm(PrimaryModelImportForm):
 
 
 class ModuleTypeImportForm(PrimaryModelImportForm):
+    module_bay_types = CSVModelMultipleChoiceField(
+        label=_('Module bay types'),
+        queryset=ModuleBayType.objects.all(),
+        to_field_name='name',
+        required=False,
+    )
     profile = forms.ModelChoiceField(
         label=_('Profile'),
         queryset=ModuleTypeProfile.objects.all(),
@@ -555,7 +561,7 @@ class ModuleTypeImportForm(PrimaryModelImportForm):
         model = ModuleType
         fields = [
             'manufacturer', 'model', 'part_number', 'description', 'cooling_method', 'airflow', 'weight', 'weight_unit',
-            'end_of_life', 'profile', 'attribute_data', 'owner', 'comments', 'tags',
+            'end_of_life', 'profile', 'attribute_data', 'module_bay_types', 'owner', 'comments', 'tags',
         ]
 
     def clean(self):
@@ -569,6 +575,40 @@ class ModuleTypeImportForm(PrimaryModelImportForm):
         if self.cleaned_data.get('profile') and not self.cleaned_data.get('attribute_data'):
             self.cleaned_data['attribute_data'] = {}
 
+        module_bay_types = self.cleaned_data.get('module_bay_types')
+        manufacturer = self.cleaned_data.get('manufacturer')
+
+        # If importing an update to an existing module type and the manufacturer is not in
+        # the import data, use the existing manufacturer.
+        if manufacturer is None and self.instance.pk:
+            manufacturer = self.instance.manufacturer
+        if not module_bay_types or manufacturer is None:
+            return
+
+        # Match the module's manufacturer or a global bay type, preferring the former
+        # when a name is shared, as with module bay template imports.
+        by_name = {}
+        for module_bay_type in module_bay_types:
+            if module_bay_type.manufacturer_id not in (None, manufacturer.pk):
+                continue
+            existing = by_name.get(module_bay_type.name)
+            if existing is None or module_bay_type.manufacturer_id is not None:
+                by_name[module_bay_type.name] = module_bay_type
+
+        # A name matching only some other manufacturer's bay type is rejected rather than
+        # resolved to it.
+        for module_bay_type in module_bay_types:
+            if module_bay_type.name not in by_name:
+                raise forms.ValidationError({
+                    'module_bay_types': forms.ValidationError(
+                        self.fields['module_bay_types'].error_messages['invalid_choice'],
+                        code='invalid_choice',
+                        params={'value': module_bay_type.name},
+                    )
+                })
+
+        self.cleaned_data['module_bay_types'] = list(by_name.values())
+
 
 class DeviceRoleImportForm(NestedGroupModelImportForm):
     parent = CSVModelChoiceField(
@@ -692,7 +732,7 @@ class BaseDeviceImportForm(PrimaryModelImportForm):
         if data:
 
             # Limit device type queryset by manufacturer
-            params = {f"manufacturer__{self.fields['manufacturer'].to_field_name}": data.get('manufacturer')}
+            params = self.get_related_filter('manufacturer', 'manufacturer', data.get('manufacturer'))
             self.fields['device_type'].queryset = self.fields['device_type'].queryset.filter(**params)
 
 
@@ -776,29 +816,25 @@ class DeviceImportForm(BaseDeviceImportForm):
         if data:
 
             # Limit location queryset by assigned site
-            params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
+            params = self.get_related_filter('site', 'site', data.get('site'))
             self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
             self.fields['parent'].queryset = self.fields['parent'].queryset.filter(**params)
 
             # Limit rack queryset by assigned site and location
-            params = {
-                f"site__{self.fields['site'].to_field_name}": data.get('site'),
-            }
+            params = self.get_related_filter('site', 'site', data.get('site'))
             if location := data.get('location'):
-                params.update({
-                    f"location__{self.fields['location'].to_field_name}": location,
-                })
+                params.update(self.get_related_filter('location', 'location', location))
             self.fields['rack'].queryset = self.fields['rack'].queryset.filter(**params)
 
             # Limit platform queryset by manufacturer
-            params = {f"manufacturer__{self.fields['manufacturer'].to_field_name}": data.get('manufacturer')}
+            params = self.get_related_filter('manufacturer', 'manufacturer', data.get('manufacturer'))
             self.fields['platform'].queryset = self.fields['platform'].queryset.filter(
                 Q(**params) | Q(manufacturer=None)
             )
 
             # Limit device bay queryset by parent device
             if parent := data.get('parent'):
-                params = {f"device__{self.fields['parent'].to_field_name}": parent}
+                params = self.get_related_filter('device', 'parent', parent)
                 self.fields['device_bay'].queryset = self.fields['device_bay'].queryset.filter(**params)
 
     def clean(self):
@@ -871,7 +907,7 @@ class ModuleImportForm(ModuleCommonForm, PrimaryModelImportForm):
 
         if data:
             # Limit module_bay queryset by assigned device
-            params = {f"device__{self.fields['device'].to_field_name}": data.get('device')}
+            params = self.get_related_filter('device', 'device', data.get('device'))
             self.fields['module_bay'].queryset = self.fields['module_bay'].queryset.filter(**params)
 
     def clean_replicate_components(self):
@@ -1290,9 +1326,7 @@ class InterfaceImportForm(OwnerCSVMixin, NetBoxModelImportForm):
         if data:
             # Limit choices for parent, bridge, and LAG interfaces to the assigned device
             if device := data.get('device'):
-                params = {
-                    f"device__{self.fields['device'].to_field_name}": device
-                }
+                params = self.get_related_filter('device', 'device', device)
                 self.fields['parent'].queryset = self.fields['parent'].queryset.filter(**params)
                 self.fields['bridge'].queryset = self.fields['bridge'].queryset.filter(**params)
                 self.fields['lag'].queryset = self.fields['lag'].queryset.filter(**params)
@@ -1300,7 +1334,7 @@ class InterfaceImportForm(OwnerCSVMixin, NetBoxModelImportForm):
 
             # Limit choices for VLANs to the assigned VLAN group
             if vlan_group := data.get('vlan_group'):
-                params = {f"group__{self.fields['vlan_group'].to_field_name}": vlan_group}
+                params = self.get_related_filter('group', 'vlan_group', vlan_group)
                 self.fields['untagged_vlan'].queryset = self.fields['untagged_vlan'].queryset.filter(**params)
                 self.fields['tagged_vlans'].queryset = self.fields['tagged_vlans'].queryset.filter(**params)
                 self.fields['qinq_svlan'].queryset = self.fields['qinq_svlan'].queryset.filter(**params)
@@ -1684,13 +1718,13 @@ class MACAddressImportForm(PrimaryModelImportForm):
             # Limit interface queryset by assigned device
             if data.get('device'):
                 self.fields['interface'].queryset = Interface.objects.filter(
-                    **{f"device__{self.fields['device'].to_field_name}": data['device']}
+                    **self.get_related_filter('device', 'device', data['device'])
                 )
 
             # Limit interface queryset by assigned device
             elif data.get('virtual_machine'):
                 self.fields['interface'].queryset = VMInterface.objects.filter(
-                    **{f"virtual_machine__{self.fields['virtual_machine'].to_field_name}": data['virtual_machine']}
+                    **self.get_related_filter('virtual_machine', 'virtual_machine', data['virtual_machine'])
                 )
 
     def clean(self):
@@ -1912,7 +1946,7 @@ class CableImportForm(PrimaryModelImportForm):
         if data:
             # Limit choices for side_a_device to the assigned side_a_site
             if side_a_site := data.get('side_a_site'):
-                side_a_parent_params = {f'site__{self.fields['side_a_site'].to_field_name}': side_a_site}
+                side_a_parent_params = self.get_related_filter('site', 'side_a_site', side_a_site)
                 self.fields['side_a_device'].queryset = self.fields['side_a_device'].queryset.filter(
                     **side_a_parent_params
                 )
@@ -1922,7 +1956,7 @@ class CableImportForm(PrimaryModelImportForm):
 
             # Limit choices for side_b_device to the assigned side_b_site
             if side_b_site := data.get('side_b_site'):
-                side_b_parent_params = {f'site__{self.fields['side_b_site'].to_field_name}': side_b_site}
+                side_b_parent_params = self.get_related_filter('site', 'side_b_site', side_b_site)
                 self.fields['side_b_device'].queryset = self.fields['side_b_device'].queryset.filter(
                     **side_b_parent_params
                 )
@@ -1995,12 +2029,11 @@ class CableImportForm(PrimaryModelImportForm):
             # The parent field has already raised its own validation error
             return None
         field = self.fields[field_name]
-        to_field_name = field.to_field_name or 'pk'
 
         parents = []
         for value in self._split_side_values(self.data.get(field_name)):
             try:
-                parents.append(field.queryset.get(**{to_field_name: value}))
+                parents.append(field.filter_by_value(value).get())
             except ObjectDoesNotExist:
                 self.add_error(field_name, _("Object not found: {value}").format(value=value))
                 return None
@@ -2236,7 +2269,7 @@ class PowerPanelImportForm(PrimaryModelImportForm):
         if data:
 
             # Limit group queryset by assigned site
-            params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
+            params = self.get_related_filter('site', 'site', data.get('site'))
             self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
 
 
@@ -2307,17 +2340,17 @@ class PowerFeedImportForm(PrimaryModelImportForm):
         if data:
 
             # Limit power_panel queryset by site
-            params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
+            params = self.get_related_filter('site', 'site', data.get('site'))
             self.fields['power_panel'].queryset = self.fields['power_panel'].queryset.filter(**params)
 
             # Limit location queryset by site
-            params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
+            params = self.get_related_filter('site', 'site', data.get('site'))
             self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
 
             # Limit rack queryset by site and group
             params = {
-                f"site__{self.fields['site'].to_field_name}": data.get('site'),
-                f"location__{self.fields['location'].to_field_name}": data.get('location'),
+                **self.get_related_filter('site', 'site', data.get('site')),
+                **self.get_related_filter('location', 'location', data.get('location')),
             }
             self.fields['rack'].queryset = self.fields['rack'].queryset.filter(**params)
 
@@ -2365,7 +2398,7 @@ class CoolingSourceImportForm(PrimaryModelImportForm):
         if data:
 
             # Limit location queryset by assigned site
-            params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
+            params = self.get_related_filter('site', 'site', data.get('site'))
             self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
 
 
@@ -2428,17 +2461,17 @@ class CoolingFeedImportForm(PrimaryModelImportForm):
         if data:
 
             # Limit cooling_source queryset by site
-            params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
+            params = self.get_related_filter('site', 'site', data.get('site'))
             self.fields['cooling_source'].queryset = self.fields['cooling_source'].queryset.filter(**params)
 
             # Limit location queryset by site
-            params = {f"site__{self.fields['site'].to_field_name}": data.get('site')}
+            params = self.get_related_filter('site', 'site', data.get('site'))
             self.fields['location'].queryset = self.fields['location'].queryset.filter(**params)
 
             # Limit rack queryset by site and group
             params = {
-                f"site__{self.fields['site'].to_field_name}": data.get('site'),
-                f"location__{self.fields['location'].to_field_name}": data.get('location'),
+                **self.get_related_filter('site', 'site', data.get('site')),
+                **self.get_related_filter('location', 'location', data.get('location')),
             }
             self.fields['rack'].queryset = self.fields['rack'].queryset.filter(**params)
 
@@ -2488,6 +2521,6 @@ class VirtualDeviceContextImportForm(PrimaryModelImportForm):
         if data:
 
             # Limit primary_ip4/ip6 querysets by assigned device
-            params = {f"interface__device__{self.fields['device'].to_field_name}": data.get('device')}
+            params = self.get_related_filter('interface__device', 'device', data.get('device'))
             self.fields['primary_ip4'].queryset = self.fields['primary_ip4'].queryset.filter(**params)
             self.fields['primary_ip6'].queryset = self.fields['primary_ip6'].queryset.filter(**params)

+ 3 - 7
netbox/dcim/graphql/filters.py

@@ -44,7 +44,7 @@ from .filter_mixins import (
 
 if TYPE_CHECKING:
     from core.graphql.filters import ContentTypeFilter
-    from extras.graphql.filters import ConfigTemplateFilter, ImageAttachmentFilter
+    from extras.graphql.filters import ConfigTemplateFilter
     from ipam.graphql.filters import (
         ASNFilter,
         FHRPGroupAssignmentFilter,
@@ -413,12 +413,8 @@ class DeviceTypeFilter(ImageAttachmentFilterMixin, WeightFilterMixin, PrimaryMod
         strawberry_django.filter_field()
     )
     end_of_life: DateFilterLookup | None = strawberry_django.filter_field()
-    front_image: Annotated['ImageAttachmentFilter', strawberry.lazy('extras.graphql.filters')] | None = (
-        strawberry_django.filter_field()
-    )
-    rear_image: Annotated['ImageAttachmentFilter', strawberry.lazy('extras.graphql.filters')] | None = (
-        strawberry_django.filter_field()
-    )
+    front_image: StrFilterLookup | None = strawberry_django.filter_field()
+    rear_image: StrFilterLookup | None = strawberry_django.filter_field()
     consoleporttemplates: Annotated['ConsolePortTemplateFilter', strawberry.lazy('dcim.graphql.filters')] | None = (
         strawberry_django.filter_field(name='console_port_templates')
     )

+ 51 - 25
netbox/dcim/models/cables.py

@@ -21,6 +21,7 @@ from dcim.exceptions import UnsupportedCablePath
 from dcim.fields import PathField
 from dcim.utils import decompile_path_node, object_to_path_node, rebuild_cable_paths
 from netbox.choices import ColorChoices
+from netbox.context import current_request
 from netbox.models import ChangeLoggedModel, PrimaryModel
 from utilities.conversion import LENGTH_TO_METERS, normalized_unit_expression
 from utilities.data import normalize_update_fields
@@ -167,7 +168,7 @@ class Cable(PrimaryModel):
         verbose_name=_('bundle'),
     )
 
-    clone_fields = ('tenant', 'type', 'profile', 'bundle')
+    clone_fields = ('tenant', 'type', 'profile', 'bundle', 'color', 'length', 'length_unit')
 
     objects = CableQuerySet.as_manager()
 
@@ -354,6 +355,8 @@ class Cable(PrimaryModel):
 
     def save(self, *args, force_insert=False, force_update=False, using=None, update_fields=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 = {
             'using': using,
             'update_fields': update_fields,
@@ -376,17 +379,24 @@ class Cable(PrimaryModel):
         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 self._state.adding:
+        if adding:
             super().save(*args, force_insert=True, **save_kwargs)
             # Update the private PK used in __str__()
             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)
+        # 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:
             trace_paths.send(Cable, instance=self, created=_created, status_written=status_written)
@@ -978,6 +988,9 @@ class CablePath(models.Model):
         is_complete = False
         is_active = True
         is_split = False
+        # Whether the trace fanned out across a multi-position front port without positional context
+        fanout = False
+        diverged = False
 
         logger.debug(f'Tracing cable path from {terminations}...')
 
@@ -997,7 +1010,11 @@ class CablePath(models.Model):
                 not isinstance(terminations[0].parent_object, Circuit) and
                 not all(t.parent_object == terminations[0].parent_object for t in terminations[1:])
             ):
-                raise UnsupportedCablePath(_("All mid-span terminations must have the same parent object"))
+                if not fanout:
+                    raise UnsupportedCablePath(_("All mid-span terminations must have the same parent object"))
+                # Fanned-out branches crossing different devices are not followed, even if they reconverge later
+                diverged = True
+                break
 
             # Check for a split path (e.g. rear port fanning out to multiple front ports with
             # different cables attached)
@@ -1093,20 +1110,18 @@ class CablePath(models.Model):
                         # channelized parent is never itself a path endpoint, so an unoccupied position yields no peer.
                         if new_pos is not None and getattr(peer, 'channels', None):
                             peer = peer.child_interfaces.filter(channel_id=new_pos).first()
+                        # Skip positions with no far-end termination (e.g. an unpopulated breakout leg) so that
+                        # a partially terminated cable still traces through to its connected peers. If no peers
+                        # remain, the path is recorded as incomplete.
+                        if peer is None:
+                            continue
                         # Deduplicate peer terminations by model type & PK.
-                        key = None if peer is None else (peer._meta.concrete_model, peer.pk)
+                        key = (peer._meta.concrete_model, peer.pk)
                         if key not in seen:
                             seen.add(key)
                             remote_terminations.append(peer)
                         new_positions.append(new_pos)
 
-                    # If all peers resolved to None (no far-end terminations exist),
-                    # treat as an empty result so the path is recorded as incomplete
-                    # rather than falling through to the endpoint check with a stale
-                    # None entry.
-                    if remote_terminations and all(peer is None for peer in remote_terminations):
-                        remote_terminations = []
-
                     position_stack.append(new_positions)
 
                 # Legacy (positionless) behavior
@@ -1162,15 +1177,13 @@ class CablePath(models.Model):
                     for rt in remote_terminations:
                         q_filter |= Q(front_port=rt, front_port_position__in=positions)
                     port_mappings = PortMapping.objects.filter(q_filter)
-                elif remote_terminations[0].positions > 1:
-                    is_split = True
-                    logger.debug(
-                        'Encountered front port mapped to multiple rear ports but position stack is empty; aborting '
-                        'trace.'
-                    )
-                    break
                 else:
-                    port_mappings = PortMapping.objects.filter(front_port__in=remote_terminations)
+                    # Without positional context, follow all mappings; branches must converge on one endpoint
+                    if any(t.positions > 1 for t in remote_terminations):
+                        fanout = True
+                    port_mappings = PortMapping.objects.filter(
+                        front_port__in=remote_terminations
+                    ).order_by('front_port', 'front_port_position')
                 if not port_mappings:
                     break
 
@@ -1242,7 +1255,10 @@ class CablePath(models.Model):
 
             else:
                 # Check for non-symmetric path
-                if all(isinstance(t, type(remote_terminations[0])) for t in remote_terminations[1:]):
+                # Fanned-out branches arriving over separate links reach different endpoints
+                if fanout and len(links) > 1:
+                    diverged = True
+                elif all(isinstance(t, type(remote_terminations[0])) for t in remote_terminations[1:]):
                     is_complete = True
                 elif len(remote_terminations) == 0:
                     is_complete = False
@@ -1253,6 +1269,12 @@ class CablePath(models.Model):
                     logger.warning('Encountered an unsupported topology; aborting trace.')
                 break
 
+        if diverged:
+            # Keep the full trace so changes to any branch retrace this path
+            logger.debug('Front port branches diverged; treating path as split.')
+            is_complete = False
+            is_split = True
+
         return cls(
             path=path,
             is_complete=is_complete,
@@ -1357,7 +1379,8 @@ class CablePath(models.Model):
 
     def get_split_nodes(self):
         """
-        Return all available next segments in a split cable path.
+        Return all available next segments in a split cable path, or the diverging endpoints if the path fanned
+        out across a multi-position front port.
         """
         from circuits.models import CircuitTermination
         nodes = self.path_objects[-1]
@@ -1380,6 +1403,9 @@ class CablePath(models.Model):
             return [
                 ct.get_peer_termination() for ct in nodes
             ]
+        # Front port branches diverging to different endpoints
+        if isinstance(nodes[0], PathEndpoint):
+            return nodes
         return []
 
     def get_asymmetric_nodes(self):

+ 2 - 1
netbox/dcim/models/device_component_templates.py

@@ -1096,7 +1096,8 @@ class InventoryItemTemplate(LtreeModel, ComponentTemplateModel):
         parent = InventoryItem.objects.get(name=self.parent.name, **kwargs) if self.parent else None
         if self.component:
             model = self.component.component_model
-            component = model.objects.get(name=self.component.name, **kwargs)
+            component_name = self.component.resolve_name(kwargs.get('module'), kwargs.get('device'))
+            component = model.objects.get(name=component_name, **kwargs)
         else:
             component = None
         return self.component_model(

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

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

+ 5 - 0
netbox/dcim/signals.py

@@ -503,8 +503,13 @@ def update_mac_address_interface(instance, created, raw, **kwargs):
     assign the MACAddress to the interface.
     """
     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.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)
 
 
 #

+ 4 - 2
netbox/dcim/tables/devices.py

@@ -822,7 +822,8 @@ class FrontPortTable(ModularDeviceComponentTable, CableTerminationTable):
     )
     mappings = columns.ManyToManyColumn(
         verbose_name=_('Mappings'),
-        transform=lambda obj: f'{obj.rear_port}:{obj.rear_port_position}'
+        transform=lambda obj: f'{obj.rear_port}:{obj.rear_port_position}',
+        prefetch_related=('mappings__rear_port',)
     )
     tags = columns.TagColumn(
         url_name='dcim:frontport_list'
@@ -875,7 +876,8 @@ class RearPortTable(ModularDeviceComponentTable, CableTerminationTable):
     )
     mappings = columns.ManyToManyColumn(
         verbose_name=_('Mappings'),
-        transform=lambda obj: f'{obj.front_port}:{obj.front_port_position}'
+        transform=lambda obj: f'{obj.front_port}:{obj.front_port_position}',
+        prefetch_related=('mappings__front_port',)
     )
     tags = columns.TagColumn(
         url_name='dcim:rearport_list'

+ 4 - 2
netbox/dcim/tables/devicetypes.py

@@ -266,7 +266,8 @@ class FrontPortTemplateTable(ComponentTemplateTable):
     )
     mappings = columns.ManyToManyColumn(
         verbose_name=_('Mappings'),
-        transform=lambda obj: f'{obj.rear_port}:{obj.rear_port_position}'
+        transform=lambda obj: f'{obj.rear_port}:{obj.rear_port_position}',
+        prefetch_related=('mappings__rear_port',)
     )
     actions = columns.ActionsColumn(
         actions=('edit', 'delete'),
@@ -285,7 +286,8 @@ class RearPortTemplateTable(ComponentTemplateTable):
     )
     mappings = columns.ManyToManyColumn(
         verbose_name=_('Mappings'),
-        transform=lambda obj: f'{obj.front_port}:{obj.front_port_position}'
+        transform=lambda obj: f'{obj.front_port}:{obj.front_port_position}',
+        prefetch_related=('mappings__front_port',)
     )
     actions = columns.ActionsColumn(
         actions=('edit', 'delete'),

+ 1 - 1
netbox/dcim/tests/query_counts.json

@@ -31,7 +31,7 @@
   "devicetype:api_list_objects": 13,
   "devicetype:list_objects_with_permission": 17,
   "frontport:api_list_objects": 14,
-  "frontport:list_objects_with_permission": 21,
+  "frontport:list_objects_with_permission": 19,
   "frontporttemplate:api_list_objects": 12,
   "interface:api_list_objects": 21,
   "interface:list_objects_with_permission": 17,

+ 39 - 2
netbox/dcim/tests/test_api.py

@@ -1729,6 +1729,33 @@ class DeviceTypeTestCase(APIViewTestCases.APIViewTestCase):
         'airflow': 'not-a-valid-airflow',
     }
     user_permissions = ('dcim.view_manufacturer', )
+    graphql_filter_tests = (
+        GraphQLFilterTest(
+            name='front_image__exact',
+            filters='front_image: {exact: "devicetype-images/device-type-2-front.png"}',
+            expected=lambda qs: qs.filter(model='Device Type 2'),
+        ),
+        GraphQLFilterTest(
+            name='front_image__exact_empty',
+            filters='front_image: {exact: ""}',
+            expected=lambda qs: qs.filter(model__in=['Device Type 1', 'Device Type 3']),
+        ),
+        GraphQLFilterTest(
+            name='front_image__contains',
+            filters='front_image: {contains: "front.png"}',
+            expected=lambda qs: qs.filter(model='Device Type 2'),
+        ),
+        GraphQLFilterTest(
+            name='rear_image__exact',
+            filters='rear_image: {exact: "devicetype-images/device-type-3-rear.png"}',
+            expected=lambda qs: qs.filter(model='Device Type 3'),
+        ),
+        GraphQLFilterTest(
+            name='rear_image__exact_empty',
+            filters='rear_image: {exact: ""}',
+            expected=lambda qs: qs.filter(model__in=['Device Type 1', 'Device Type 2']),
+        ),
+    )
 
     @classmethod
     def setUpTestData(cls):
@@ -1741,8 +1768,18 @@ class DeviceTypeTestCase(APIViewTestCases.APIViewTestCase):
 
         device_types = (
             DeviceType(manufacturer=manufacturers[0], model='Device Type 1', slug='device-type-1'),
-            DeviceType(manufacturer=manufacturers[0], model='Device Type 2', slug='device-type-2'),
-            DeviceType(manufacturer=manufacturers[0], model='Device Type 3', slug='device-type-3'),
+            DeviceType(
+                manufacturer=manufacturers[0],
+                model='Device Type 2',
+                slug='device-type-2',
+                front_image='devicetype-images/device-type-2-front.png',
+            ),
+            DeviceType(
+                manufacturer=manufacturers[0],
+                model='Device Type 3',
+                slug='device-type-3',
+                rear_image='devicetype-images/device-type-3-rear.png',
+            ),
         )
         DeviceType.objects.bulk_create(device_types)
 

+ 522 - 0
netbox/dcim/tests/test_cablepaths.py

@@ -2746,6 +2746,528 @@ class LegacyCablePathTestCase(BaseCablePathTestCase):
         cablepath.delete()
         self.assertIsNone(CablePath.objects.filter(pk=cablepath.pk).first())
 
+    def test_226_multiposition_frontport_to_converging_rear_ports(self):
+        """
+        [IF1] --C1-- [FP1:1] [RP1] --C2-- [RP3] [FP2] --C4-- [IF2]
+                     [FP1:2] [RP2] --C3-- [RP4] [FP3]
+        """
+        interface1 = Interface.objects.create(device=self.device, name='Interface 1')
+        interface2 = Interface.objects.create(device=self.device, name='Interface 2')
+        rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1')
+        rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2')
+        rearport3 = RearPort.objects.create(device=self.device, name='Rear Port 3')
+        rearport4 = RearPort.objects.create(device=self.device, name='Rear Port 4')
+        frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1', positions=2)
+        frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2')
+        frontport3 = FrontPort.objects.create(device=self.device, name='Front Port 3')
+        PortMapping.objects.bulk_create([
+            PortMapping(
+                device=self.device, front_port=frontport1, front_port_position=1,
+                rear_port=rearport1, rear_port_position=1,
+            ),
+            PortMapping(
+                device=self.device, front_port=frontport1, front_port_position=2,
+                rear_port=rearport2, rear_port_position=1,
+            ),
+            PortMapping(
+                device=self.device, front_port=frontport2, front_port_position=1,
+                rear_port=rearport3, rear_port_position=1,
+            ),
+            PortMapping(
+                device=self.device, front_port=frontport3, front_port_position=1,
+                rear_port=rearport4, rear_port_position=1,
+            ),
+        ])
+
+        cable1 = Cable(a_terminations=[interface1], b_terminations=[frontport1])
+        cable1.save()
+        cable2 = Cable(a_terminations=[rearport1], b_terminations=[rearport3])
+        cable2.save()
+        cable3 = Cable(a_terminations=[rearport2], b_terminations=[rearport4])
+        cable3.save()
+        cable4 = Cable(a_terminations=[frontport2, frontport3], b_terminations=[interface2])
+        cable4.save()
+
+        path1 = self.assertPathExists(
+            (
+                interface1, cable1, frontport1, (rearport1, rearport2), (cable2, cable3),
+                (rearport3, rearport4), (frontport2, frontport3), cable4, interface2
+            ),
+            is_complete=True,
+            is_active=True,
+            is_split=False
+        )
+        path2 = self.assertPathExists(
+            (
+                interface2, cable4, (frontport2, frontport3), (rearport3, rearport4), (cable2, cable3),
+                (rearport1, rearport2), frontport1, cable1, interface1
+            ),
+            is_complete=True,
+            is_active=True,
+            is_split=False
+        )
+        self.assertEqual(CablePath.objects.count(), 2)
+        interface1.refresh_from_db()
+        interface2.refresh_from_db()
+        self.assertPathIsSet(interface1, path1)
+        self.assertPathIsSet(interface2, path2)
+
+    def test_227_multiposition_frontport_to_diverging_rear_ports(self):
+        """
+        [IF1] --C1-- [FP1:1] [RP1] --C2-- [IF2]
+                     [FP1:2] [RP2] --C3-- [IF3]
+        """
+        interface1 = Interface.objects.create(device=self.device, name='Interface 1')
+        interface2 = Interface.objects.create(device=self.device, name='Interface 2')
+        interface3 = Interface.objects.create(device=self.device, name='Interface 3')
+        rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1')
+        rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2')
+        frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1', positions=2)
+        PortMapping.objects.bulk_create([
+            PortMapping(
+                device=self.device, front_port=frontport1, front_port_position=1,
+                rear_port=rearport1, rear_port_position=1,
+            ),
+            PortMapping(
+                device=self.device, front_port=frontport1, front_port_position=2,
+                rear_port=rearport2, rear_port_position=1,
+            ),
+        ])
+
+        cable1 = Cable(a_terminations=[interface1], b_terminations=[frontport1])
+        cable1.save()
+        cable2 = Cable(a_terminations=[rearport1], b_terminations=[interface2])
+        cable2.save()
+        cable3 = Cable(a_terminations=[rearport2], b_terminations=[interface3])
+        cable3.save()
+
+        # Branches reaching different endpoints are still treated as a split
+        path1 = self.assertPathExists(
+            (
+                interface1, cable1, frontport1, (rearport1, rearport2), (cable2, cable3),
+                (interface2, interface3)
+            ),
+            is_complete=False,
+            is_split=True
+        )
+        self.assertEqual(path1.get_split_nodes(), [interface2, interface3])
+        self.assertPathExists(
+            (interface2, cable2, rearport1, frontport1, cable1, interface1),
+            is_complete=True,
+            is_active=True
+        )
+        self.assertPathExists(
+            (interface3, cable3, rearport2, frontport1, cable1, interface1),
+            is_complete=True,
+            is_active=True
+        )
+        self.assertEqual(CablePath.objects.count(), 3)
+
+    def test_228_multiposition_frontport_to_crossed_rear_ports_on_remote_device(self):
+        """
+        Device A                                    Device B
+        [IF1] --C1-- [FP1:1] [RP1] --C2-- [RP4] [FP3] --C4-- [IF2]
+                     [FP1:2] [RP2] --C3-- [RP3] [FP2] --C4--
+        """
+        device_b = Device.objects.create(
+            site=self.site, device_type=self.device.device_type, role=self.device.role, name='Device B'
+        )
+        interface1 = Interface.objects.create(device=self.device, name='Interface 1')
+        interface2 = Interface.objects.create(device=device_b, name='Interface 2')
+        rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1')
+        rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2')
+        rearport3 = RearPort.objects.create(device=device_b, name='Rear Port 3')
+        rearport4 = RearPort.objects.create(device=device_b, name='Rear Port 4')
+        frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1', positions=2)
+        frontport2 = FrontPort.objects.create(device=device_b, name='Front Port 2')
+        frontport3 = FrontPort.objects.create(device=device_b, name='Front Port 3')
+        PortMapping.objects.bulk_create([
+            PortMapping(
+                device=self.device, front_port=frontport1, front_port_position=1,
+                rear_port=rearport1, rear_port_position=1,
+            ),
+            PortMapping(
+                device=self.device, front_port=frontport1, front_port_position=2,
+                rear_port=rearport2, rear_port_position=1,
+            ),
+            PortMapping(
+                device=device_b, front_port=frontport2, front_port_position=1,
+                rear_port=rearport3, rear_port_position=1,
+            ),
+            PortMapping(
+                device=device_b, front_port=frontport3, front_port_position=1,
+                rear_port=rearport4, rear_port_position=1,
+            ),
+        ])
+
+        # TX/RX crossed between the two devices
+        cable1 = Cable(a_terminations=[interface1], b_terminations=[frontport1])
+        cable1.save()
+        cable2 = Cable(a_terminations=[rearport1], b_terminations=[rearport4])
+        cable2.save()
+        cable3 = Cable(a_terminations=[rearport2], b_terminations=[rearport3])
+        cable3.save()
+        cable4 = Cable(a_terminations=[frontport2, frontport3], b_terminations=[interface2])
+        cable4.save()
+
+        path1 = self.assertPathExists(
+            (
+                interface1, cable1, frontport1, (rearport1, rearport2), (cable2, cable3),
+                (rearport4, rearport3), (frontport2, frontport3), cable4, interface2
+            ),
+            is_complete=True,
+            is_active=True,
+            is_split=False
+        )
+        path2 = self.assertPathExists(
+            (
+                interface2, cable4, (frontport2, frontport3), (rearport3, rearport4), (cable3, cable2),
+                (rearport1, rearport2), frontport1, cable1, interface1
+            ),
+            is_complete=True,
+            is_active=True,
+            is_split=False
+        )
+        self.assertEqual(CablePath.objects.count(), 2)
+        interface1.refresh_from_db()
+        interface2.refresh_from_db()
+        self.assertPathIsSet(interface1, path1)
+        self.assertPathIsSet(interface2, path2)
+        self.assertEqual(interface1.connected_endpoints, [interface2])
+        self.assertEqual(interface2.connected_endpoints, [interface1])
+
+    def test_229_multiposition_frontport_to_rear_ports_on_different_devices(self):
+        """
+        [IF1] --C1-- [FP1:1] [RP1] --C2-- [RP3] [FP2]  (Device A)
+                     [FP1:2] [RP2] --C3-- [RP4] [FP3]  (Device B)
+        """
+        device_a = Device.objects.create(
+            site=self.site, device_type=self.device.device_type, role=self.device.role, name='Device A'
+        )
+        device_b = Device.objects.create(
+            site=self.site, device_type=self.device.device_type, role=self.device.role, name='Device B'
+        )
+        interface1 = Interface.objects.create(device=self.device, name='Interface 1')
+        rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1')
+        rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2')
+        rearport3 = RearPort.objects.create(device=device_a, name='Rear Port 3')
+        rearport4 = RearPort.objects.create(device=device_b, name='Rear Port 4')
+        frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1', positions=2)
+        frontport2 = FrontPort.objects.create(device=device_a, name='Front Port 2')
+        frontport3 = FrontPort.objects.create(device=device_b, name='Front Port 3')
+        PortMapping.objects.bulk_create([
+            PortMapping(
+                device=self.device, front_port=frontport1, front_port_position=1,
+                rear_port=rearport1, rear_port_position=1,
+            ),
+            PortMapping(
+                device=self.device, front_port=frontport1, front_port_position=2,
+                rear_port=rearport2, rear_port_position=1,
+            ),
+            PortMapping(
+                device=device_a, front_port=frontport2, front_port_position=1,
+                rear_port=rearport3, rear_port_position=1,
+            ),
+            PortMapping(
+                device=device_b, front_port=frontport3, front_port_position=1,
+                rear_port=rearport4, rear_port_position=1,
+            ),
+        ])
+
+        cable1 = Cable(a_terminations=[interface1], b_terminations=[frontport1])
+        cable1.save()
+        cable2 = Cable(a_terminations=[rearport1], b_terminations=[rearport3], status=LinkStatusChoices.STATUS_PLANNED)
+        cable2.save()
+        cable3 = Cable(a_terminations=[rearport2], b_terminations=[rearport4])
+        cable3.save()
+
+        # Branches crossing different devices are not followed past the remote rear ports
+        path1 = self.assertPathExists(
+            (interface1, cable1, frontport1, (rearport1, rearport2), (cable2, cable3), (rearport3, rearport4)),
+            is_complete=False,
+            is_active=False,
+            is_split=True
+        )
+        self.assertEqual(CablePath.objects.count(), 1)
+        interface1.refresh_from_db()
+        self.assertPathIsSet(interface1, path1)
+
+    def test_230_multiposition_frontport_with_uncabled_rear_port(self):
+        """
+        [IF1] --C1-- [FP1:1] [RP1] --C2-- [RP3] [FP2] --C3-- [IF2]
+                     [FP1:2] [RP2]
+        """
+        interface1 = Interface.objects.create(device=self.device, name='Interface 1')
+        interface2 = Interface.objects.create(device=self.device, name='Interface 2')
+        rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1')
+        rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2')
+        rearport3 = RearPort.objects.create(device=self.device, name='Rear Port 3')
+        frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1', positions=2)
+        frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2')
+        PortMapping.objects.bulk_create([
+            PortMapping(
+                device=self.device, front_port=frontport1, front_port_position=1,
+                rear_port=rearport1, rear_port_position=1,
+            ),
+            PortMapping(
+                device=self.device, front_port=frontport1, front_port_position=2,
+                rear_port=rearport2, rear_port_position=1,
+            ),
+            PortMapping(
+                device=self.device, front_port=frontport2, front_port_position=1,
+                rear_port=rearport3, rear_port_position=1,
+            ),
+        ])
+
+        cable1 = Cable(a_terminations=[interface1], b_terminations=[frontport1])
+        cable1.save()
+        cable2 = Cable(a_terminations=[rearport1], b_terminations=[rearport3])
+        cable2.save()
+        cable3 = Cable(a_terminations=[frontport2], b_terminations=[interface2])
+        cable3.save()
+
+        # The uncabled branch is flagged as split (asymmetric), as for multi-termination cables
+        path1 = self.assertPathExists(
+            (
+                interface1, cable1, frontport1, (rearport1, rearport2), cable2, rearport3, frontport2, cable3,
+                interface2
+            ),
+            is_complete=True,
+            is_active=True,
+            is_split=True
+        )
+        path2 = self.assertPathExists(
+            (interface2, cable3, frontport2, rearport3, cable2, rearport1, frontport1, cable1, interface1),
+            is_complete=True,
+            is_active=True,
+            is_split=False
+        )
+        self.assertEqual(CablePath.objects.count(), 2)
+        interface1.refresh_from_db()
+        interface2.refresh_from_db()
+        self.assertPathIsSet(interface1, path1)
+        self.assertPathIsSet(interface2, path2)
+        self.assertEqual(interface1.connected_endpoints, [interface2])
+
+    def test_231_multiposition_frontport_rewire_diverged_to_converged(self):
+        """
+        [IF1] --C1-- [FP1:1] [RP1] --C2-- [RP3] [FP2] --C4-- [IF2]
+                     [FP1:2] [RP2] --C3-- [RP4] [FP3] --C5-- [IF3]
+        Rewired so that FP2 and FP3 both connect to IF2, then back again.
+        """
+        interface1 = Interface.objects.create(device=self.device, name='Interface 1')
+        interface2 = Interface.objects.create(device=self.device, name='Interface 2')
+        interface3 = Interface.objects.create(device=self.device, name='Interface 3')
+        rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1')
+        rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2')
+        rearport3 = RearPort.objects.create(device=self.device, name='Rear Port 3')
+        rearport4 = RearPort.objects.create(device=self.device, name='Rear Port 4')
+        frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1', positions=2)
+        frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2')
+        frontport3 = FrontPort.objects.create(device=self.device, name='Front Port 3')
+        PortMapping.objects.bulk_create([
+            PortMapping(
+                device=self.device, front_port=frontport1, front_port_position=1,
+                rear_port=rearport1, rear_port_position=1,
+            ),
+            PortMapping(
+                device=self.device, front_port=frontport1, front_port_position=2,
+                rear_port=rearport2, rear_port_position=1,
+            ),
+            PortMapping(
+                device=self.device, front_port=frontport2, front_port_position=1,
+                rear_port=rearport3, rear_port_position=1,
+            ),
+            PortMapping(
+                device=self.device, front_port=frontport3, front_port_position=1,
+                rear_port=rearport4, rear_port_position=1,
+            ),
+        ])
+
+        def assert_path_is_current(interface):
+            interface.refresh_from_db()
+            stored = interface.path
+            traced = CablePath.from_origin([interface])
+            self.assertEqual(
+                (stored.path, stored.is_complete, stored.is_active, stored.is_split),
+                (traced.path, traced.is_complete, traced.is_active, traced.is_split),
+            )
+            return stored
+
+        cable1 = Cable(a_terminations=[interface1], b_terminations=[frontport1])
+        cable1.save()
+        cable2 = Cable(a_terminations=[rearport1], b_terminations=[rearport3])
+        cable2.save()
+        cable3 = Cable(a_terminations=[rearport2], b_terminations=[rearport4])
+        cable3.save()
+        cable4 = Cable(a_terminations=[frontport2], b_terminations=[interface2])
+        cable4.save()
+        cable5 = Cable(a_terminations=[frontport3], b_terminations=[interface3])
+        cable5.save()
+        path1 = assert_path_is_current(interface1)
+        self.assertTrue(path1.is_split)
+        self.assertFalse(path1.is_complete)
+
+        # Removing one branch's endpoint leaves the other branch complete (and asymmetric)
+        cable5.delete()
+        path1 = assert_path_is_current(interface1)
+        self.assertTrue(path1.is_complete)
+
+        # Converge both branches on a single endpoint
+        cable4.delete()
+        cable6 = Cable(a_terminations=[frontport2, frontport3], b_terminations=[interface2])
+        cable6.save()
+        path1 = assert_path_is_current(interface1)
+        self.assertTrue(path1.is_complete)
+        self.assertFalse(path1.is_split)
+        self.assertEqual(Interface.objects.get(pk=interface1.pk).connected_endpoints, [interface2])
+        self.assertEqual(Interface.objects.get(pk=interface2.pk).connected_endpoints, [interface1])
+
+        # Diverge the branches again
+        cable6.delete()
+        cable7 = Cable(a_terminations=[frontport2], b_terminations=[interface2])
+        cable7.save()
+        cable8 = Cable(a_terminations=[frontport3], b_terminations=[interface3])
+        cable8.save()
+        path1 = assert_path_is_current(interface1)
+        self.assertTrue(path1.is_split)
+        self.assertFalse(path1.is_complete)
+        self.assertEqual(Interface.objects.get(pk=interface1.pk).connected_endpoints, [])
+
+    def test_232_multiposition_frontport_reconverged_to_multiple_interfaces(self):
+        """
+        [IF1] --C1-- [FP1:1] [RP1:1] --C2-- [RP2:1] [FP2:1] --C3-- [IF2]
+                     [FP1:2] [RP1:2]        [RP2:2] [FP2:2]        [IF3]
+        """
+        interface1 = Interface.objects.create(device=self.device, name='Interface 1')
+        interface2 = Interface.objects.create(device=self.device, name='Interface 2')
+        interface3 = Interface.objects.create(device=self.device, name='Interface 3')
+        rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=2)
+        rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=2)
+        frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1', positions=2)
+        frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2', positions=2)
+        PortMapping.objects.bulk_create([
+            PortMapping(
+                device=self.device, front_port=frontport, front_port_position=position,
+                rear_port=rearport, rear_port_position=position,
+            )
+            for frontport, rearport in ((frontport1, rearport1), (frontport2, rearport2))
+            for position in (1, 2)
+        ])
+
+        cable1 = Cable(a_terminations=[interface1], b_terminations=[frontport1])
+        cable1.save()
+        cable2 = Cable(a_terminations=[rearport1], b_terminations=[rearport2])
+        cable2.save()
+        cable3 = Cable(a_terminations=[frontport2], b_terminations=[interface2, interface3])
+        cable3.save()
+
+        # Branches reconverge on RP1, so the final multi-termination cable is not a split
+        self.assertPathExists(
+            (
+                interface1, cable1, frontport1, rearport1, cable2, rearport2, frontport2, cable3,
+                (interface2, interface3)
+            ),
+            is_complete=True,
+            is_active=True,
+            is_split=False
+        )
+
+    def test_233_mixed_position_frontports_to_diverging_rear_ports(self):
+        """
+        [IF1] --C1-- [FP1]   [RP1] --C2-- [IF3]
+        [IF2]        [FP2:1] [RP2] --C3-- [IF4]
+                     [FP2:2] [RP3] --C4-- [IF5]
+        """
+        interface1 = Interface.objects.create(device=self.device, name='Interface 1')
+        interface2 = Interface.objects.create(device=self.device, name='Interface 2')
+        interface3 = Interface.objects.create(device=self.device, name='Interface 3')
+        interface4 = Interface.objects.create(device=self.device, name='Interface 4')
+        interface5 = Interface.objects.create(device=self.device, name='Interface 5')
+        rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1')
+        rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2')
+        rearport3 = RearPort.objects.create(device=self.device, name='Rear Port 3')
+        frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1')
+        frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2', positions=2)
+        PortMapping.objects.bulk_create([
+            PortMapping(
+                device=self.device, front_port=frontport1, front_port_position=1,
+                rear_port=rearport1, rear_port_position=1,
+            ),
+            PortMapping(
+                device=self.device, front_port=frontport2, front_port_position=1,
+                rear_port=rearport2, rear_port_position=1,
+            ),
+            PortMapping(
+                device=self.device, front_port=frontport2, front_port_position=2,
+                rear_port=rearport3, rear_port_position=1,
+            ),
+        ])
+
+        # The single-position front port is the first termination on the cable
+        cable1 = Cable(a_terminations=[interface1, interface2], b_terminations=[frontport1, frontport2])
+        cable1.save()
+        for rearport, interface in ((rearport1, interface3), (rearport2, interface4), (rearport3, interface5)):
+            Cable(a_terminations=[rearport], b_terminations=[interface]).save()
+
+        interface1.refresh_from_db()
+        self.assertFalse(interface1.path.is_complete)
+        self.assertTrue(interface1.path.is_split)
+
+    def test_234_multiposition_frontport_reconverged_then_diverging(self):
+        """
+        [IF1] --C1-- [FP1:1] [RP1:1] --C2-- [RP2:1] [FP2] --C3-- [IF2]
+                     [FP1:2] [RP1:2]        [RP2:2] [FP3] --C4-- [IF3]
+        """
+        interface1 = Interface.objects.create(device=self.device, name='Interface 1')
+        interface2 = Interface.objects.create(device=self.device, name='Interface 2')
+        interface3 = Interface.objects.create(device=self.device, name='Interface 3')
+        rearport1 = RearPort.objects.create(device=self.device, name='Rear Port 1', positions=2)
+        rearport2 = RearPort.objects.create(device=self.device, name='Rear Port 2', positions=2)
+        frontport1 = FrontPort.objects.create(device=self.device, name='Front Port 1', positions=2)
+        frontport2 = FrontPort.objects.create(device=self.device, name='Front Port 2')
+        frontport3 = FrontPort.objects.create(device=self.device, name='Front Port 3')
+        PortMapping.objects.bulk_create([
+            PortMapping(
+                device=self.device, front_port=frontport1, front_port_position=1,
+                rear_port=rearport1, rear_port_position=1,
+            ),
+            PortMapping(
+                device=self.device, front_port=frontport1, front_port_position=2,
+                rear_port=rearport1, rear_port_position=2,
+            ),
+            PortMapping(
+                device=self.device, front_port=frontport2, front_port_position=1,
+                rear_port=rearport2, rear_port_position=1,
+            ),
+            PortMapping(
+                device=self.device, front_port=frontport3, front_port_position=1,
+                rear_port=rearport2, rear_port_position=2,
+            ),
+        ])
+
+        cable1 = Cable(a_terminations=[interface1], b_terminations=[frontport1])
+        cable1.save()
+        cable2 = Cable(a_terminations=[rearport1], b_terminations=[rearport2])
+        cable2.save()
+        cable3 = Cable(a_terminations=[frontport2], b_terminations=[interface2])
+        cable3.save()
+        cable4 = Cable(a_terminations=[frontport3], b_terminations=[interface3])
+        cable4.save()
+
+        # Reconverging on RP1 does not hide the branches diverging again at RP2
+        path1 = self.assertPathExists(
+            (
+                interface1, cable1, frontport1, rearport1, cable2, rearport2, (frontport2, frontport3),
+                (cable3, cable4), (interface2, interface3)
+            ),
+            is_complete=False,
+            is_split=True
+        )
+        self.assertEqual(path1.get_split_nodes(), [interface2, interface3])
+        interface1.refresh_from_db()
+        self.assertEqual(interface1.connected_endpoints, [])
+
     def test_301_create_path_via_existing_cable(self):
         """
         [IF1] --C1-- [FP1] [RP1] --C2-- [RP2] [FP2] --C3-- [IF2]

+ 208 - 0
netbox/dcim/tests/test_cablepaths2.py

@@ -1317,6 +1317,214 @@ class CablePathTestCase(BaseCablePathTestCase):
         self.assertEqual(interface4.cable_connector, 2)
         self.assertEqual(interface4.cable_positions, [1])
 
+    def test_111_partially_populated_breakout(self):
+        """
+        Tests that an interface on a partially populated 1C4P:4C1P breakout traces to the
+        connected legs as a complete, unsplit path, ignoring the unpopulated connector.
+
+        [IF1] --C1(1C4P:4C1P)-- [IF2]
+                                [IF3]
+                                [IF4]
+                                (connector 4 empty)
+
+        Cable profile: C1=Breakout 1C4P:4C1P, B side connectors 1-3 terminated
+        """
+        interfaces = [
+            Interface.objects.create(device=self.device, name='Interface 1'),
+            Interface.objects.create(device=self.device, name='Interface 2'),
+            Interface.objects.create(device=self.device, name='Interface 3'),
+            Interface.objects.create(device=self.device, name='Interface 4'),
+        ]
+
+        # Create cables
+        cable1 = Cable(
+            profile=CableProfileChoices.BREAKOUT_1C4P_4C1P,
+            a_terminations=[interfaces[0]],
+            b_terminations=interfaces[1:4],
+        )
+        cable1.clean()
+        cable1.save()
+
+        # Verify forward path: IF1 -> IF2, IF3, IF4 (the empty connector must not split the path)
+        path1 = self.assertPathExists(
+            (interfaces[0], cable1, interfaces[1:4]),
+            is_complete=True,
+            is_active=True,
+            is_split=False,
+        )
+
+        # Verify reverse paths: IF2, IF3, IF4 -> IF1
+        paths = [
+            self.assertPathExists(
+                (interface, cable1, interfaces[0]),
+                is_complete=True,
+                is_active=True,
+                is_split=False,
+            )
+            for interface in interfaces[1:4]
+        ]
+        self.assertEqual(CablePath.objects.count(), 4)
+        for interface in interfaces:
+            interface.refresh_from_db()
+        self.assertPathIsSet(interfaces[0], path1)
+        for interface, path in zip(interfaces[1:4], paths):
+            self.assertPathIsSet(interface, path)
+
+        # Verify cable positions
+        self.assertEqual(interfaces[0].cable_connector, 1)
+        self.assertEqual(interfaces[0].cable_positions, [1, 2, 3, 4])
+        for connector, interface in enumerate(interfaces[1:4], start=1):
+            self.assertEqual(interface.cable_connector, connector)
+            self.assertEqual(interface.cable_positions, [1])
+
+        # Test SVG generation
+        CableTraceSVG(interfaces[0]).render()
+
+        # Now attach the missing fourth leg and verify the existing path from IF1
+        # is rebuilt to include it.
+        interface5 = Interface.objects.create(device=self.device, name='Interface 5')
+        cable1.b_terminations = [*interfaces[1:4], interface5]
+        cable1.clean()
+        cable1.save()
+
+        path1 = self.assertPathExists(
+            (interfaces[0], cable1, [*interfaces[1:4], interface5]),
+            is_complete=True,
+            is_active=True,
+            is_split=False,
+        )
+        path5 = self.assertPathExists(
+            (interface5, cable1, interfaces[0]),
+            is_complete=True,
+            is_active=True,
+            is_split=False,
+        )
+        self.assertEqual(CablePath.objects.count(), 5)
+        interfaces[0].refresh_from_db()
+        interface5.refresh_from_db()
+        self.assertPathIsSet(interfaces[0], path1)
+        self.assertPathIsSet(interface5, path5)
+        self.assertEqual(interface5.cable_connector, 4)
+        self.assertEqual(interface5.cable_positions, [1])
+
+        # Detach two legs and verify the path from IF1 is rebuilt to the remaining
+        # legs, and the detached interfaces no longer have a cable or a path.
+        cable1.b_terminations = [interfaces[1], interface5]
+        cable1.clean()
+        cable1.save()
+
+        path1 = self.assertPathExists(
+            (interfaces[0], cable1, [interfaces[1], interface5]),
+            is_complete=True,
+            is_active=True,
+            is_split=False,
+        )
+        self.assertEqual(CablePath.objects.count(), 3)
+        interfaces[0].refresh_from_db()
+        self.assertPathIsSet(interfaces[0], path1)
+        for interface in interfaces[2:4]:
+            interface.refresh_from_db()
+            self.assertIsNone(interface.cable)
+            self.assertIsNone(interface._path_id)
+
+    def test_112_partially_populated_breakout_to_pass_throughs(self):
+        """
+        Tests that a partially populated 1C4P:4C1P breakout landing on front ports continues
+        the trace through the pass-throughs to the far-end interfaces, ignoring the unpopulated
+        connectors.
+
+        [IF1] --C1(1C4P:4C1P)-- [FP1][RP1] --C2-- [IF2]
+                                [FP2][RP2] --C3-- [IF3]
+                                (connectors 3-4 empty)
+
+        Cable profiles: C1=Breakout 1C4P:4C1P, C2/C3=unprofiled
+        PortMappings: FP1p1->RP1p1, FP2p1->RP2p1
+        """
+        interfaces = [
+            Interface.objects.create(device=self.device, name='Interface 1'),
+            Interface.objects.create(device=self.device, name='Interface 2'),
+            Interface.objects.create(device=self.device, name='Interface 3'),
+        ]
+        rear_ports = [
+            RearPort.objects.create(device=self.device, name='Rear Port 1', positions=1),
+            RearPort.objects.create(device=self.device, name='Rear Port 2', positions=1),
+        ]
+        front_ports = [
+            FrontPort.objects.create(device=self.device, name='Front Port 1', positions=1),
+            FrontPort.objects.create(device=self.device, name='Front Port 2', positions=1),
+        ]
+        # Panel: FP1 -> RP1, FP2 -> RP2
+        PortMapping.objects.bulk_create([
+            PortMapping(
+                device=self.device,
+                front_port=front_port,
+                front_port_position=1,
+                rear_port=rear_port,
+                rear_port_position=1,
+            )
+            for front_port, rear_port in zip(front_ports, rear_ports)
+        ])
+
+        # Create cables
+        cable1 = Cable(
+            profile=CableProfileChoices.BREAKOUT_1C4P_4C1P,
+            a_terminations=[interfaces[0]],
+            b_terminations=front_ports,
+        )
+        cable1.clean()
+        cable1.save()
+        cable2 = Cable(a_terminations=[rear_ports[0]], b_terminations=[interfaces[1]])
+        cable2.clean()
+        cable2.save()
+        cable3 = Cable(a_terminations=[rear_ports[1]], b_terminations=[interfaces[2]])
+        cable3.clean()
+        cable3.save()
+
+        # Verify forward path: IF1 -> IF2, IF3 (the empty connectors must not split the path)
+        path1 = self.assertPathExists(
+            (interfaces[0], cable1, front_ports, rear_ports, [cable2, cable3], interfaces[1:3]),
+            is_complete=True,
+            is_active=True,
+            is_split=False,
+        )
+
+        # Verify reverse paths: IF2 -> IF1, IF3 -> IF1
+        path2 = self.assertPathExists(
+            (interfaces[1], cable2, rear_ports[0], front_ports[0], cable1, interfaces[0]),
+            is_complete=True,
+            is_active=True,
+            is_split=False,
+        )
+        path3 = self.assertPathExists(
+            (interfaces[2], cable3, rear_ports[1], front_ports[1], cable1, interfaces[0]),
+            is_complete=True,
+            is_active=True,
+            is_split=False,
+        )
+        self.assertEqual(CablePath.objects.count(), 3)
+        for interface in interfaces:
+            interface.refresh_from_db()
+        self.assertPathIsSet(interfaces[0], path1)
+        self.assertPathIsSet(interfaces[1], path2)
+        self.assertPathIsSet(interfaces[2], path3)
+
+        # Verify cable positions
+        self.assertEqual(interfaces[0].cable_connector, 1)
+        self.assertEqual(interfaces[0].cable_positions, [1, 2, 3, 4])
+        for connector, front_port in enumerate(front_ports, start=1):
+            front_port.refresh_from_db()
+            self.assertEqual(front_port.cable_connector, connector)
+            self.assertEqual(front_port.cable_positions, [1])
+
+        # Verify cable positions are not set (unprofiled cables)
+        for port in (*rear_ports, interfaces[1], interfaces[2]):
+            port.refresh_from_db()
+            self.assertIsNone(port.cable_connector)
+            self.assertIsNone(port.cable_positions)
+
+        # Test SVG generation
+        CableTraceSVG(interfaces[0]).render()
+
     def test_202_single_path_via_pass_through_with_breakouts(self):
         """
         [IF1] --C1-- [FP1] [RP1] --C2-- [IF3]

+ 19 - 1
netbox/dcim/tests/test_filtersets.py

@@ -1,9 +1,10 @@
+import re
 from decimal import Decimal
 
 from django.conf import settings
 from django.contrib.contenttypes.models import ContentType
 from django.db import DEFAULT_DB_ALIAS, connection
-from django.test import TestCase
+from django.test import TestCase, tag
 
 from circuits.models import Circuit, CircuitTermination, CircuitType, Provider
 from dcim.choices import *
@@ -3487,6 +3488,23 @@ class DeviceTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
         params = {'interfaces': 'false'}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
 
+    @tag('performance', 'regression')
+    def test_interfaces_query_reads_only_interface_table(self):
+        """
+        Regression test for #23721: the interfaces filter must query the Interface table directly
+        rather than self-joining Device, which PostgreSQL can plan very poorly on large inventories.
+        """
+        for value in ('true', 'false'):
+            with self.subTest(interfaces=value):
+                sql = str(self.filterset({'interfaces': value}, self.queryset).qs.query)
+                # Device appears once, as the outer table, at any nesting depth
+                self.assertEqual(len(re.findall(r'(?:FROM|JOIN) "dcim_device"', sql)), 1)
+                if value == 'true':
+                    self.assertIn('EXISTS', sql)
+                    self.assertNotIn('NOT EXISTS', sql)
+                else:
+                    self.assertIn('NOT EXISTS', sql)
+
     def test_pass_through_ports(self):
         params = {'pass_through_ports': 'true'}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)

+ 75 - 0
netbox/dcim/tests/test_forms.py

@@ -1,6 +1,7 @@
 import tempfile
 from unittest.mock import patch
 
+import yaml
 from django import forms
 from django.template.loader import render_to_string
 from django.test import TestCase, override_settings
@@ -408,6 +409,80 @@ class ModuleTypeFormTestCase(TestCase):
                     self.assertEqual(module_type.attribute_data, {'slots': value})
 
 
+class ModuleTypeImportFormTestCase(TestCase):
+
+    @classmethod
+    def setUpTestData(cls):
+        cls.manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
+        other_manufacturer = Manufacturer.objects.create(name='Manufacturer 2', slug='manufacturer-2')
+        cls.global_type = ModuleBayType.objects.create(name='global-slot', slug='global-slot')
+        cls.manufacturer_type = ModuleBayType.objects.create(
+            manufacturer=cls.manufacturer, name='manufacturer-slot', slug='manufacturer-slot',
+        )
+        ModuleBayType.objects.create(name='manufacturer-slot', slug='manufacturer-slot')
+        cls.other_type = ModuleBayType.objects.create(
+            manufacturer=other_manufacturer, name='Other Bay', slug='other-bay',
+        )
+
+    def test_import_module_bay_types(self):
+        """Save global and manufacturer-specific bay types, preferring the latter when a name is shared."""
+        form = ModuleTypeImportForm(data={
+            'manufacturer': self.manufacturer.name,
+            'model': 'Imported Module',
+            'module_bay_types': ['global-slot', 'manufacturer-slot'],
+        })
+        self.assertTrue(form.is_valid(), form.errors)
+        module_type = form.save()
+        self.assertEqual(set(module_type.module_bay_types.all()), {self.global_type, self.manufacturer_type})
+
+    def test_invalid_module_bay_types(self):
+        """Reject names that are unknown or belong only to another manufacturer."""
+        for name in ('Unknown Bay', self.other_type.name):
+            with self.subTest(name=name):
+                form = ModuleTypeImportForm(data={
+                    'manufacturer': self.manufacturer.name,
+                    'model': 'Imported Module',
+                    'module_bay_types': [self.global_type.name, name],
+                })
+                self.assertFalse(form.is_valid())
+                self.assertEqual(form.errors.as_data()['module_bay_types'][0].code, 'invalid_choice')
+
+    def test_optional_module_bay_types(self):
+        """An omitted or empty bay type list leaves a new module type unconstrained."""
+        for extra_data in ({}, {'module_bay_types': []}):
+            with self.subTest(data=extra_data):
+                form = ModuleTypeImportForm(data={
+                    'manufacturer': self.manufacturer.name,
+                    'model': 'Imported Module',
+                    **extra_data,
+                })
+                self.assertTrue(form.is_valid(), form.errors)
+                module_type = form.save()
+                self.assertFalse(module_type.module_bay_types.exists())
+                module_type.delete()
+
+    def test_update_module_bay_types_without_manufacturer(self):
+        """Resolve bay types against the saved manufacturer when an update omits it."""
+        module_type = ModuleType.objects.create(manufacturer=self.manufacturer, model='Existing Module')
+        form = ModuleTypeImportForm(instance=module_type, data={'module_bay_types': ['manufacturer-slot']})
+        # BulkImportView removes unspecified fields when updating an existing object.
+        for name in list(form.fields):
+            if name not in form.data:
+                del form.fields[name]
+        self.assertTrue(form.is_valid(), form.errors)
+        self.assertEqual(list(form.save().module_bay_types.all()), [self.manufacturer_type])
+
+    def test_import_export_round_trip(self):
+        """Exporting and reimporting a module type preserves its bay type assignments."""
+        original = ModuleType.objects.create(manufacturer=self.manufacturer, model='Original Module')
+        original.module_bay_types.set([self.global_type, self.manufacturer_type])
+        data = yaml.safe_load(original.to_yaml())
+        data['model'] = 'Reimported Module'
+        form = ModuleTypeImportForm(data=data)
+        self.assertTrue(form.is_valid(), form.errors)
+        self.assertEqual(set(form.save().module_bay_types.all()), set(original.module_bay_types.all()))
+
+
 class ModuleTypeProfileDescriptionRenderingTestCase(TestCase):
     """
     A profile schema property's description is rendered as the attribute field's help text via the

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

@@ -59,6 +59,49 @@ class MACAddressTestCase(TestCase):
         cls.interface.primary_mac_address = cls.mac_a
         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')
     def test_clean_will_not_allow_removal_of_assigned_object_if_primary(self):
         self.mac_a.assigned_object = None
@@ -1710,6 +1753,29 @@ class DeviceBayTestCase(TestCase):
         self.assertIn('installed_device', cm.exception.message_dict)
         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):
         """
         Test that disabling a bay that already has a device installed does NOT raise an error
@@ -2988,6 +3054,20 @@ class CableTestCase(TestCase):
         self.assertEqual(interface1.link_peers, [interface2])
         self.assertEqual(interface2.link_peers, [interface1])
 
+    def test_clone_includes_color_and_length(self):
+        """
+        Cloning a cable preserves its color, length, and length unit.
+        """
+        cable = Cable.objects.first()
+        cable.color = 'ff0000'
+        cable.length = Decimal('3.50')
+        cable.length_unit = CableLengthUnitChoices.UNIT_METER
+
+        attrs = cable.clone()
+        self.assertEqual(attrs['color'], 'ff0000')
+        self.assertEqual(attrs['length'], Decimal('3.50'))
+        self.assertEqual(attrs['length_unit'], CableLengthUnitChoices.UNIT_METER)
+
     def test_cable_deletion(self):
         """
         When a Cable is deleted, the `cable` field on its termination points must be nullified. The str() method
@@ -3837,6 +3917,65 @@ class CableDisconnectChangeLoggingTestCase(TestCase):
             action=ObjectChangeActionChoices.ACTION_UPDATE,
         ).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
     def test_cable_deletion_records_disconnect(self):
         cable = self._connect(self.interface1, self.interface2)
@@ -3914,6 +4053,7 @@ class CableDisconnectChangeLoggingTestCase(TestCase):
         request = self._request()
         with event_tracking(request):
             cable = Cable.objects.get(pk=cable_pk)
+            cable.snapshot()
             cable.b_terminations = [self.interface3]
             cable.save()
 
@@ -4548,6 +4688,57 @@ class VCPositionTokenTestCase(TestCase):
         self.assertEqual(mapping.front_port_position, 1)
         self.assertEqual(mapping.rear_port_position, 1)
 
+    @tag('regression')  # Ref: #23493
+    def test_vc_position_token_inventory_item_component_device_type_template(self):
+        site = Site.objects.first()
+        device_type = DeviceType.objects.first()
+        device_role = DeviceRole.objects.first()
+
+        interface_template = InterfaceTemplate.objects.create(
+            device_type=device_type,
+            name='eth{vc_position}',
+            type='1000base-t',
+        )
+        InventoryItemTemplate.objects.create(
+            device_type=device_type,
+            name='NIC',
+            component=interface_template,
+        )
+        vc = VirtualChassis.objects.create(name='Test VC 7')
+        device = Device.objects.create(
+            name='Device VC 7', device_type=device_type, role=device_role,
+            site=site, virtual_chassis=vc, vc_position=7,
+        )
+
+        inventory_item = device.inventoryitems.get(name='NIC')
+        self.assertEqual(inventory_item.component, device.interfaces.get(name='eth7'))
+
+    @tag('regression')  # Ref: #23747
+    def test_vc_position_token_interface_parent_device_type_template(self):
+        site = Site.objects.first()
+        device_type = DeviceType.objects.first()
+        device_role = DeviceRole.objects.first()
+
+        parent_template = InterfaceTemplate.objects.create(
+            device_type=device_type,
+            name='eth{vc_position}',
+            type='1000base-t',
+        )
+        InterfaceTemplate.objects.create(
+            device_type=device_type,
+            name='eth{vc_position}.100',
+            type='virtual',
+            parent=parent_template,
+        )
+        vc = VirtualChassis.objects.create(name='Test VC 8')
+        device = Device.objects.create(
+            name='Device VC 8', device_type=device_type, role=device_role,
+            site=site, virtual_chassis=vc, vc_position=8,
+        )
+
+        interface = device.interfaces.get(name='eth8.100')
+        self.assertEqual(interface.parent, device.interfaces.get(name='eth8'))
+
 
 class SiteSignalTestCase(TestCase):
 

+ 245 - 1
netbox/dcim/tests/test_tables.py

@@ -1,3 +1,5 @@
+from django.test import tag
+
 from dcim.choices import CableEndChoices, CableProfileChoices, InterfaceTypeChoices
 from dcim.models import (
     Cable,
@@ -5,13 +7,19 @@ from dcim.models import (
     Device,
     DeviceRole,
     DeviceType,
+    FrontPort,
+    FrontPortTemplate,
     Interface,
     Manufacturer,
+    PortMapping,
+    PortTemplateMapping,
     PowerPort,
+    RearPort,
+    RearPortTemplate,
     Site,
 )
 from dcim.tables import *
-from utilities.testing import TableTestCases
+from utilities.testing import TableTestCases, create_test_device
 
 #
 # Sites
@@ -70,6 +78,132 @@ class DeviceTypeTableTestCase(TableTestCases.StandardTableTestCase):
     table = DeviceTypeTable
 
 
+class FrontPortTemplateTableTestCase(TableTestCases.StandardTableTestCase):
+    table = FrontPortTemplateTable
+    queryset_sources = [
+        ('DeviceTypeFrontPortsView', FrontPortTemplate.objects.all()),
+    ]
+
+    @classmethod
+    def setUpTestData(cls):
+        manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
+        device_type = DeviceType.objects.create(manufacturer=manufacturer, model='Device Type 1', slug='device-type-1')
+        rear_ports = (
+            RearPortTemplate(device_type=device_type, name='Rear Port 1'),
+            RearPortTemplate(device_type=device_type, name='Rear Port 2'),
+            RearPortTemplate(device_type=device_type, name='Rear Port 3'),
+        )
+        RearPortTemplate.objects.bulk_create(rear_ports)
+        front_ports = (
+            FrontPortTemplate(device_type=device_type, name='Front Port 1'),
+            FrontPortTemplate(device_type=device_type, name='Front Port 2'),
+            FrontPortTemplate(device_type=device_type, name='Front Port 3'),
+        )
+        FrontPortTemplate.objects.bulk_create(front_ports)
+        PortTemplateMapping.objects.bulk_create((
+            PortTemplateMapping(device_type=device_type, front_port=front_ports[0], rear_port=rear_ports[0]),
+            PortTemplateMapping(device_type=device_type, front_port=front_ports[1], rear_port=rear_ports[1]),
+        ))
+
+    @tag('regression')  # Ref: #23349
+    def test_mappings_column(self):
+        """The mappings column lists the rear port of each mapping without further queries."""
+        table = FrontPortTemplateTable(FrontPortTemplate.objects.all())
+        table.configure(self.get_request())
+        rows = list(table.rows)
+
+        with self.assertNumQueries(0):
+            cells = {row.record.name: row.get_cell('mappings') for row in rows}
+
+        self.assertEqual(cells, {
+            'Front Port 1': 'Rear Port 1:1',
+            'Front Port 2': 'Rear Port 2:1',
+            'Front Port 3': table.columns['mappings'].default,
+        })
+
+    @tag('regression')  # Ref: #23349
+    def test_mappings_export(self):
+        """An export lists the rear port of each mapping without further queries."""
+        self.user.config.set('tables.FrontPortTemplateTable.columns', ['name'], commit=True)
+        table = FrontPortTemplateTable(FrontPortTemplate.objects.all())
+        table.configure(self.get_request())
+        # An "All Data" export prefetches for every column, hidden or not
+        table._apply_prefetching(columns=table.columns.names())
+        rows = list(table.rows)
+
+        with self.assertNumQueries(0):
+            values = {row.record.name: row.get_cell_value('mappings') for row in rows}
+
+        self.assertEqual(values, {
+            'Front Port 1': 'Rear Port 1:1',
+            'Front Port 2': 'Rear Port 2:1',
+            'Front Port 3': None,
+        })
+
+
+class RearPortTemplateTableTestCase(TableTestCases.StandardTableTestCase):
+    table = RearPortTemplateTable
+    queryset_sources = [
+        ('DeviceTypeRearPortsView', RearPortTemplate.objects.all()),
+    ]
+
+    @classmethod
+    def setUpTestData(cls):
+        manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
+        device_type = DeviceType.objects.create(manufacturer=manufacturer, model='Device Type 1', slug='device-type-1')
+        rear_ports = (
+            RearPortTemplate(device_type=device_type, name='Rear Port 1'),
+            RearPortTemplate(device_type=device_type, name='Rear Port 2'),
+            RearPortTemplate(device_type=device_type, name='Rear Port 3'),
+        )
+        RearPortTemplate.objects.bulk_create(rear_ports)
+        front_ports = (
+            FrontPortTemplate(device_type=device_type, name='Front Port 1'),
+            FrontPortTemplate(device_type=device_type, name='Front Port 2'),
+            FrontPortTemplate(device_type=device_type, name='Front Port 3'),
+        )
+        FrontPortTemplate.objects.bulk_create(front_ports)
+        PortTemplateMapping.objects.bulk_create((
+            PortTemplateMapping(device_type=device_type, front_port=front_ports[0], rear_port=rear_ports[0]),
+            PortTemplateMapping(device_type=device_type, front_port=front_ports[1], rear_port=rear_ports[1]),
+        ))
+
+    @tag('regression')  # Ref: #23349
+    def test_mappings_column(self):
+        """The mappings column lists the front port of each mapping without further queries."""
+        table = RearPortTemplateTable(RearPortTemplate.objects.all())
+        table.configure(self.get_request())
+        rows = list(table.rows)
+
+        with self.assertNumQueries(0):
+            cells = {row.record.name: row.get_cell('mappings') for row in rows}
+
+        self.assertEqual(cells, {
+            'Rear Port 1': 'Front Port 1:1',
+            'Rear Port 2': 'Front Port 2:1',
+            'Rear Port 3': table.columns['mappings'].default,
+        })
+
+    @tag('regression')  # Ref: #23349
+    def test_mappings_export(self):
+        """An export lists the front port of each mapping without further queries."""
+        self.user.config.set('tables.RearPortTemplateTable.columns', ['name'], commit=True)
+        table = RearPortTemplateTable(RearPortTemplate.objects.all())
+        table.configure(self.get_request())
+        # An "All Data" export prefetches for every column, hidden or not
+        table._apply_prefetching(columns=table.columns.names())
+        rows = list(table.rows)
+
+        with self.assertNumQueries(0):
+            values = {row.record.name: row.get_cell_value('mappings') for row in rows}
+
+        self.assertEqual(values, {
+            'Rear Port 1': 'Front Port 1:1',
+            'Rear Port 2': 'Front Port 2:1',
+            'Rear Port 3': None,
+        })
+
+
 #
 # Module types
 #
@@ -136,10 +270,120 @@ class InterfaceTableTestCase(TableTestCases.StandardTableTestCase):
 class FrontPortTableTestCase(TableTestCases.StandardTableTestCase):
     table = FrontPortTable
 
+    @classmethod
+    def setUpTestData(cls):
+        device = create_test_device('Device 1')
+        rear_ports = (
+            RearPort(device=device, name='Rear Port 1'),
+            RearPort(device=device, name='Rear Port 2'),
+            RearPort(device=device, name='Rear Port 3'),
+        )
+        RearPort.objects.bulk_create(rear_ports)
+        front_ports = (
+            FrontPort(device=device, name='Front Port 1'),
+            FrontPort(device=device, name='Front Port 2'),
+            FrontPort(device=device, name='Front Port 3'),
+        )
+        FrontPort.objects.bulk_create(front_ports)
+        PortMapping.objects.bulk_create((
+            PortMapping(device=device, front_port=front_ports[0], rear_port=rear_ports[0]),
+            PortMapping(device=device, front_port=front_ports[1], rear_port=rear_ports[1]),
+        ))
+
+    @tag('regression')  # Ref: #23349
+    def test_mappings_column(self):
+        """The mappings column lists the rear port of each mapping without further queries."""
+        table = FrontPortTable(FrontPort.objects.all())
+        table.configure(self.get_request())
+        rows = list(table.rows)
+
+        with self.assertNumQueries(0):
+            cells = {row.record.name: row.get_cell('mappings') for row in rows}
+
+        self.assertEqual(cells, {
+            'Front Port 1': 'Rear Port 1:1',
+            'Front Port 2': 'Rear Port 2:1',
+            'Front Port 3': table.columns['mappings'].default,
+        })
+
+    @tag('regression')  # Ref: #23349
+    def test_mappings_export(self):
+        """An export lists the rear port of each mapping without further queries."""
+        self.user.config.set('tables.FrontPortTable.columns', ['name'], commit=True)
+        table = FrontPortTable(FrontPort.objects.all())
+        table.configure(self.get_request())
+        # An "All Data" export prefetches for every column, hidden or not
+        table._apply_prefetching(columns=table.columns.names())
+        rows = list(table.rows)
+
+        with self.assertNumQueries(0):
+            values = {row.record.name: row.get_cell_value('mappings') for row in rows}
+
+        self.assertEqual(values, {
+            'Front Port 1': 'Rear Port 1:1',
+            'Front Port 2': 'Rear Port 2:1',
+            'Front Port 3': None,
+        })
+
 
 class RearPortTableTestCase(TableTestCases.StandardTableTestCase):
     table = RearPortTable
 
+    @classmethod
+    def setUpTestData(cls):
+        device = create_test_device('Device 1')
+        rear_ports = (
+            RearPort(device=device, name='Rear Port 1'),
+            RearPort(device=device, name='Rear Port 2'),
+            RearPort(device=device, name='Rear Port 3'),
+        )
+        RearPort.objects.bulk_create(rear_ports)
+        front_ports = (
+            FrontPort(device=device, name='Front Port 1'),
+            FrontPort(device=device, name='Front Port 2'),
+            FrontPort(device=device, name='Front Port 3'),
+        )
+        FrontPort.objects.bulk_create(front_ports)
+        PortMapping.objects.bulk_create((
+            PortMapping(device=device, front_port=front_ports[0], rear_port=rear_ports[0]),
+            PortMapping(device=device, front_port=front_ports[1], rear_port=rear_ports[1]),
+        ))
+
+    @tag('regression')  # Ref: #23349
+    def test_mappings_column(self):
+        """The mappings column lists the front port of each mapping without further queries."""
+        table = RearPortTable(RearPort.objects.all())
+        table.configure(self.get_request())
+        rows = list(table.rows)
+
+        with self.assertNumQueries(0):
+            cells = {row.record.name: row.get_cell('mappings') for row in rows}
+
+        self.assertEqual(cells, {
+            'Rear Port 1': 'Front Port 1:1',
+            'Rear Port 2': 'Front Port 2:1',
+            'Rear Port 3': table.columns['mappings'].default,
+        })
+
+    @tag('regression')  # Ref: #23349
+    def test_mappings_export(self):
+        """An export lists the front port of each mapping without further queries."""
+        self.user.config.set('tables.RearPortTable.columns', ['name'], commit=True)
+        table = RearPortTable(RearPort.objects.all())
+        table.configure(self.get_request())
+        # An "All Data" export prefetches for every column, hidden or not
+        table._apply_prefetching(columns=table.columns.names())
+        rows = list(table.rows)
+
+        with self.assertNumQueries(0):
+            values = {row.record.name: row.get_cell_value('mappings') for row in rows}
+
+        self.assertEqual(values, {
+            'Rear Port 1': 'Front Port 1:1',
+            'Rear Port 2': 'Front Port 2:1',
+            'Rear Port 3': None,
+        })
+
 
 class ModuleBayTableTestCase(TableTestCases.StandardTableTestCase):
     table = ModuleBayTable

+ 164 - 3
netbox/dcim/tests/test_views.py

@@ -5,18 +5,19 @@ import tempfile
 from decimal import Decimal
 from io import StringIO
 from unittest.mock import patch
-from urllib.parse import quote
+from urllib.parse import quote, urlencode
 from zoneinfo import ZoneInfo
 
 import yaml
 from django.contrib.contenttypes.models import ContentType
-from django.contrib.messages import get_messages
+from django.contrib.messages import WARNING, get_messages
 from django.db import connection
 from django.http import QueryDict, StreamingHttpResponse
 from django.templatetags.static import static
 from django.test import override_settings, tag
 from django.test.utils import CaptureQueriesContext
 from django.urls import reverse
+from django.utils.html import escape
 from netaddr import EUI
 
 from core.choices import ObjectChangeActionChoices
@@ -24,6 +25,7 @@ from core.models import ObjectChange, ObjectType
 from dcim.choices import *
 from dcim.constants import *
 from dcim.models import *
+from dcim.views import ModuleTypeImportView
 from extras.models import ConfigContext, ConfigTemplate
 from ipam.models import ASN, RIR, VLAN, VRF, IPAddress, VLANGroup
 from netbox.choices import (
@@ -36,6 +38,7 @@ from netbox.choices import (
 from netbox.exporters import get_exporter
 from tenancy.models import Tenant
 from users.models import ObjectPermission, Owner, User
+from utilities.exceptions import PermissionsViolation
 from utilities.testing import ViewTestCases, create_tags, create_test_device, create_test_image, post_data
 from wireless.models import WirelessLAN
 
@@ -1869,6 +1872,81 @@ class ModuleTypeTestCase(ViewTestCases.PrimaryObjectViewTestCase):
         url = reverse('dcim:moduletype_frontports', kwargs={'pk': moduletype.pk})
         self.assertHttpStatus(self.client.get(url), 200)
 
+    def test_import_module_bay_types(self):
+        """YAML and JSON imports save global bay types and prefer manufacturer-specific matches for shared names."""
+        manufacturer = Manufacturer.objects.first()
+        global_type = ModuleBayType.objects.create(name='global-slot', slug='global-slot')
+        manufacturer_type = ModuleBayType.objects.create(
+            manufacturer=manufacturer, name='manufacturer-slot', slug='manufacturer-slot',
+        )
+        ModuleBayType.objects.create(name='manufacturer-slot', slug='manufacturer-slot')
+        self.add_permissions(
+            'dcim.view_manufacturer',
+            'dcim.view_modulebaytype',
+            'dcim.view_moduletype',
+            'dcim.add_moduletype',
+            'dcim.add_consoleporttemplate',
+            'dcim.add_consoleserverporttemplate',
+            'dcim.add_powerporttemplate',
+            'dcim.add_poweroutlettemplate',
+            'dcim.add_coolingintaketemplate',
+            'dcim.add_coolingoutflowtemplate',
+            'dcim.add_interfacetemplate',
+            'dcim.add_frontporttemplate',
+            'dcim.add_rearporttemplate',
+            'dcim.add_modulebaytemplate',
+        )
+
+        data = {
+            'manufacturer': manufacturer.name,
+            'model': 'Imported Transceiver',
+            'module_bay_types': ['global-slot', 'manufacturer-slot'],
+        }
+        for format_, serialized in (('yaml', yaml.safe_dump(data)), ('json', json.dumps(data))):
+            with self.subTest(format=format_):
+                response = self.client.post(reverse('dcim:moduletype_bulk_import'), data={
+                    'data': serialized,
+                    'format': format_,
+                })
+                self.assertHttpStatus(response, 302)
+                module_type = ModuleType.objects.get(model=data['model'])
+                self.assertEqual(set(module_type.module_bay_types.all()), {global_type, manufacturer_type})
+                module_type.delete()
+
+    def test_import_update_warns_about_incompatible_installed_modules(self):
+        """An import can restrict an existing module type and gives a warning (doesn't remove installed modules)."""
+        self.add_permissions(
+            *ModuleTypeImportView.additional_permissions,
+            'dcim.change_moduletype',
+            'dcim.view_modulebaytype',
+        )
+        module_type = ModuleType.objects.get(model='Module Type 2')
+        device = create_test_device('Device 1')
+        allowed_type = ModuleBayType.objects.create(name='Allowed Slot', slug='allowed-slot')
+        other_type = ModuleBayType.objects.create(name='Other Slot', slug='other-slot')
+        compatible_bay = ModuleBay.objects.create(device=device, name='Compatible Bay')
+        compatible_bay.module_bay_types.add(allowed_type)
+        incompatible_bay = ModuleBay.objects.create(device=device, name='Incompatible Bay')
+        incompatible_bay.module_bay_types.add(other_type)
+
+        # Install modules with no bay type constraints in bays with differing bay type constraints.
+        Module.objects.create(device=device, module_bay=compatible_bay, module_type=module_type)
+        installed_module = Module.objects.create(device=device, module_bay=incompatible_bay, module_type=module_type)
+
+        response = self.client.post(reverse('dcim:moduletype_bulk_import'), data={
+            'data': yaml.safe_dump({'id': module_type.pk, 'module_bay_types': [allowed_type.name]}),
+            'format': 'yaml',
+        })
+
+        self.assertHttpStatus(response, 302)
+        self.assertEqual(list(module_type.module_bay_types.all()), [allowed_type])
+        installed_module.refresh_from_db()
+        self.assertEqual(installed_module.module_bay_id, incompatible_bay.pk)
+        self.assertEqual(
+            [str(message) for message in get_messages(response.wsgi_request) if message.level == WARNING],
+            ['1 installed module is incompatible with its module bay due to conflicting bay type constraints.'],
+        )
+
     def test_import_objects(self):
         """
         Custom import test for YAML-based imports (versus CSV)
@@ -4390,6 +4468,23 @@ class InterfaceTestCase(ViewTestCases.DeviceComponentViewTestCase):
         response = self.client.get(reverse('dcim:interface_trace', kwargs={'pk': interface1.pk}))
         self.assertHttpStatus(response, 200)
 
+    @tag('regression')  # Issue #23711
+    def test_ip_addresses_panel_add_action(self):
+        """
+        The interface's IP addresses panel links to add an IP address assigned to the interface.
+        """
+        self.add_permissions('dcim.view_interface', 'ipam.view_ipaddress', 'ipam.add_ipaddress')
+        interface = Interface.objects.first()
+        url_params = urlencode({
+            'device': interface.device.pk,
+            'interface': interface.pk,
+            'return_url': interface.get_absolute_url(),
+        })
+
+        response = self.client.get(interface.get_absolute_url())
+        self.assertHttpStatus(response, 200)
+        self.assertContains(response, escape(f"{reverse('ipam:ipaddress_add')}?{url_params}"))
+
     def test_bulk_delete_child_interfaces(self):
         interface1 = Interface.objects.get(name='Interface 1')
         device = interface1.device
@@ -5985,7 +6080,7 @@ class VirtualChassisTestCase(ViewTestCases.PrimaryObjectViewTestCase):
 
     @tag('regression')  # Ref: #23212
     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')
         device = Device.objects.get(name='Device 10')
         lag = Interface.objects.create(device=vc1_member, name='lag0', type=InterfaceTypeChoices.TYPE_LAG)
@@ -6001,6 +6096,72 @@ class VirtualChassisTestCase(ViewTestCases.PrimaryObjectViewTestCase):
         self.assertIsNone(device.virtual_chassis)
         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
     def test_create_with_members_blocked_by_cross_chassis_lag(self):
         self.add_permissions('dcim.add_virtualchassis', 'dcim.view_device')

+ 5 - 2
netbox/dcim/utils.py

@@ -482,11 +482,14 @@ def update_interface_parents(device, interface_templates, module=None):
     Interface = apps.get_model('dcim', 'Interface')
 
     for interface_template in interface_templates.exclude(parent=None):
-        interface = Interface.objects.get(device=device, name=interface_template.resolve_name(module=module))
+        interface = Interface.objects.get(
+            device=device,
+            name=interface_template.resolve_name(module=module, device=device)
+        )
         interface.snapshot()
         interface.parent = Interface.objects.get(
             device=device,
-            name=interface_template.parent.resolve_name(module=module)
+            name=interface_template.parent.resolve_name(module=module, device=device)
         )
         interface.full_clean()
         interface.save()

+ 60 - 11
netbox/dcim/views.py

@@ -15,6 +15,7 @@ from django.utils.translation import ngettext
 from django.views.generic import View
 
 from circuits.models import Circuit, CircuitTermination
+from core.signals import clear_events
 from extras.ui.panels import CustomFieldsPanel, ImageAttachmentsPanel, TagsPanel
 from extras.views import ObjectConfigContextView, ObjectRenderConfigView
 from ipam.models import ASN, VLAN, IPAddress, Prefix, VLANGroup
@@ -34,7 +35,9 @@ from netbox.ui.panels import (
     TemplatePanel,
 )
 from netbox.views import generic
-from utilities.forms import ConfirmationForm
+from utilities.exceptions import PermissionsViolation
+from utilities.forms import ConfirmationForm, restrict_form_fields
+from utilities.jobs import is_background_request
 from utilities.paginator import EnhancedPaginator, get_paginate_count
 from utilities.permissions import get_permission_for_model
 from utilities.query import count_related
@@ -2167,6 +2170,30 @@ class ModuleTypeImportView(generic.BulkImportView):
         data.update({'module_type': parent})
         return data
 
+    def save_object(self, object_form, request):
+        check_compatibility = object_form.instance.pk and 'module_bay_types' in object_form.cleaned_data
+        module_type = super().save_object(object_form, request)
+        if check_compatibility:
+            self._incompatible_count += module_type.get_incompatible_modules().count()
+        return module_type
+
+    def post(self, request):
+        self._incompatible_count = 0
+        response = super().post(request)
+        if self._incompatible_count and (response is None or response.status_code == 302):
+            warning = ngettext(
+                '%(count)d installed module is incompatible with its module bay '
+                'due to conflicting bay type constraints.',
+                '%(count)d installed modules are incompatible with their module bays '
+                'due to conflicting bay type constraints.',
+                self._incompatible_count,
+            ) % {'count': self._incompatible_count}
+            if is_background_request(request):
+                request.job.logger.warning(warning)
+            else:
+                messages.warning(request, warning)
+        return response
+
 
 @register_model_view(ModuleType, 'bulk_edit', path='edit', detail=False)
 class ModuleTypeBulkEditView(generic.BulkEditView):
@@ -3971,6 +3998,15 @@ class InterfaceView(generic.ObjectView):
                 filters={'interface_id': lambda ctx: ctx['object'].pk},
                 title=_('IP Addresses'),
                 exclude_columns=['assigned', 'assigned_object', 'assigned_object_parent'],
+                actions=[
+                    actions.AddObject(
+                        'ipam.IPAddress',
+                        url_params={
+                            'device': lambda ctx: ctx['object'].device.pk,
+                            'interface': lambda ctx: ctx['object'].pk,
+                        },
+                    ),
+                ],
             ),
             ObjectsTablePanel(
                 model='dcim.MACAddress',
@@ -5270,6 +5306,7 @@ class VirtualChassisAddMemberView(ObjectPermissionRequiredMixin, GetReturnURLMix
         virtual_chassis = get_object_or_404(self.queryset, pk=pk)
         initial_data = {k: request.GET[k] for k in request.GET}
         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)
 
         return render(request, 'dcim/virtualchassis_add_member.html', {
@@ -5282,6 +5319,7 @@ class VirtualChassisAddMemberView(ObjectPermissionRequiredMixin, GetReturnURLMix
     def post(self, request, pk):
         virtual_chassis = get_object_or_404(self.queryset, pk=pk)
         member_select_form = forms.VCMemberSelectForm(request.POST)
+        restrict_form_fields(member_select_form, request.user, action='change')
 
         if member_select_form.is_valid():
             device = member_select_form.cleaned_data['device']
@@ -5301,16 +5339,27 @@ class VirtualChassisAddMemberView(ObjectPermissionRequiredMixin, GetReturnURLMix
                 membership_form.add_error(None, e.messages)
 
             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:
             membership_form = forms.DeviceVCMembershipForm(data=request.POST)

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

@@ -1,6 +1,6 @@
 from django import forms
 from django.urls import reverse_lazy
-from django.utils.translation import gettext as _
+from django.utils.translation import gettext_lazy as _
 
 from extras.choices import DashboardWidgetColorChoices
 from netbox.registry import registry

+ 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 extras.constants import DEFAULT_DASHBOARD
+from netbox.config import get_config
 from netbox.registry import registry
 
 __all__ = (
@@ -46,10 +47,11 @@ def get_dashboard(user):
         try:
             dashboard = user.dashboard
         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.user = user
-            dashboard.save()
+            if not get_config().MAINTENANCE_MODE:
+                dashboard.save()
 
     return dashboard
 

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

@@ -302,7 +302,7 @@ class EventRuleBulkEditForm(OwnerMixin, NetBoxModelBulkEditForm):
         widget=BulkEditNullBooleanSelect()
     )
     event_types = forms.MultipleChoiceField(
-        choices=get_event_type_choices(),
+        choices=get_event_type_choices,
         required=False,
         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")
     )
     event_types = CSVMultipleChoiceField(
-        choices=get_event_type_choices(),
         label=_('Event types'),
         help_text=_('The event type(s) which will trigger this rule')
     )
@@ -337,6 +336,11 @@ class EventRuleImportForm(OwnerCSVMixin, NetBoxModelImportForm):
             '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):
         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'),
     )
     event_types = MultipleChoiceField(
-        choices=get_event_type_choices(),
+        choices=get_event_type_choices,
         label=_('Event types')
     )
     action_choice = ChoiceField(

+ 10 - 0
netbox/extras/models/customfields.py

@@ -821,6 +821,16 @@ class CustomField(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedMo
                 raise ValidationError({
                     'related_object_filter': _("Filter must be defined as a dictionary mapping attributes to values.")
                 })
+            # Each value must be a scalar or a list of scalars (rendered as query parameters)
+            for attr, value in self.related_object_filter.items():
+                values = value if isinstance(value, (list, tuple)) else [value]
+                if any(isinstance(v, (dict, list, tuple)) for v in values):
+                    raise ValidationError({
+                        'related_object_filter': _(
+                            "Invalid value for filter attribute '{attr}': values must be a scalar or a list of "
+                            "scalars."
+                        ).format(attr=attr)
+                    })
 
     def serialize(self, value):
         """

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

@@ -287,7 +287,8 @@ class Webhook(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, OwnerMixin, Ch
         blank=True,
         verbose_name=_('CA File Path'),
         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(

+ 1 - 1
netbox/extras/tables/columns.py

@@ -1,6 +1,6 @@
 import django_tables2 as tables
 from django.utils.html import format_html
-from django.utils.translation import gettext as _
+from django.utils.translation import gettext_lazy as _
 
 from extras.choices import CustomFieldStatusChoices
 from netbox.tables.columns import ActionsColumn, ActionsItem

+ 3 - 0
netbox/extras/tables/tables.py

@@ -778,6 +778,9 @@ class JournalEntryTable(NetBoxTable):
         timespec='minutes',
         linkify=True
     )
+    created_by = tables.Column(
+        verbose_name=_('Created by')
+    )
     assigned_object_type = columns.ContentTypeColumn(
         verbose_name=_('Object Type')
     )

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

@@ -1112,6 +1112,43 @@ class CustomFieldTestCase(TestCase):
                 validation_schema=schema, default={'age': 25}
             ).full_clean()
 
+    def test_related_object_filter_validation(self):
+        object_type = ObjectType.objects.get_for_model(Site)
+
+        valid_filters = (
+            {'status': 'active'},
+            {'status': ['active', 'planned']},
+            {'id': 1, 'is_active': True, 'tenant': None, 'region_id': '$region'},
+            {'vid': [1, 2.5, False, None]},
+        )
+        for related_object_filter in valid_filters:
+            with self.subTest(related_object_filter=related_object_filter):
+                CustomField(
+                    name='test',
+                    type=CustomFieldTypeChoices.TYPE_OBJECT,
+                    related_object_type=object_type,
+                    related_object_filter=related_object_filter,
+                ).full_clean()
+
+        # Nested dicts/lists cannot be rendered as query parameters (#23635)
+        invalid_filters = (
+            {'and': [{'attr': 'name', 'value': 'a'}, {'attr': 'rd', 'value': 'b'}]},
+            {'status': {'value': 'active'}},
+            {'status': [['active']]},
+            {'status': ('active', ['planned'])},
+            {'status': ['active', ('planned',)]},
+        )
+        for related_object_filter in invalid_filters:
+            with self.subTest(related_object_filter=related_object_filter):
+                with self.assertRaises(ValidationError) as cm:
+                    CustomField(
+                        name='test',
+                        type=CustomFieldTypeChoices.TYPE_MULTIOBJECT,
+                        related_object_type=object_type,
+                        related_object_filter=related_object_filter,
+                    ).full_clean()
+                self.assertIn('related_object_filter', cm.exception.message_dict)
+
 
 class CustomFieldManagerTestCase(TestCase):
 

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

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

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

@@ -116,6 +116,8 @@ class CustomFieldTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
         params = {'object_type_id': [ObjectType.objects.get_by_natural_key('dcim', 'site').pk]}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+        params = {'object_type__n': ['dcim.site']}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 5)
 
     def test_related_object_type(self):
         params = {'related_object_type': ['dcim.site']}

+ 72 - 2
netbox/extras/tests/test_forms.py

@@ -9,15 +9,27 @@ from core.choices import ManagedFileRootPathChoices
 from core.events import OBJECT_CREATED
 from core.models import DataSource, ObjectType
 from dcim.forms import SiteForm
+from dcim.forms.filtersets import PowerOutletFilterForm
 from dcim.models import Site
 from extras.choices import CustomFieldTypeChoices, EventRuleActionChoices
 from extras.forms import SavedFilterForm, TableConfigBulkEditForm, TableConfigForm
+from extras.forms.bulk_edit import EventRuleBulkEditForm
 from extras.forms.bulk_import import EventRuleImportForm
 from extras.forms.filtersets import EventRuleFilterForm
-from extras.forms.model_forms import CustomFieldChoiceSetForm, EventRuleForm
+from extras.forms.model_forms import CustomFieldChoiceSetForm, EventRuleForm, TagForm
 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,
+    Tag,
+    Webhook,
+)
 from netbox.event_rules import EventRuleAction, register_event_rule_action
+from netbox.events import EventType
 from netbox.registry import registry
 from utilities.forms.widgets import HTMXSelect
 
@@ -522,6 +534,41 @@ class EventRuleFilterFormTestCase(TestCase):
         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):
     """
     EventRuleImportForm resolves action_object via each registered action's resolve_import_object()
@@ -693,3 +740,26 @@ class EventRuleImportFormTestCase(TestCase):
         self.assertFalse(form.is_valid())
         self.assertIn(NON_FIELD_ERRORS, form.errors)
         self.assertIn('Bad action_data for test', form.errors[NON_FIELD_ERRORS])
+
+
+class TagFormTestCase(TestCase):
+
+    def test_edit_tag_with_custom_color(self):
+        """
+        A Tag with a color outside the predefined ColorChoices can be edited without losing its color.
+        """
+        tag = Tag.objects.create(name='Tag 1', slug='tag-1', color='e20074')
+
+        # The current color must be rendered as the selected option
+        form = TagForm(instance=tag)
+        self.assertInHTML(
+            '<option value="e20074" selected>e20074</option>',
+            str(form['color'])
+        )
+
+    def test_filter_form_ignores_invalid_color(self):
+        """
+        A non-hex color passed to a filter form must not be rendered as an option.
+        """
+        form = PowerOutletFilterForm(data={'color': 'ff0000;background:url(x)'})
+        self.assertNotIn('background:url', str(form['color']))

+ 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.
         request = _build_request(user=self.user)
         with event_tracking(request):
+            site.snapshot()
             site.description = 'first'
             site.save()
+            site.snapshot()
             site.description = 'second'
             site.save()
 

+ 10 - 2
netbox/extras/tests/test_tables.py

@@ -1,10 +1,12 @@
-from django.test import TestCase
+from django.test import TestCase, tag
+from django.utils import translation
+from django.utils.translation import gettext
 
 from core.events import OBJECT_CREATED
 from core.models import ObjectType
 from dcim.models import Site
 from extras.choices import CustomFieldStatusChoices, CustomFieldTypeChoices
-from extras.models import Bookmark, CustomField, EventRule, Notification, Subscription
+from extras.models import Bookmark, CustomField, EventRule, JournalEntry, Notification, Subscription
 from extras.tables import *
 from utilities.testing import TableTestCases
 
@@ -190,3 +192,9 @@ class ImageAttachmentTableTestCase(TableTestCases.StandardTableTestCase):
 
 class JournalEntryTableTestCase(TableTestCases.StandardTableTestCase):
     table = JournalEntryTable
+
+    @tag('regression')  # Ref: #23753
+    def test_created_by_header_translated(self):
+        with translation.override('nl'):
+            table = JournalEntryTable(JournalEntry.objects.none())
+            self.assertEqual(table.columns['created_by'].header, gettext('Created by'))

+ 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.scripts import prepare_script_form
 from extras.utils import SharedObjectViewMixin
+from netbox.config import get_config
 from netbox.object_actions import *
 from netbox.ui import layout
 from netbox.ui.panels import (
@@ -649,8 +650,9 @@ class NotificationReadView(LoginRequiredMixin, View):
     def get(self, request, pk):
         # Mark the Notification as read
         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)
         if hasattr(notification.object, 'get_absolute_url'):

+ 1 - 1
netbox/ipam/api/serializers_/services.py

@@ -1,6 +1,6 @@
 from django.contrib.contenttypes.models import ContentType
 from django.core.exceptions import ValidationError as DjangoValidationError
-from django.utils.translation import gettext as _
+from django.utils.translation import gettext_lazy as _
 from rest_framework import serializers
 
 from ipam.choices import *

+ 4 - 8
netbox/ipam/forms/bulk_import.py

@@ -241,14 +241,10 @@ class PrefixImportForm(ScopedImportForm, PrimaryModelImportForm):
         query = Q()
 
         if vlan_site:
-            query |= Q(**{
-                f"site__{self.fields['vlan_site'].to_field_name}": vlan_site
-            })
+            query |= Q(**self.get_related_filter('site', 'vlan_site', vlan_site))
 
         if vlan_group:
-            query &= Q(**{
-                f"group__{self.fields['vlan_group'].to_field_name}": vlan_group
-            })
+            query &= Q(**self.get_related_filter('group', 'vlan_group', vlan_group))
 
         queryset = self.fields['vlan'].queryset.filter(query)
         self.fields['vlan'].queryset = queryset
@@ -370,13 +366,13 @@ class IPAddressImportForm(PrimaryModelImportForm):
             # Limit interface queryset by assigned device
             if data.get('device'):
                 self.fields['interface'].queryset = Interface.objects.filter(
-                    **{f"device__{self.fields['device'].to_field_name}": data['device']}
+                    **self.get_related_filter('device', 'device', data['device'])
                 )
 
             # Limit interface queryset by assigned VM
             elif data.get('virtual_machine'):
                 self.fields['interface'].queryset = VMInterface.objects.filter(
-                    **{f"virtual_machine__{self.fields['virtual_machine'].to_field_name}": data['virtual_machine']}
+                    **self.get_related_filter('virtual_machine', 'virtual_machine', data['virtual_machine'])
                 )
 
     def clean_is_primary(self):

+ 7 - 0
netbox/ipam/tests/test_filtersets.py

@@ -1967,6 +1967,13 @@ class VLANGroupTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
         params = {'cluster': [clusters[0].pk, clusters[1].pk]}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
 
+    def test_scope_type(self):
+        """Negating a scope type keeps VLAN groups without a scope."""
+        params = {'scope_type': ['dcim.region']}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+        params = {'scope_type__n': ['dcim.region']}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 7)
+
     def test_tenant(self):
         tenants = Tenant.objects.all()[:2]
         params = {'tenant_id': [tenants[0].pk, tenants[1].pk]}

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

@@ -110,7 +110,11 @@ class TokenAuthentication(BaseAuthentication):
 
             # Load from LDAP if FIND_GROUP_PERMS is active
             # 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)
                 # If the user is found in the LDAP directory use it, if not fallback to the local user
                 if ldap_user:

+ 1 - 1
netbox/netbox/api/fields.py

@@ -2,7 +2,7 @@ from functools import cached_property
 
 from django.core.exceptions import ObjectDoesNotExist
 from django.db.backends.postgresql.psycopg_any import NumericRange
-from django.utils.translation import gettext as _
+from django.utils.translation import gettext_lazy as _
 from drf_spectacular.types import OpenApiTypes
 from drf_spectacular.utils import extend_schema_field
 from netaddr import IPNetwork

+ 24 - 21
netbox/netbox/api/viewsets/__init__.py

@@ -16,6 +16,7 @@ from rest_framework.viewsets import GenericViewSet
 from netbox.api.fields import RelatedObjectCountField
 from netbox.api.serializers.features import ChangeLogMessageSerializer
 from utilities.api import get_annotations_for_serializer, get_fields_for_serializer, get_prefetches_for_serializer
+from utilities.error_handlers import get_viewable_protected_objects
 from utilities.exceptions import AbortRequest, PreconditionFailed
 from utilities.query import reapply_model_ordering
 
@@ -266,19 +267,7 @@ class NetBoxModelViewSet(
         try:
             return super().dispatch(request, *args, **kwargs)
         except (ProtectedError, RestrictedError) as e:
-            if type(e) is ProtectedError:
-                protected_objects = list(e.protected_objects)
-            else:
-                protected_objects = list(e.restricted_objects)
-            msg = f'Unable to delete object. {len(protected_objects)} dependent objects were found: '
-            msg += ', '.join([f'{obj} ({obj.pk})' for obj in protected_objects])
-            logger.warning(msg)
-            return self.finalize_response(
-                request,
-                Response({'detail': msg}, status=409),
-                *args,
-                **kwargs
-            )
+            return self.finalize_response(request, self._get_protected_error_response(e), *args, **kwargs)
         except AbortRequest as e:
             logger.debug(e.message)
             return self.finalize_response(
@@ -288,6 +277,27 @@ class NetBoxModelViewSet(
                 **kwargs
             )
 
+    def _get_protected_error_response(self, exc):
+        """
+        Log all dependent objects of a ProtectedError or RestrictedError, and return a 409 response listing only those
+        which the user is permitted to view.
+        """
+        def get_message(objects, hidden_count=0):
+            dependent_objects = [f'{obj} ({obj.pk})' for obj in objects]
+            if hidden_count:
+                noun = 'object' if hidden_count == 1 else 'objects'
+                dependent_objects.append(f'{hidden_count} {noun} you do not have permission to view')
+            msg = f'Unable to delete object. {len(objects) + hidden_count} dependent objects were found: '
+            return msg + ', '.join(dependent_objects)
+
+        protected_objects = exc.protected_objects if isinstance(exc, ProtectedError) else exc.restricted_objects
+        logger = logging.getLogger(f'netbox.api.views.{self.__class__.__name__}')
+        logger.warning(get_message(protected_objects))
+
+        return Response({
+            'detail': get_message(*get_viewable_protected_objects(exc, self.request.user)),
+        }, status=409)
+
     def exception_to_response(self, exc):
         """
         Translate a NetBox/Django exception that is not a DRF APIException into the same
@@ -301,14 +311,7 @@ class NetBoxModelViewSet(
         """
         logger = logging.getLogger(f'netbox.api.views.{self.__class__.__name__}')
         if isinstance(exc, (ProtectedError, RestrictedError)):
-            if type(exc) is ProtectedError:
-                protected_objects = list(exc.protected_objects)
-            else:
-                protected_objects = list(exc.restricted_objects)
-            msg = f'Unable to delete object. {len(protected_objects)} dependent objects were found: '
-            msg += ', '.join([f'{obj} ({obj.pk})' for obj in protected_objects])
-            logger.warning(msg)
-            return Response({'detail': msg}, status=409)
+            return self._get_protected_error_response(exc)
         if isinstance(exc, AbortRequest):
             logger.debug(exc.message)
             return Response({'detail': exc.message}, status=400)

+ 1 - 4
netbox/netbox/api/viewsets/mixins.py

@@ -805,10 +805,7 @@ class BulkDestroyModelMixin:
                         e.protected_objects if isinstance(e, ProtectedError) else e.restricted_objects
                     )
                     # Report only the count, not names or PKs, to keep each per-object error
-                    # entry small in a batch response. Note: the single-object delete endpoint
-                    # (NetBoxModelViewSet.dispatch()) does include names and PKs of dependent
-                    # objects, so this is not a hard security boundary — just a narrower
-                    # response shape for the bulk case.
+                    # entry small in a batch response.
                     errors.append({
                         'id': pk,
                         'errors': {

+ 1 - 0
netbox/netbox/filtersets/__init__.py

@@ -311,6 +311,7 @@ class BaseFilterSet(django_filters.FilterSet):
         if isinstance(existing_filter, (
             django_filters.ModelChoiceFilter,
             django_filters.ModelMultipleChoiceFilter,
+            filters.MultiValueContentTypeFilter,
         )):
             # These filter types support only negation
             return FILTER_NEGATION_LOOKUP_MAP

+ 2 - 1
netbox/netbox/forms/mixins.py

@@ -1,5 +1,5 @@
 from django import forms
-from django.utils.translation import gettext as _
+from django.utils.translation import gettext_lazy as _
 
 from core.models import ObjectType
 from extras.choices import *
@@ -22,6 +22,7 @@ class ChangelogMessageMixin(forms.Form):
     Adds an optional field for recording a message on the resulting changelog record(s).
     """
     changelog_message = forms.CharField(
+        label=_('Changelog message'),
         required=False,
         max_length=200,
     )

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

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

@@ -14,6 +14,7 @@ from strawberry.django.views import GraphQLView
 
 from netbox.api.authentication import TokenAuthentication
 from netbox.config import get_config
+from netbox.graphql.extensions import log_graphql_queries
 from utilities.templatetags.builtins.tags import static_with_params
 
 
@@ -38,6 +39,7 @@ class NetBoxGraphQLView(GraphQLView):
                 auth_info = authenticator.authenticate(request)
                 if auth_info is not None:
                     request.user = auth_info[0]  # User object
+                    request.auth = auth_info[1]  # Token object
             except AuthenticationFailed as exc:
                 return HttpResponseForbidden(exc.detail)
 
@@ -47,7 +49,10 @@ class NetBoxGraphQLView(GraphQLView):
                 return redirect_to_login(reverse('graphql'))
             return HttpResponseForbidden("No credentials provided.")
 
-        return super().dispatch(request, *args, **kwargs)
+        response = super().dispatch(request, *args, **kwargs)
+        log_graphql_queries(request, response)
+
+        return response
 
 
 @method_decorator(never_cache, name='dispatch')

+ 31 - 7
netbox/netbox/middleware.py

@@ -7,10 +7,11 @@ from django.contrib.auth.middleware import LoginRequiredMiddleware as LoginRequi
 from django.contrib.auth.middleware import RemoteUserMiddleware as RemoteUserMiddleware_
 from django.core.exceptions import ImproperlyConfigured
 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.http import Http404, HttpResponseRedirect
+from django.http import Http404, HttpResponse, HttpResponseRedirect
 from django.middleware.common import CommonMiddleware as DjangoCommonMiddleware
+from django.template import loader
 from django.utils.translation import gettext_lazy as _
 from django_prometheus import middleware
 from rest_framework.views import APIView
@@ -44,6 +45,8 @@ class CommonMiddleware(DjangoCommonMiddleware):
     body (clients downgrade to GET on a 302) or raise a RuntimeError when
     DEBUG is enabled. Letting the original 404 propagate gives the caller a
     clear, actionable error instead.
+
+    Also reports 404 responses to Sentry after APPEND_SLASH handling.
     """
     UNSAFE_METHODS = frozenset(('DELETE', 'PATCH', 'POST', 'PUT'))
 
@@ -52,6 +55,15 @@ class CommonMiddleware(DjangoCommonMiddleware):
             return False
         return super().should_redirect_with_slash(request)
 
+    def process_response(self, request, response):
+        response = super().process_response(request, response)
+
+        if settings.SENTRY_ENABLED and response.status_code == 404 and getattr(request, '_sentry_report_404', False):
+            from sentry_sdk import capture_message
+            capture_message("Page not found", level="error")
+
+        return response
+
 
 class PermissionsPolicyMiddleware:
     """
@@ -316,12 +328,20 @@ class MaintenanceModeMiddleware:
         self.get_response = get_response
 
     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
     def _set_session_type(allow_write):
@@ -346,6 +366,10 @@ class MaintenanceModeMiddleware:
             if is_api_request(request) or is_graphql_request(request):
                 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)
             return HttpResponseRedirect(request.path_info)
         return None

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

@@ -1,4 +1,5 @@
 import json
+import logging
 from collections import defaultdict
 from functools import cached_property
 
@@ -50,6 +51,8 @@ __all__ = (
     'register_models',
 )
 
+logger = logging.getLogger('netbox.models.features')
+
 
 #
 # Feature mixins
@@ -102,6 +105,21 @@ class ChangeLoggingMixin(DeleteMixin, models.Model):
         self._prechange_snapshot = self.serialize_object(exclude=exclude_fields)
     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):
         """
         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
         """
+        # 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.data_synced = timezone.now()
         if 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
 
     def sync_data(self):

+ 4 - 3
netbox/netbox/settings.py

@@ -678,10 +678,11 @@ EXEMPT_EXCLUDE_MODELS = (
 
 # All URLs starting with a string listed here are exempt from maintenance mode enforcement
 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_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
 )
 
 

+ 11 - 0
netbox/netbox/tables/columns.py

@@ -133,6 +133,17 @@ class ManyToManyColumn(tables.ManyToManyColumn):
     """
     Overrides django-tables2's stock ManyToManyColumn to ensure that value() returns only plaintext data.
     """
+    def __init__(self, *args, prefetch_related=(), **kwargs):
+        """
+        Args:
+            prefetch_related: Additional lookup strings (one string or an iterable), relative to the table's model,
+                              needed to render or export the items
+        """
+        super().__init__(*args, **kwargs)
+        if isinstance(prefetch_related, str):
+            prefetch_related = (prefetch_related,)
+        self.prefetch_related = tuple(prefetch_related)
+
     def value(self, value):
         items = [self.transform(item) for item in self.filter(value)]
         return self.separator.join(items)

+ 1 - 0
netbox/netbox/tables/tables.py

@@ -133,6 +133,7 @@ class BaseTable(tables.Table):
             elif not column.visible:
                 # Skip hidden columns
                 continue
+            prefetch_fields.extend(getattr(column.column, 'prefetch_related', ()))
             model = getattr(self.Meta, 'model')  # Must be called *after* resolving columns
             accessor = column.accessor
             if accessor.startswith('custom_field_data__'):

+ 1 - 1
netbox/netbox/tests/dummy_plugin/navigation.py

@@ -1,4 +1,4 @@
-from django.utils.translation import gettext as _
+from django.utils.translation import gettext_lazy as _
 
 from netbox.plugins.navigation import PluginMenu, PluginMenuButton, PluginMenuItem
 

+ 51 - 2
netbox/netbox/tests/test_api.py

@@ -6,6 +6,7 @@ from django.contrib.contenttypes.models import ContentType
 from django.core.exceptions import NON_FIELD_ERRORS
 from django.db import DEFAULT_DB_ALIAS, connection, connections
 from django.db.backends.postgresql.psycopg_any import NumericRange
+from django.db.models import ProtectedError
 from django.test import RequestFactory, TestCase, TransactionTestCase, override_settings, tag
 from django.test.utils import CaptureQueriesContext
 from django.urls import reverse
@@ -17,7 +18,7 @@ from rest_framework.test import APIClient
 
 from core.models import DataFile, DataSource, ObjectType
 from dcim.api.serializers import InterfaceSerializer, RackSerializer
-from dcim.api.views import SiteViewSet
+from dcim.api.views import DeviceTypeViewSet, SiteViewSet
 from dcim.models import Device, Rack, Site
 from extras.models import ExportTemplate
 from ipam.api.serializers import RouteTargetSerializer, VRFSerializer
@@ -28,7 +29,7 @@ from netbox.api.pagination import NetBoxPagination
 from netbox.api.serializers import ValidatedModelSerializer, WritableNestedSerializer
 from netbox.api.viewsets.mixins import BulkUpdateModelMixin
 from users.constants import TOKEN_PREFIX
-from users.models import Token, User
+from users.models import ObjectPermission, Token, User
 from utilities.api import get_serializer_for_model
 from utilities.testing import APITestCase, create_test_device
 from vpn.api.serializers import L2VPNSerializer
@@ -706,3 +707,51 @@ class ObjectUpdateLockingTestCase(APITestCase):
                 with viewset.lock_object():
                     self.assertEqual(viewset.locked_pks, locked_pks)
                 self.assertEqual(viewset.locked_pks, set())
+
+
+class ProtectedObjectsMessageTestCase(APITestCase):
+    """
+    The error for a deletion prevented by dependent objects must name only those dependent objects which the user is
+    permitted to view. (Ref: #23398)
+    """
+
+    @classmethod
+    def setUpTestData(cls):
+        cls.devices = (
+            create_test_device('Device 1'),
+            create_test_device('Device 2'),
+        )
+        cls.device_type = cls.devices[0].device_type
+        cls.expected_message = (
+            f'Unable to delete object. 2 dependent objects were found: Device 1 ({cls.devices[0].pk}), '
+            '1 object you do not have permission to view'
+        )
+
+    def setUp(self):
+        super().setUp()
+        self.add_permissions('dcim.delete_devicetype')
+
+        # Permit viewing only the first Device
+        obj_perm = ObjectPermission.objects.create(
+            name='View Device 1', actions=['view'], constraints={'pk': self.devices[0].pk}
+        )
+        obj_perm.users.add(self.user)
+        obj_perm.object_types.add(ObjectType.objects.get_for_model(Device))
+
+    def test_delete_object(self):
+        url = reverse('dcim-api:devicetype-detail', kwargs={'pk': self.device_type.pk})
+        with self.assertLogs('netbox.api.views.DeviceTypeViewSet', 'WARNING') as logs:
+            response = self.client.delete(url, **self.header)
+        self.assertHttpStatus(response, 409)
+        self.assertEqual(response.data['detail'], self.expected_message)
+
+        # The log lists all dependent objects
+        self.assertIn(f'Device 2 ({self.devices[1].pk})', logs.output[0])
+
+    def test_exception_to_response(self):
+        viewset = DeviceTypeViewSet()
+        viewset.request = Request(RequestFactory().delete('/'))
+        viewset.request.user = self.user
+        response = viewset.exception_to_response(ProtectedError('', set(self.devices)))
+        self.assertEqual(response.status_code, 409)
+        self.assertEqual(response.data['detail'], self.expected_message)

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

@@ -1074,6 +1074,18 @@ class SSOLoginButtonTestCase(DjangoTestCase):
             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):
     """
     Verify the view which initiates an SSO login. Chromium-based browsers evaluate the CSP

+ 45 - 1
netbox/netbox/tests/test_forms.py

@@ -5,7 +5,11 @@ from django.core.exceptions import NON_FIELD_ERRORS
 from django.core.exceptions import ValidationError as DjangoValidationError
 from django.core.validators import MaxLengthValidator
 from django.forms.models import ALL_FIELDS
-from django.test import TestCase
+from django.test import TestCase, tag
+from django.utils import translation
+from django.utils.functional import Promise
+from django.utils.html import escape
+from django.utils.translation import gettext
 
 from circuits.forms import CircuitGroupAssignmentForm, CircuitTerminationForm
 from core.forms import DataSourceForm
@@ -17,6 +21,8 @@ from dcim.forms import (
     InterfaceImportForm,
     ModuleTypeForm,
     RackForm,
+    SiteFilterForm,
+    SiteForm,
 )
 from dcim.models import Device, DeviceRole, DeviceType, Interface, Manufacturer, Site
 from extras.forms import CustomFieldForm, EventRuleForm
@@ -574,3 +580,41 @@ class MetaShadowingTestCase(TestCase):
     def test_localized_fields_all_sentinel_expands_to_declared(self):
         # The ALL_FIELDS sentinel must expand to the declared fields, not char-split into letters.
         self.assertEqual(self._configured_field_names(ALL_FIELDS, {'name', 'status'}), {'name', 'status'})
+
+
+class FormMixinLabelTranslationTestCase(TestCase):
+    """
+    Mixin labels are set at import, so eager gettext keeps them in DEFAULT_LANGUAGE (#23702).
+    """
+
+    def assertLabelsTranslated(self, form, expected):
+        # Compare against gettext() so catalog updates don't break the test
+        for name, msgid in expected.items():
+            with self.subTest(field=name):
+                label = form.fields[name].label
+                self.assertIsInstance(label, Promise)
+                self.assertEqual(str(label), gettext(msgid))
+
+    @tag('regression')  # Ref: #23702
+    def test_model_form_mixin_labels(self):
+        # SiteForm inherits OwnerMixin, TagsMixin and ChangelogMessageMixin
+        with translation.override('nl'):
+            self.assertLabelsTranslated(SiteForm(), {
+                'owner_group': 'Owner group',
+                'owner': 'Owner',
+                'tags': 'Tags',
+                'changelog_message': 'Changelog message',
+            })
+
+    @tag('regression')  # Ref: #23702
+    def test_filter_form_mixin_labels(self):
+        # SiteFilterForm inherits OwnerFilterMixin and SavedFiltersMixin
+        with translation.override('nl'):
+            form = SiteFilterForm()
+            self.assertLabelsTranslated(form, {
+                'owner_group_id': 'Owner Group',
+                'owner_id': 'Owner',
+                'filter_id': 'Saved Filter',
+            })
+            # Set in __init__, so it also passes with eager gettext. It pins that a lazy value renders in widget attrs.
+            self.assertIn(f'aria-label="{escape(gettext("Saved filter"))}"', str(form['filter_id']))

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

@@ -1,4 +1,6 @@
+import hashlib
 import json
+import logging
 import re
 from types import SimpleNamespace
 from unittest import mock, skipIf
@@ -14,6 +16,7 @@ from django.test import override_settings
 from django.test.utils import CaptureQueriesContext
 from django.urls import reverse
 from django.utils import timezone
+from graphql import parse
 from rest_framework import status
 from strawberry.extensions import QueryDepthLimiter
 from strawberry.schema.config import StrawberryConfig
@@ -39,6 +42,12 @@ from dcim.models import (
 from extras.choices import CustomFieldTypeChoices
 from extras.models import CustomField, ExportTemplate, JournalEntry, TableConfig, Tag
 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.scalars import BigInt, BigIntScalar
 from netbox.graphql.schema import Query, get_schema_extensions, schema
@@ -1539,6 +1548,266 @@ class GraphQLAPITestCase(APITestCase):
         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):
     """
     A GraphQL field backed by a custom resolver is opaque to the query optimizer, which narrows column

+ 344 - 3
netbox/netbox/tests/test_middleware.py

@@ -1,5 +1,6 @@
 import json
 import re
+import sys
 from contextlib import contextmanager
 from types import SimpleNamespace
 from unittest import skipIf
@@ -7,17 +8,27 @@ from unittest.mock import Mock, patch
 
 from django.conf import settings
 from django.contrib.auth.models import AnonymousUser
+from django.contrib.messages import get_messages
+from django.core.cache import cache
 from django.core.signals import got_request_exception
-from django.db.utils import InternalError
-from django.test import Client, RequestFactory, override_settings
+from django.db import connection
+from django.db.utils import InterfaceError, InternalError
+from django.test import Client, RequestFactory, TransactionTestCase, override_settings
 from django.urls import ResolverMatch, reverse
 from django.utils.csp import CSP
 from django.views.generic import View
 from rest_framework import status
 from rest_framework.views import APIView
 
+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, LoginRequiredMiddleware, MaintenanceModeMiddleware
-from utilities.testing import TestCase
+from users.constants import TOKEN_PREFIX
+from users.models import Token, User
+from utilities.testing import TestCase, disable_warnings
 
 CSP_POLICY = {
     'default-src': [CSP.SELF],
@@ -152,6 +163,29 @@ class CoreMiddlewareTestCase(TestCase):
 
         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):
         request = self.factory.post(
             reverse('graphql'),
@@ -313,3 +347,310 @@ class ContentSecurityPolicyTestCase(TestCase):
                 response = self.anonymous_client.get(url)
                 self.assertHttpStatus(response, status_code)
                 self.assertIn("default-src 'self'", response['Content-Security-Policy'])
+
+
+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)
+class SentryNotFoundReportingTestCase(TestCase):
+
+    def setUp(self):
+        super().setUp()
+        self.sentry_sdk = Mock()
+        patcher = patch.dict(sys.modules, {'sentry_sdk': self.sentry_sdk})
+        patcher.start()
+        self.addCleanup(patcher.stop)
+
+    def test_404_reported_to_sentry(self):
+        with disable_warnings('django.request'):
+            response = self.client.get('/nonexistent-path/')
+
+        self.assertEqual(response.status_code, 404)
+        self.sentry_sdk.capture_message.assert_called_once_with('Page not found', level='error')
+
+    def test_append_slash_redirect_not_reported_to_sentry(self):
+        url = reverse('api-status')
+
+        for method in ('get', 'head'):
+            with self.subTest(method=method):
+                response = getattr(self.client, method)(url.rstrip('/'))
+
+                self.assertEqual(response.status_code, 301)
+                self.assertEqual(response.headers['Location'], url)
+                self.sentry_sdk.capture_message.assert_not_called()
+
+    def test_unsafe_api_request_without_slash_reported_to_sentry(self):
+        with disable_warnings('django.request'):
+            response = self.client.post(
+                reverse('api-status').rstrip('/'), data={}, content_type='application/json'
+            )
+
+        self.assertEqual(response.status_code, 404)
+        self.sentry_sdk.capture_message.assert_called_once_with('Page not found', level='error')
+
+    @override_settings(SENTRY_ENABLED=False)
+    def test_404_not_reported_when_sentry_disabled(self):
+        with disable_warnings('django.request'):
+            response = self.client.get('/nonexistent-path/')
+
+        self.assertEqual(response.status_code, 404)
+        self.sentry_sdk.capture_message.assert_not_called()

Alguns ficheiros não foram mostrados porque muitos ficheiros mudaram neste diff