Kaynağa Gözat

Merge remote-tracking branch 'origin/feature' into 21098-lag

Arthur 1 gün önce
ebeveyn
işleme
16742776fa
69 değiştirilmiş dosya ile 1932 ekleme ve 77 silme
  1. 1 0
      AGENTS.md
  2. 35 0
      docs/administration/content-security-policy.md
  3. 63 0
      docs/configuration/security.md
  4. 7 1
      docs/models/dcim/device.md
  5. 4 0
      docs/models/dcim/moduletype.md
  6. 17 1
      docs/models/dcim/site.md
  7. 2 2
      docs/models/extras/configtemplate.md
  8. 2 2
      docs/models/extras/exporttemplate.md
  9. 40 0
      docs/plugins/development/config-templates.md
  10. 20 0
      docs/plugins/development/templates.md
  11. 1 0
      mkdocs.yml
  12. 16 5
      netbox/dcim/api/serializers_/devices.py
  13. 4 2
      netbox/dcim/api/serializers_/devicetypes.py
  14. 14 3
      netbox/dcim/api/serializers_/sites.py
  15. 10 0
      netbox/dcim/constants.py
  16. 18 0
      netbox/dcim/filtersets.py
  17. 15 0
      netbox/dcim/forms/filtersets.py
  18. 8 1
      netbox/dcim/forms/model_forms.py
  19. 2 0
      netbox/dcim/graphql/filters.py
  20. 14 0
      netbox/dcim/graphql/mixins.py
  21. 5 3
      netbox/dcim/graphql/types.py
  22. 21 0
      netbox/dcim/migrations/0254_moduletype_images.py
  23. 2 1
      netbox/dcim/models/devices.py
  24. 51 1
      netbox/dcim/models/mixins.py
  25. 44 0
      netbox/dcim/models/modules.py
  26. 3 1
      netbox/dcim/models/sites.py
  27. 20 1
      netbox/dcim/signals.py
  28. 165 2
      netbox/dcim/tests/test_api.py
  29. 22 1
      netbox/dcim/tests/test_filtersets.py
  30. 49 2
      netbox/dcim/tests/test_forms.py
  31. 212 1
      netbox/dcim/tests/test_models.py
  32. 88 1
      netbox/dcim/tests/test_views.py
  33. 29 5
      netbox/dcim/ui/panels.py
  34. 2 0
      netbox/dcim/views.py
  35. 1 3
      netbox/extras/api/mixins.py
  36. 2 2
      netbox/extras/models/configs.py
  37. 13 0
      netbox/extras/models/mixins.py
  38. 104 0
      netbox/extras/tests/test_models.py
  39. 5 5
      netbox/extras/views.py
  40. 1 1
      netbox/ipam/tests/test_views.py
  41. 3 1
      netbox/netbox/forms/search.py
  42. 34 0
      netbox/netbox/middleware.py
  43. 16 0
      netbox/netbox/settings.py
  44. 64 0
      netbox/netbox/settings_utils.py
  45. 170 0
      netbox/netbox/tests/test_csp.py
  46. 64 0
      netbox/netbox/tests/test_middleware.py
  47. 127 0
      netbox/netbox/tests/test_permissions_policy.py
  48. 5 5
      netbox/netbox/tests/test_search.py
  49. 67 0
      netbox/netbox/tests/test_settings_utils.py
  50. 13 0
      netbox/netbox/tests/test_ui.py
  51. 69 3
      netbox/netbox/tests/test_views.py
  52. 4 1
      netbox/netbox/ui/attrs.py
  53. 6 1
      netbox/netbox/views/misc.py
  54. 0 0
      netbox/project-static/dist/netbox.js
  55. 0 0
      netbox/project-static/dist/netbox.js.map
  56. 5 0
      netbox/project-static/src/global.d.ts
  57. 35 0
      netbox/project-static/src/htmx.ts
  58. 1 1
      netbox/templates/account/usertoken_edit.html
  59. 18 7
      netbox/templates/base/base.html
  60. 20 0
      netbox/templates/dcim/panels/module_type.html
  61. 16 0
      netbox/templates/drf_spectacular/redoc.html
  62. 15 0
      netbox/templates/drf_spectacular/swagger_ui.html
  63. 1 1
      netbox/templates/graphql/graphiql.html
  64. 17 0
      netbox/templates/rest_framework/api.html
  65. 2 2
      netbox/templates/ui/attrs/numeric.html
  66. 1 1
      netbox/templates/users/token_edit.html
  67. 2 3
      netbox/utilities/forms/fields/generic.py
  68. 4 4
      netbox/utilities/tests/test_forms.py
  69. 21 0
      netbox/virtualization/tests/test_models.py

+ 1 - 0
AGENTS.md

@@ -323,6 +323,7 @@ Do not include an entry in the release notes for the PR unless explicitly instru
 - `NETBOX_CONFIGURATION` env var controls which settings module loads; set to `netbox.configuration_testing` for tests.
 - `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).
 - 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.
 - Plugins API: only documented public APIs are stable. Internal NetBox code is subject to change without notice.
+- `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.
 - See `docs/development/` for the full contributing guide and code style details.
 
 
 ## References
 ## References

+ 35 - 0
docs/administration/content-security-policy.md

@@ -0,0 +1,35 @@
+# Content Security Policy
+
+!!! info "This feature was introduced in NetBox v4.8."
+
+A [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP) (CSP) tells the browser from which sources a page may load scripts, images, fonts, and other resources. NetBox does not send one by default. To send one, define it with the [`SECURE_CSP`](../configuration/security.md#secure_csp) or [`SECURE_CSP_REPORT_ONLY`](../configuration/security.md#secure_csp_report_only) configuration parameter.
+
+NetBox's own pages are written to work under a strict script policy. Every `<script>` element NetBox renders carries the per-request nonce, and NetBox does not use inline event handler attributes or evaluate strings as code. This applies to scripts only. NetBox makes no equivalent promise for styles: it renders inline `<style>` elements and `style=` attributes, and none of them carry a nonce.
+
+!!! warning "Debug mode"
+    With `DEBUG` enabled, Django's debug error pages, GraphiQL's debug integration and django-htmx's error handler run scripts that a strict policy blocks or reports. Test policies with `DEBUG` disabled, and don't loosen a policy to accommodate them.
+
+## Example policy
+
+```python
+from django.utils.csp import CSP
+
+SECURE_CSP = {
+    'default-src': [CSP.SELF],
+    'script-src': [
+        CSP.SELF,
+        CSP.NONCE,
+        'https://static.copilot.netboxlabs.ai',
+    ],
+    'style-src': [CSP.SELF, CSP.UNSAFE_INLINE, 'https://fonts.googleapis.com'],
+    'font-src': [CSP.SELF, 'data:', 'https://fonts.gstatic.com'],
+    'img-src': [CSP.SELF, 'data:', 'https:'],
+    'connect-src': [CSP.SELF],
+    'worker-src': [CSP.SELF, 'blob:'],
+    'base-uri': [CSP.SELF],
+}
+```
+
+Try a policy first by assigning it to `SECURE_CSP_REPORT_ONLY`, which reports violations in the browser console without blocking anything.
+
+If your users enable NetBox Copilot, also allow `https://unpkg.com` and `https://js.stripe.com` in `script-src`, `'self'` and `https://js.stripe.com` in `frame-src`, and `https://api.copilot.netboxlabs.ai` and `wss://api.copilot.netboxlabs.ai` in `connect-src`.

+ 63 - 0
docs/configuration/security.md

@@ -200,6 +200,69 @@ The view name or URL to which a user is redirected after logging out.
 
 
 ---
 ---
 
 
+## PERMISSIONS_POLICY
+
+Default:
+
+```python
+PERMISSIONS_POLICY = {
+    'camera': [],
+    'microphone': [],
+    'geolocation': [],
+    'payment': [],
+    'usb': [],
+    'hid': [],
+    'serial': [],
+    'bluetooth': [],
+}
+```
+
+Defines the `Permissions-Policy` header sent with HTML responses, which controls which browser features NetBox pages may use. See the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Permissions-Policy) for the syntax and the list of features.
+
+Your dictionary replaces the default entirely, so copy the default and edit it. For example, to re-allow the camera for NetBox's own origin:
+
+```python
+PERMISSIONS_POLICY = {
+    'camera': ['self'],
+    'microphone': [],
+    'geolocation': [],
+    'payment': [],
+    'usb': [],
+    'hid': [],
+    'serial': [],
+    'bluetooth': [],
+}
+```
+
+Set `PERMISSIONS_POLICY = {}` to send no header. Values are checked at startup, and Django's quoted `CSP.SELF` is not accepted here.
+
+---
+
+## SECURE_CSP
+
+Default: `{}`
+
+Defines a Content Security Policy (CSP) to be sent with every response in the `Content-Security-Policy` header. This is a pass-through to Django's [`SECURE_CSP`](https://docs.djangoproject.com/en/stable/ref/settings/#secure-csp) setting: directives are mapped to lists of sources, using the constants in `django.utils.csp.CSP`. Include `CSP.NONCE` in a directive to have a fresh nonce generated for each request, which is added to the header whenever the rendered page uses it. If empty (the default), no header is sent.
+
+```python
+from django.utils.csp import CSP
+
+SECURE_CSP = {
+    'default-src': [CSP.SELF],
+    'script-src': [CSP.SELF, CSP.NONCE],
+}
+```
+
+---
+
+## SECURE_CSP_REPORT_ONLY
+
+Default: `{}`
+
+Defines a Content Security Policy to be sent in the `Content-Security-Policy-Report-Only` header. The browser reports violations of this policy without blocking anything, which makes it useful for testing a policy before enforcing it with [`SECURE_CSP`](#secure_csp). This is a pass-through to Django's [`SECURE_CSP_REPORT_ONLY`](https://docs.djangoproject.com/en/stable/ref/settings/#secure-csp-report-only) setting, and takes the same form as `SECURE_CSP`. If empty (the default), no header is sent.
+
+---
+
 ## SECURE_HSTS_INCLUDE_SUBDOMAINS
 ## SECURE_HSTS_INCLUDE_SUBDOMAINS
 
 
 Default: `False`
 Default: `False`

+ 7 - 1
docs/models/dcim/device.md

@@ -71,7 +71,13 @@ If installed in a rack, this field indicates the base rack unit in which the dev
 
 
 ### Latitude & Longitude
 ### Latitude & Longitude
 
 
-GPS coordinates of the device for geolocation.
+GPS coordinates of the device for geolocation. These are assumed to use the WGS84 datum (as reported by GPS).
+
+### Web Mercator X & Y
+
+!!! info "This field was introduced in NetBox v4.8."
+
+The device's coordinates in the [Web Mercator](https://epsg.io/3857) (EPSG:3857) projection, in meters. These read-only values are calculated from the latitude and longitude. See the [site](./site.md#web-mercator-x-y) documentation for details.
 
 
 ### Status
 ### Status
 
 

+ 4 - 0
docs/models/dcim/moduletype.md

@@ -83,6 +83,10 @@ The cooling method employed by modules of this type (air, liquid, hybrid, or imm
 
 
 The date after which this module type is no longer supported by its manufacturer. This can be used to identify modules approaching or past their support horizon to aid in hardware lifecycle planning.
 The date after which this module type is no longer supported by its manufacturer. This can be used to identify modules approaching or past their support horizon to aid in hardware lifecycle planning.
 
 
+### Front & Rear Images
+
+Users can upload images of the module's front and rear panels. These are displayed on the module type and its module instances.
+
 ### Profile
 ### Profile
 
 
 The assigned [profile](./moduletypeprofile.md) for the type of module. Profiles can be used to classify module types by function (e.g. power supply, hard disk, etc.), and they support the addition of user-configurable attributes on module types. The assignment of a module type to a profile is optional.
 The assigned [profile](./moduletypeprofile.md) for the type of module. Profiles can be used to classify module types by function (e.g. power supply, hard disk, etc.), and they support the addition of user-configurable attributes on module types. The assignment of a module type to a profile is optional.

+ 17 - 1
docs/models/dcim/site.md

@@ -48,4 +48,20 @@ The address to use for deliveries destined for the site.
 
 
 ### Latitude & Longitude
 ### Latitude & Longitude
 
 
-GPS coordinates of the site for geolocation.
+GPS coordinates of the site for geolocation. These are assumed to use the WGS84 datum (as reported by GPS).
+
+### Web Mercator X & Y
+
+!!! info "This field was introduced in NetBox v4.8."
+
+The site's [Web Mercator](https://epsg.io/3857) (EPSG:3857) coordinates, in meters. These read-only values are calculated from its latitude and longitude for use with mapping tools:
+
+```
+X = longitude × (π / 180) × 6378137
+Y = ln(tan(π / 4 + latitude × π / 360)) × 6378137
+```
+
+where `ln` is the natural logarithm. Because Web Mercator is undefined at the poles, latitudes beyond ±85.05113° are clamped to that bound.
+
+!!! note
+    Web Mercator (EPSG:3857) differs from the ellipsoidal World Mercator projection (EPSG:3395). Ensure the target system expects EPSG:3857 coordinates.

+ 2 - 2
docs/models/extras/configtemplate.md

@@ -32,9 +32,9 @@ The `undefined` Jinja environment parameter, which must reference a Python class
 }
 }
 ```
 ```
 
 
-!!! note "Changed in NetBox v4.6.1"
+!!! warning "Deprecation Warning"
 
 
-    The `finalize` parameter is deprecated and cannot be set on new or modified templates. Templates that already have it saved continue to honor it.
+    The `finalize` parameter has been deprecated as of NetBox v4.6.1, and is scheduled for removal in NetBox v5.0. It cannot be set on new or modified templates. Templates that already have it saved continue to honor it until then. Move any `finalize` logic into the template code itself.
 
 
 ### MIME Type
 ### MIME Type
 
 

+ 2 - 2
docs/models/extras/exporttemplate.md

@@ -32,9 +32,9 @@ The `undefined` Jinja environment parameter, which must reference a Python class
 }
 }
 ```
 ```
 
 
-!!! note "Changed in NetBox v4.6.1"
+!!! warning "Deprecation Warning"
 
 
-    The `finalize` parameter is deprecated and cannot be set on new or modified templates. Templates that already have it saved continue to honor it.
+    The `finalize` parameter has been deprecated as of NetBox v4.6.1, and is scheduled for removal in NetBox v5.0. It cannot be set on new or modified templates. Templates that already have it saved continue to honor it until then. Move any `finalize` logic into the template code itself.
 
 
 ### MIME Type
 ### MIME Type
 
 

+ 40 - 0
docs/plugins/development/config-templates.md

@@ -115,3 +115,43 @@ The returned dict is merged into the template context, so `my_plugin` becomes av
 
 
 !!! note "No per-render context"
 !!! note "No per-render context"
     `get_jinja_context()` receives no arguments — it has no access to the object being rendered or the caller-supplied context. It is intended for plugin-global namespaces (e.g. a lazily-evaluated query helper). Per-object logic belongs in the template itself or in a custom filter.
     `get_jinja_context()` receives no arguments — it has no access to the object being rendered or the caller-supplied context. It is intended for plugin-global namespaces (e.g. a lazily-evaluated query helper). Per-object logic belongs in the template itself or in a custom filter.
+
+---
+
+## Rendering Configurations
+
+!!! info "This feature was introduced in NetBox v4.8."
+
+Devices and virtual machines provide two methods for rendering their configuration outside of a web request, for example from a background job, a custom script, or a management command. For the same template and extra context, these produce the same output as the "Render Config" tab in the UI and the `render-config` REST API endpoint.
+
+### `render_config(config_template=None, extra_context=None)`
+
+Renders and returns the object's configuration as text. If `config_template` is not given, the template is resolved from the object, its role, or its platform (in that order). Returns `None` if no template applies. Rendering errors are raised to the caller.
+
+```python
+from dcim.models import Device
+
+device = Device.objects.get(name='router1')
+config = device.render_config(extra_context={'deploy_id': 42})
+```
+
+!!! tip "Rendering many objects"
+    Resolving each object's config template, and computing any config context that isn't cached, can take extra queries per object. When rendering many objects, preload the template relationships and annotate the queryset so that both are fetched in the same query:
+
+    ```python
+    devices = (
+        Device.objects
+        .select_related('config_template', 'role__config_template', 'platform__config_template')
+        .annotate_config_context_data(only_invalidated=True)
+    )
+
+    for device in devices:
+        config = device.render_config()
+    ```
+
+### `get_render_context(extra_context=None)`
+
+Returns the context used to render the object's config template: its [config context](../../features/context-data.md) data, then any extra context, then the object itself under its model name (`device` or `virtualmachine`). The object always takes precedence, so extra context can't replace it.
+
+!!! note "Permissions"
+    Neither method checks permissions. If you render a configuration on behalf of a user, confirm that the user has the `render_config` and `view` permissions for the object, as the UI and REST API do. If you pass a `config_template` the user selected, also confirm that they have `view` permission for that template.

+ 20 - 0
docs/plugins/development/templates.md

@@ -203,6 +203,26 @@ This template is used by the `BulkDeleteView` generic view to delete multiple ob
 | `table`      | Yes      | The table class used for rendering the list of objects          |
 | `table`      | Yes      | The table class used for rendering the list of objects          |
 | `return_url` | Yes      | The URL to which the user is redirect after submitting the form |
 | `return_url` | Yes      | The URL to which the user is redirect after submitting the form |
 
 
+## Content Security Policy
+
+Administrators can send a [Content Security Policy](../../administration/content-security-policy.md) (CSP) that only allows scripts carrying a per-request nonce.
+
+!!! warning
+    NetBox is planning to turn a CSP on by default in v5.0 ([#23503](https://github.com/netbox-community/netbox/issues/23503)), so plugin templates should work under one now.
+
+* **Nonce every script.** Add `nonce="{{ csp_nonce }}"` to every `<script>` element, inline or with a `src`. The `csp_nonce` template variable is public plugin API from NetBox v4.8. A `<script>` inside a fragment that htmx swaps into the page does not run under a nonce policy, so use a static JavaScript listener instead.
+* **No inline event handler attributes.** Attributes such as `onclick=` or `onerror=` are blocked and the handler silently does not run. Attach a listener from a script file under your plugin's static directory instead.
+* **No runtime evaluation of strings as code.** This includes htmx's `hx-on` attributes, `hx-trigger` filter expressions such as `keyup[event.target.value.length > 2]`, and `js:` values in `hx-vals` or `hx-headers`. Without `'unsafe-eval'`, `hx-on` handlers and `js:` values throw an error, which shows in the browser console as a CSP violation, and they do not work. A trigger filter fails open instead: htmx drops the filter, so the request fires on every event. Use a listener that dispatches a custom event or sets a request parameter in `htmx:configRequest`.
+* **Inline styles are fine.** The [example policy](../../administration/content-security-policy.md#example-policy) allows inline `style=` attributes and `<style>` elements, and `style-src` takes no nonce.
+
+```jinja2
+{% load static %}
+<script nonce="{{ csp_nonce }}">
+  window.myPluginConfig = { endpoint: "{% url 'plugins:my_plugin:endpoint' %}" };
+</script>
+<script nonce="{{ csp_nonce }}" src="{% static 'my_plugin/widget.js' %}"></script>
+```
+
 ## Tags
 ## Tags
 
 
 The following custom template tags are available in NetBox.
 The following custom template tags are available in NetBox.

+ 1 - 0
mkdocs.yml

@@ -173,6 +173,7 @@ nav:
             - Microsoft Entra ID: 'administration/authentication/microsoft-entra-id.md'
             - Microsoft Entra ID: 'administration/authentication/microsoft-entra-id.md'
             - Okta: 'administration/authentication/okta.md'
             - Okta: 'administration/authentication/okta.md'
         - Permissions: 'administration/permissions.md'
         - Permissions: 'administration/permissions.md'
+        - Content Security Policy: 'administration/content-security-policy.md'
         - Error Reporting: 'administration/error-reporting.md'
         - Error Reporting: 'administration/error-reporting.md'
         - Management Commands: 'administration/management-commands.md'
         - Management Commands: 'administration/management-commands.md'
         - Replicating NetBox: 'administration/replicating-netbox.md'
         - Replicating NetBox: 'administration/replicating-netbox.md'

+ 16 - 5
netbox/dcim/api/serializers_/devices.py

@@ -2,7 +2,7 @@ import decimal
 from functools import cached_property
 from functools import cached_property
 
 
 from django.contrib.contenttypes.models import ContentType
 from django.contrib.contenttypes.models import ContentType
-from django.utils.translation import gettext as _
+from django.utils.translation import gettext_lazy as _
 from drf_spectacular.utils import extend_schema_field
 from drf_spectacular.utils import extend_schema_field
 from rest_framework import serializers
 from rest_framework import serializers
 
 
@@ -58,6 +58,16 @@ class DeviceSerializer(PrimaryModelSerializer):
         min_value=decimal.Decimal(0.5),
         min_value=decimal.Decimal(0.5),
         default=None
         default=None
     )
     )
+    mercator_x = serializers.FloatField(
+        read_only=True,
+        allow_null=True,
+        help_text=_('Web Mercator (EPSG:3857) X coordinate, in meters')
+    )
+    mercator_y = serializers.FloatField(
+        read_only=True,
+        allow_null=True,
+        help_text=_('Web Mercator (EPSG:3857) Y coordinate, in meters')
+    )
     status = ChoiceField(choices=DeviceStatusChoices, required=False)
     status = ChoiceField(choices=DeviceStatusChoices, required=False)
     airflow = ChoiceField(choices=DeviceAirflowChoices, allow_blank=True, required=False)
     airflow = ChoiceField(choices=DeviceAirflowChoices, allow_blank=True, required=False)
     cooling_method = ChoiceField(choices=CoolingMethodChoices, allow_blank=True, required=False, allow_null=True)
     cooling_method = ChoiceField(choices=CoolingMethodChoices, allow_blank=True, required=False, allow_null=True)
@@ -115,10 +125,11 @@ class DeviceSerializer(PrimaryModelSerializer):
         model = Device
         model = Device
         fields = [
         fields = [
             'id', 'url', 'display_url', 'display', 'name', 'device_type', 'role', 'tenant', 'platform', 'serial',
             'id', 'url', 'display_url', 'display', 'name', 'device_type', 'role', 'tenant', 'platform', 'serial',
-            'asset_tag', 'site', 'location', 'rack', 'position', 'face', 'latitude', 'longitude', 'parent_device',
-            'status', 'airflow', 'cooling_method', 'primary_ip', 'primary_ip4', 'primary_ip6', 'oob_ip', 'cluster',
-            'virtual_chassis', 'vc_position', 'vc_priority', 'description', 'owner', 'comments', 'config_template',
-            'config_context', 'local_context_data', 'tags', 'custom_fields', 'created', 'last_updated',
+            'asset_tag', 'site', 'location', 'rack', 'position', 'face', 'latitude', 'longitude', 'mercator_x',
+            'mercator_y', 'parent_device', 'status', 'airflow', 'cooling_method', 'primary_ip', 'primary_ip4',
+            'primary_ip6', 'oob_ip', 'cluster', 'virtual_chassis', 'vc_position', 'vc_priority', 'description', 'owner',
+            'comments', 'config_template', 'config_context', 'local_context_data', 'tags', 'custom_fields', 'created',
+            'last_updated',
             'console_port_count', 'console_server_port_count', 'power_port_count', 'power_outlet_count',
             'console_port_count', 'console_server_port_count', 'power_port_count', 'power_outlet_count',
             'cooling_intake_count', 'cooling_outflow_count', 'interface_count', 'front_port_count', 'rear_port_count',
             'cooling_intake_count', 'cooling_outflow_count', 'interface_count', 'front_port_count', 'rear_port_count',
             'device_bay_count', 'module_bay_count', 'inventory_item_count', 'replicate_components',
             'device_bay_count', 'module_bay_count', 'inventory_item_count', 'replicate_components',

+ 4 - 2
netbox/dcim/api/serializers_/devicetypes.py

@@ -124,6 +124,8 @@ class ModuleTypeSerializer(PrimaryModelSerializer):
         allow_null=True
         allow_null=True
     )
     )
     cooling_method = ChoiceField(choices=CoolingMethodChoices, allow_blank=True, required=False, allow_null=True)
     cooling_method = ChoiceField(choices=CoolingMethodChoices, allow_blank=True, required=False, allow_null=True)
+    front_image = serializers.ImageField(required=False, allow_null=True)
+    rear_image = serializers.ImageField(required=False, allow_null=True)
     attributes = AttributesField(
     attributes = AttributesField(
         source='attribute_data',
         source='attribute_data',
         required=False,
         required=False,
@@ -147,8 +149,8 @@ class ModuleTypeSerializer(PrimaryModelSerializer):
         model = ModuleType
         model = ModuleType
         fields = [
         fields = [
             'id', 'url', 'display_url', 'display', 'profile', 'manufacturer', 'model', 'part_number', 'airflow',
             'id', 'url', 'display_url', 'display', 'profile', 'manufacturer', 'model', 'part_number', 'airflow',
-            'cooling_method', 'weight', 'weight_unit', 'end_of_life', 'description', 'attributes', 'module_bay_types',
-            'owner', 'comments', 'tags', 'custom_fields',
+            'cooling_method', 'weight', 'weight_unit', 'end_of_life', 'front_image', 'rear_image', 'description',
+            'attributes', 'module_bay_types', 'owner', 'comments', 'tags', 'custom_fields',
             'created', 'last_updated', 'module_count', 'console_port_template_count',
             'created', 'last_updated', 'module_count', 'console_port_template_count',
             'console_server_port_template_count', 'power_port_template_count', 'power_outlet_template_count',
             'console_server_port_template_count', 'power_port_template_count', 'power_outlet_template_count',
             'cooling_intake_template_count', 'cooling_outflow_template_count', 'interface_template_count',
             'cooling_intake_template_count', 'cooling_outflow_template_count', 'interface_template_count',

+ 14 - 3
netbox/dcim/api/serializers_/sites.py

@@ -1,3 +1,4 @@
+from django.utils.translation import gettext_lazy as _
 from rest_framework import serializers
 from rest_framework import serializers
 from timezone_field.rest_framework import TimeZoneSerializerField
 from timezone_field.rest_framework import TimeZoneSerializerField
 
 
@@ -53,6 +54,16 @@ class SiteSerializer(PrimaryModelSerializer):
     group = SiteGroupSerializer(nested=True, required=False, allow_null=True)
     group = SiteGroupSerializer(nested=True, required=False, allow_null=True)
     tenant = TenantSerializer(nested=True, required=False, allow_null=True)
     tenant = TenantSerializer(nested=True, required=False, allow_null=True)
     time_zone = TimeZoneSerializerField(required=False, allow_null=True)
     time_zone = TimeZoneSerializerField(required=False, allow_null=True)
+    mercator_x = serializers.FloatField(
+        read_only=True,
+        allow_null=True,
+        help_text=_('Web Mercator (EPSG:3857) X coordinate, in meters')
+    )
+    mercator_y = serializers.FloatField(
+        read_only=True,
+        allow_null=True,
+        help_text=_('Web Mercator (EPSG:3857) Y coordinate, in meters')
+    )
     asns = SerializedPKRelatedField(
     asns = SerializedPKRelatedField(
         queryset=ASN.objects.all(),
         queryset=ASN.objects.all(),
         serializer=ASNSerializer,
         serializer=ASNSerializer,
@@ -73,9 +84,9 @@ class SiteSerializer(PrimaryModelSerializer):
         model = Site
         model = Site
         fields = [
         fields = [
             'id', 'url', 'display_url', 'display', 'name', 'slug', 'status', 'region', 'group', 'tenant', 'facility',
             'id', 'url', 'display_url', 'display', 'name', 'slug', 'status', 'region', 'group', 'tenant', 'facility',
-            'time_zone', 'description', 'physical_address', 'shipping_address', 'latitude', 'longitude', 'owner',
-            'comments', 'asns', 'tags', 'custom_fields', 'created', 'last_updated', 'circuit_count', 'device_count',
-            'prefix_count', 'rack_count', 'virtualmachine_count', 'vlan_count',
+            'time_zone', 'description', 'physical_address', 'shipping_address', 'latitude', 'longitude', 'mercator_x',
+            'mercator_y', 'owner', 'comments', 'asns', 'tags', 'custom_fields', 'created', 'last_updated',
+            'circuit_count', 'device_count', 'prefix_count', 'rack_count', 'virtualmachine_count', 'vlan_count',
         ]
         ]
         brief_fields = ('id', 'url', 'display', 'name', 'description', 'slug')
         brief_fields = ('id', 'url', 'display', 'name', 'description', 'slug')
 
 

+ 10 - 0
netbox/dcim/constants.py

@@ -8,6 +8,16 @@ from .choices import InterfaceLAGModeChoices, InterfaceTypeChoices
 DEVICETYPE_IMAGE_FORMATS = 'image/bmp,image/gif,image/jpeg,image/png,image/tiff,image/webp'
 DEVICETYPE_IMAGE_FORMATS = 'image/bmp,image/gif,image/jpeg,image/png,image/tiff,image/webp'
 
 
 
 
+#
+# Sites
+#
+
+# WGS84 semi-major axis (meters), used as the sphere radius for Web Mercator (EPSG:3857)
+WEB_MERCATOR_EARTH_RADIUS = 6378137
+# Latitude bounds of Web Mercator, at which the projection is square
+WEB_MERCATOR_MAX_LATITUDE = 85.05112877980659
+
+
 #
 #
 # Racks
 # Racks
 #
 #

+ 18 - 0
netbox/dcim/filtersets.py

@@ -919,6 +919,14 @@ class ModuleTypeFilterSet(AttributeFiltersMixin, PrimaryModelFilterSet):
         to_field_name='slug',
         to_field_name='slug',
         label=_('Module bay type (slug)'),
         label=_('Module bay type (slug)'),
     )
     )
+    has_front_image = django_filters.BooleanFilter(
+        label=_('Has a front image'),
+        method='_has_front_image'
+    )
+    has_rear_image = django_filters.BooleanFilter(
+        label=_('Has a rear image'),
+        method='_has_rear_image'
+    )
     console_ports = django_filters.BooleanFilter(
     console_ports = django_filters.BooleanFilter(
         method='_console_ports',
         method='_console_ports',
         label=_('Has console ports'),
         label=_('Has console ports'),
@@ -979,6 +987,16 @@ class ModuleTypeFilterSet(AttributeFiltersMixin, PrimaryModelFilterSet):
             Q(comments__icontains=value)
             Q(comments__icontains=value)
         )
         )
 
 
+    def _has_front_image(self, queryset, name, value):
+        if value:
+            return queryset.exclude(front_image='')
+        return queryset.filter(front_image='')
+
+    def _has_rear_image(self, queryset, name, value):
+        if value:
+            return queryset.exclude(rear_image='')
+        return queryset.filter(rear_image='')
+
     def _console_ports(self, queryset, name, value):
     def _console_ports(self, queryset, name, value):
         return queryset.exclude(consoleporttemplates__isnull=value)
         return queryset.exclude(consoleporttemplates__isnull=value)
 
 

+ 15 - 0
netbox/dcim/forms/filtersets.py

@@ -772,6 +772,7 @@ class ModuleTypeFilterForm(PrimaryModelFilterSetForm):
             'module_bay_type_id', name=_('Hardware')
             'module_bay_type_id', name=_('Hardware')
         ),
         ),
         FieldSet('cooling_method', 'airflow', name=_('Cooling')),
         FieldSet('cooling_method', 'airflow', name=_('Cooling')),
+        FieldSet('has_front_image', 'has_rear_image', name=_('Images')),
         FieldSet(
         FieldSet(
             'console_ports', 'console_server_ports', 'power_ports', 'power_outlets', 'interfaces',
             'console_ports', 'console_server_ports', 'power_ports', 'power_outlets', 'interfaces',
             'pass_through_ports', 'module_bays', name=_('Components')
             'pass_through_ports', 'module_bays', name=_('Components')
@@ -807,6 +808,20 @@ class ModuleTypeFilterForm(PrimaryModelFilterSetForm):
         required=False,
         required=False,
         min_value=0,
         min_value=0,
     )
     )
+    has_front_image = forms.NullBooleanField(
+        required=False,
+        label=_('Has a front image'),
+        widget=forms.Select(
+            choices=BOOLEAN_WITH_BLANK_CHOICES
+        )
+    )
+    has_rear_image = forms.NullBooleanField(
+        required=False,
+        label=_('Has a rear image'),
+        widget=forms.Select(
+            choices=BOOLEAN_WITH_BLANK_CHOICES
+        )
+    )
     console_ports = forms.NullBooleanField(
     console_ports = forms.NullBooleanField(
         required=False,
         required=False,
         label=_('Has console ports'),
         label=_('Has console ports'),

+ 8 - 1
netbox/dcim/forms/model_forms.py

@@ -642,6 +642,7 @@ class ModuleTypeForm(PrimaryModelForm):
             FieldSet('cooling_method', 'airflow', name=_('Cooling')),
             FieldSet('cooling_method', 'airflow', name=_('Cooling')),
             FieldSet('module_bay_types', name=_('Bay Type Compatibility')),
             FieldSet('module_bay_types', name=_('Bay Type Compatibility')),
             FieldSet('end_of_life', name=_('Lifecycle')),
             FieldSet('end_of_life', name=_('Lifecycle')),
+            FieldSet('front_image', 'rear_image', name=_('Images')),
             FieldSet('profile', *self.attr_fields, name=_('Profile & Attributes'), html_id='profile-attributes')
             FieldSet('profile', *self.attr_fields, name=_('Profile & Attributes'), html_id='profile-attributes')
         ]
         ]
 
 
@@ -649,9 +650,15 @@ class ModuleTypeForm(PrimaryModelForm):
         model = ModuleType
         model = ModuleType
         fields = [
         fields = [
             'profile', 'manufacturer', 'model', 'part_number', 'description', 'cooling_method', 'airflow', 'weight',
             'profile', 'manufacturer', 'model', 'part_number', 'description', 'cooling_method', 'airflow', 'weight',
-            'weight_unit', 'module_bay_types', 'end_of_life', 'owner', 'comments', 'tags',
+            'weight_unit', 'module_bay_types', 'end_of_life', 'front_image', 'rear_image', 'owner', 'comments', 'tags',
         ]
         ]
         widgets = {
         widgets = {
+            'front_image': ClearableFileInput(attrs={
+                'accept': DEVICETYPE_IMAGE_FORMATS
+            }),
+            'rear_image': ClearableFileInput(attrs={
+                'accept': DEVICETYPE_IMAGE_FORMATS
+            }),
             'end_of_life': DatePicker(),
             'end_of_life': DatePicker(),
         }
         }
 
 

+ 2 - 0
netbox/dcim/graphql/filters.py

@@ -865,6 +865,8 @@ class ModuleTypeFilter(ImageAttachmentFilterMixin, WeightFilterMixin, PrimaryMod
         strawberry_django.filter_field()
         strawberry_django.filter_field()
     )
     )
     end_of_life: DateFilterLookup | None = strawberry_django.filter_field()
     end_of_life: DateFilterLookup | 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 = (
     consoleporttemplates: Annotated['ConsolePortTemplateFilter', strawberry.lazy('dcim.graphql.filters')] | None = (
         strawberry_django.filter_field(name='console_port_templates')
         strawberry_django.filter_field(name='console_port_templates')
     )
     )

+ 14 - 0
netbox/dcim/graphql/mixins.py

@@ -1,6 +1,7 @@
 from typing import TYPE_CHECKING, Annotated
 from typing import TYPE_CHECKING, Annotated
 
 
 import strawberry
 import strawberry
+import strawberry_django
 
 
 if TYPE_CHECKING:
 if TYPE_CHECKING:
     from circuits.graphql.types import CircuitTerminationType, ProviderNetworkType, VirtualCircuitTerminationType
     from circuits.graphql.types import CircuitTerminationType, ProviderNetworkType, VirtualCircuitTerminationType
@@ -19,6 +20,7 @@ if TYPE_CHECKING:
 __all__ = (
 __all__ = (
     'CabledObjectMixin',
     'CabledObjectMixin',
     'PathEndpointMixin',
     'PathEndpointMixin',
+    'WebMercatorMixin',
 )
 )
 
 
 
 
@@ -61,3 +63,15 @@ class PathEndpointMixin:
             strawberry.union("ConnectedEndpointType"),
             strawberry.union("ConnectedEndpointType"),
         ]
         ]
     ]
     ]
+
+
+@strawberry.type
+class WebMercatorMixin:
+
+    @strawberry_django.field(only=['latitude', 'longitude'])
+    def mercator_x(self) -> float | None:
+        return self.mercator_x
+
+    @strawberry_django.field(only=['latitude', 'longitude'])
+    def mercator_y(self) -> float | None:
+        return self.mercator_y

+ 5 - 3
netbox/dcim/graphql/types.py

@@ -26,7 +26,7 @@ from utilities.querysets import RestrictedPrefetch
 from virtualization.models import Cluster, VMInterface
 from virtualization.models import Cluster, VMInterface
 
 
 from .filters import *
 from .filters import *
-from .mixins import CabledObjectMixin, PathEndpointMixin
+from .mixins import CabledObjectMixin, PathEndpointMixin, WebMercatorMixin
 
 
 if TYPE_CHECKING:
 if TYPE_CHECKING:
     from circuits.graphql.types import CircuitTerminationType
     from circuits.graphql.types import CircuitTerminationType
@@ -327,7 +327,7 @@ class ConsoleServerPortTemplateType(ModularComponentTemplateType):
     filters=DeviceFilter,
     filters=DeviceFilter,
     pagination=True
     pagination=True
 )
 )
-class DeviceType(ConfigContextMixin, ImageAttachmentsMixin, ContactsMixin, PrimaryObjectType):
+class DeviceType(ConfigContextMixin, ImageAttachmentsMixin, ContactsMixin, WebMercatorMixin, PrimaryObjectType):
     console_port_count: BigInt
     console_port_count: BigInt
     console_server_port_count: BigInt
     console_server_port_count: BigInt
     power_port_count: BigInt
     power_port_count: BigInt
@@ -809,6 +809,8 @@ class ModuleTypeType(PrimaryObjectType):
     front_port_template_count: BigInt
     front_port_template_count: BigInt
     rear_port_template_count: BigInt
     rear_port_template_count: BigInt
     module_bay_template_count: BigInt
     module_bay_template_count: BigInt
+    front_image: strawberry_django.fields.types.DjangoImageType | None
+    rear_image: strawberry_django.fields.types.DjangoImageType | None
     profile: Annotated["ModuleTypeProfileType", strawberry.lazy('dcim.graphql.types')] | None
     profile: Annotated["ModuleTypeProfileType", strawberry.lazy('dcim.graphql.types')] | None
     manufacturer: Annotated["ManufacturerType", strawberry.lazy('dcim.graphql.types')]
     manufacturer: Annotated["ManufacturerType", strawberry.lazy('dcim.graphql.types')]
     module_bay_types: list[Annotated["ModuleBayTypeType", strawberry.lazy('dcim.graphql.types')]]
     module_bay_types: list[Annotated["ModuleBayTypeType", strawberry.lazy('dcim.graphql.types')]]
@@ -1145,7 +1147,7 @@ class RegionType(VLANGroupsMixin, ContactsMixin, NestedLtreeGroupObjectType):
     filters=SiteFilter,
     filters=SiteFilter,
     pagination=True
     pagination=True
 )
 )
-class SiteType(VLANGroupsMixin, ImageAttachmentsMixin, ContactsMixin, PrimaryObjectType):
+class SiteType(VLANGroupsMixin, ImageAttachmentsMixin, ContactsMixin, WebMercatorMixin, PrimaryObjectType):
     time_zone: str | None
     time_zone: str | None
     region: Annotated["RegionType", strawberry.lazy('dcim.graphql.types')] | None
     region: Annotated["RegionType", strawberry.lazy('dcim.graphql.types')] | None
     group: Annotated["SiteGroupType", strawberry.lazy('dcim.graphql.types')] | None
     group: Annotated["SiteGroupType", strawberry.lazy('dcim.graphql.types')] | None

+ 21 - 0
netbox/dcim/migrations/0254_moduletype_images.py

@@ -0,0 +1,21 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('dcim', '0253_macblock'),
+    ]
+
+    operations = [
+        migrations.AddField(
+            model_name='moduletype',
+            name='front_image',
+            field=models.ImageField(blank=True, upload_to='moduletype-images'),
+        ),
+        migrations.AddField(
+            model_name='moduletype',
+            name='rear_image',
+            field=models.ImageField(blank=True, upload_to='moduletype-images'),
+        ),
+    ]

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

@@ -36,7 +36,7 @@ from utilities.prefetch import get_prefetchable_fields
 from utilities.tracking import TrackingModelMixin
 from utilities.tracking import TrackingModelMixin
 
 
 from .device_components import *
 from .device_components import *
-from .mixins import RenderConfigMixin
+from .mixins import RenderConfigMixin, WebMercatorMixin
 from .modules import Module
 from .modules import Module
 
 
 __all__ = (
 __all__ = (
@@ -553,6 +553,7 @@ class Device(
     ContactsMixin,
     ContactsMixin,
     ImageAttachmentsMixin,
     ImageAttachmentsMixin,
     RenderConfigMixin,
     RenderConfigMixin,
+    WebMercatorMixin,
     ConfigContextModel,
     ConfigContextModel,
     TrackingModelMixin,
     TrackingModelMixin,
     PrimaryModel
     PrimaryModel

+ 51 - 1
netbox/dcim/models/mixins.py

@@ -1,3 +1,4 @@
+import math
 from decimal import Decimal
 from decimal import Decimal
 
 
 from django.apps import apps
 from django.apps import apps
@@ -8,7 +9,13 @@ from django.db import IntegrityError, models, transaction
 from django.utils.translation import gettext_lazy as _
 from django.utils.translation import gettext_lazy as _
 
 
 from dcim.choices import InterfaceTypeChoices
 from dcim.choices import InterfaceTypeChoices
-from dcim.constants import NONCONNECTABLE_IFACE_TYPES, VIRTUAL_IFACE_TYPES, WIRELESS_IFACE_TYPES
+from dcim.constants import (
+    NONCONNECTABLE_IFACE_TYPES,
+    VIRTUAL_IFACE_TYPES,
+    WEB_MERCATOR_EARTH_RADIUS,
+    WEB_MERCATOR_MAX_LATITUDE,
+    WIRELESS_IFACE_TYPES,
+)
 from netbox.choices import *
 from netbox.choices import *
 from utilities.conversion import (
 from utilities.conversion import (
     DIAMETER_TO_MILLIMETERS,
     DIAMETER_TO_MILLIMETERS,
@@ -26,10 +33,14 @@ __all__ = (
     'InterfaceValidationMixin',
     'InterfaceValidationMixin',
     'MaxFlowMixin',
     'MaxFlowMixin',
     'RenderConfigMixin',
     'RenderConfigMixin',
+    'WebMercatorMixin',
 )
 )
 
 
 
 
 class RenderConfigMixin(models.Model):
 class RenderConfigMixin(models.Model):
+    """
+    Enables rendering an object's configuration from a ConfigTemplate. Must be combined with ConfigContextModel.
+    """
     config_template = models.ForeignKey(
     config_template = models.ForeignKey(
         to='extras.ConfigTemplate',
         to='extras.ConfigTemplate',
         on_delete=models.PROTECT,
         on_delete=models.PROTECT,
@@ -53,6 +64,26 @@ class RenderConfigMixin(models.Model):
             return self.platform.config_template
             return self.platform.config_template
         return None
         return None
 
 
+    def get_render_context(self, extra_context=None):
+        """
+        Return the context for rendering this object's config template: its config context data, then any extra
+        context, then the object itself under its model name.
+        """
+        context = self.get_config_context()
+        context.update(extra_context or {})
+        context[self._meta.model_name] = self
+        return context
+
+    def render_config(self, config_template=None, extra_context=None):
+        """
+        Render this object's configuration using the given ConfigTemplate, or the one resolved by
+        get_config_template(). Returns None if no template applies; rendering errors propagate to the caller.
+        """
+        config_template = config_template or self.get_config_template()
+        if config_template is None:
+            return None
+        return config_template.render(context=self.get_render_context(extra_context))
+
 
 
 class CachedScopeMixin(models.Model):
 class CachedScopeMixin(models.Model):
     """
     """
@@ -500,3 +531,22 @@ class MaxFlowMixin(models.Model):
         # Validate max_flow and max_flow_unit
         # Validate max_flow and max_flow_unit
         if self.max_flow is not None and not self.max_flow_unit:
         if self.max_flow is not None and not self.max_flow_unit:
             raise ValidationError(_("Must specify a unit when setting a maximum flow"))
             raise ValidationError(_("Must specify a unit when setting a maximum flow"))
+
+
+class WebMercatorMixin:
+    """
+    Provides read-only Web Mercator (EPSG:3857) coordinates calculated from a model's latitude and longitude.
+    """
+    @property
+    def mercator_x(self):
+        if self.latitude is None or self.longitude is None:
+            return None
+        return round(math.radians(float(self.longitude)) * WEB_MERCATOR_EARTH_RADIUS, 2)
+
+    @property
+    def mercator_y(self):
+        if self.latitude is None or self.longitude is None:
+            return None
+        # Web Mercator is undefined at the poles; clamp latitude to the projection's bounds
+        latitude = max(-WEB_MERCATOR_MAX_LATITUDE, min(float(self.latitude), WEB_MERCATOR_MAX_LATITUDE))
+        return round(math.log(math.tan(math.pi / 4 + math.radians(latitude) / 2)) * WEB_MERCATOR_EARTH_RADIUS, 2)

+ 44 - 0
netbox/dcim/models/modules.py

@@ -1,4 +1,5 @@
 from collections.abc import Iterable, Mapping
 from collections.abc import Iterable, Mapping
+from functools import partial
 
 
 import jsonschema
 import jsonschema
 import yaml
 import yaml
@@ -165,6 +166,14 @@ class ModuleType(ImageAttachmentsMixin, PrimaryModel, WeightMixin):
         null=True,
         null=True,
         help_text=_('The date after which this module type is no longer supported by the manufacturer')
         help_text=_('The date after which this module type is no longer supported by the manufacturer')
     )
     )
+    front_image = models.ImageField(
+        upload_to='moduletype-images',
+        blank=True
+    )
+    rear_image = models.ImageField(
+        upload_to='moduletype-images',
+        blank=True
+    )
     attribute_data = models.JSONField(
     attribute_data = models.JSONField(
         blank=True,
         blank=True,
         null=True,
         null=True,
@@ -319,6 +328,41 @@ class ModuleType(ImageAttachmentsMixin, PrimaryModel, WeightMixin):
         else:
         else:
             self.attribute_data = None
             self.attribute_data = None
 
 
+    def save(self, *args, **kwargs):
+        update_fields = normalize_update_fields(kwargs)
+        using = kwargs.get('using') or router.db_for_write(self.__class__, instance=self)
+        deferred_fields = self.get_deferred_fields()
+        image_fields = [
+            name for name in ('front_image', 'rear_image')
+            if name not in deferred_fields and (update_fields is None or name in update_fields)
+        ]
+
+        # Read persisted filenames only for image fields included in this save.
+        original_images = {}
+        if self.pk is not None and image_fields:
+            original_images = (
+                ModuleType.objects.using(using).filter(pk=self.pk).order_by().values(*image_fields).first() or {}
+            )
+
+        kwargs['using'] = using
+        ret = super().save(*args, **kwargs)
+
+        for field_name, name in original_images.items():
+            if name and getattr(self, field_name).name != name:
+                transaction.on_commit(
+                    partial(self._delete_image_file, field_name, name, using), using=using, robust=True
+                )
+
+        return ret
+
+    @classmethod
+    def _delete_image_file(cls, field_name, name, using):
+        """
+        Delete an image file only when no module type still references it.
+        """
+        if not cls.objects.using(using).filter(models.Q(front_image=name) | models.Q(rear_image=name)).exists():
+            cls._meta.get_field(field_name).storage.delete(name)
+
     def get_cooling_method_color(self):
     def get_cooling_method_color(self):
         return CoolingMethodChoices.colors.get(self.cooling_method)
         return CoolingMethodChoices.colors.get(self.cooling_method)
 
 

+ 3 - 1
netbox/dcim/models/sites.py

@@ -13,6 +13,8 @@ from dcim.constants import *
 from netbox.models import NestedLtreeGroupModel, PrimaryModel
 from netbox.models import NestedLtreeGroupModel, PrimaryModel
 from netbox.models.features import ContactsMixin, ImageAttachmentsMixin
 from netbox.models.features import ContactsMixin, ImageAttachmentsMixin
 
 
+from .mixins import WebMercatorMixin
+
 __all__ = (
 __all__ = (
     'Location',
     'Location',
     'Region',
     'Region',
@@ -167,7 +169,7 @@ class SiteGroup(ContactsMixin, NestedLtreeGroupModel):
 # Sites
 # Sites
 #
 #
 
 
-class Site(ContactsMixin, ImageAttachmentsMixin, PrimaryModel):
+class Site(ContactsMixin, ImageAttachmentsMixin, WebMercatorMixin, PrimaryModel):
     """
     """
     A Site represents a geographic location within a network; typically a building or campus. The optional facility
     A Site represents a geographic location within a network; typically a building or campus. The optional facility
     field can be used to include an external designation, such as a data center name (e.g. Equinix SV6).
     field can be used to include an external designation, such as a data center name (e.g. Equinix SV6).

+ 20 - 1
netbox/dcim/signals.py

@@ -1,8 +1,9 @@
 import logging
 import logging
+from functools import partial
 
 
 from django.db import transaction
 from django.db import transaction
 from django.db.models import Q
 from django.db.models import Q
-from django.db.models.signals import post_delete, post_save, pre_save
+from django.db.models.signals import post_delete, post_save, pre_delete, pre_save
 from django.dispatch import receiver
 from django.dispatch import receiver
 
 
 from dcim.choices import CableEndChoices, LinkStatusChoices
 from dcim.choices import CableEndChoices, LinkStatusChoices
@@ -17,6 +18,7 @@ from .models import (
     Device,
     Device,
     Interface,
     Interface,
     Location,
     Location,
+    ModuleType,
     PathEndpoint,
     PathEndpoint,
     PortMapping,
     PortMapping,
     PowerPanel,
     PowerPanel,
@@ -503,3 +505,20 @@ def update_mac_address_interface(instance, created, raw, **kwargs):
     if created and not raw and instance.primary_mac_address:
     if created and not raw and instance.primary_mac_address:
         instance.primary_mac_address.assigned_object = instance
         instance.primary_mac_address.assigned_object = instance
         instance.primary_mac_address.save()
         instance.primary_mac_address.save()
+
+
+#
+# Module types
+#
+
+@receiver(pre_delete, sender=ModuleType)
+def delete_module_type_images(sender, instance, using, **kwargs):
+    """
+    Remove stored module type images after the deletion commits.
+    """
+    images = (
+        sender.objects.using(using).filter(pk=instance.pk).order_by().values('front_image', 'rear_image').first() or {}
+    )
+    for field_name, name in images.items():
+        if name:
+            transaction.on_commit(partial(sender._delete_image_file, field_name, name, using), using=using, robust=True)

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

@@ -458,6 +458,27 @@ class SiteTestCase(APIViewTestCases.APIViewTestCase):
         self.assertNotIn('remove_tags', response.data)
         self.assertNotIn('remove_tags', response.data)
         self.assertIn('tags', response.data)
         self.assertIn('tags', response.data)
 
 
+    def test_web_mercator_coordinates(self):
+        """
+        Web Mercator coordinates are calculated from the GPS coordinates and cannot be written.
+        """
+        obj_perm = ObjectPermission(name='Test permission', actions=['change'])
+        obj_perm.save()
+        obj_perm.users.add(self.user)
+        obj_perm.object_types.add(ObjectType.objects.get_for_model(self.model))
+
+        site = Site.objects.first()
+        data = {
+            'latitude': 40.7128,
+            'longitude': -74.006,
+            'mercator_x': 1,
+            'mercator_y': 1,
+        }
+        response = self.client.patch(self._get_detail_url(site), data, format='json', **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        self.assertEqual(response.data['mercator_x'], -8238310.24)
+        self.assertEqual(response.data['mercator_y'], 4970071.58)
+
     def test_remove_tags(self):
     def test_remove_tags(self):
         """
         """
         Remove tags from an existing object via the remove_tags field.
         Remove tags from an existing object via the remove_tags field.
@@ -1808,6 +1829,23 @@ class ModuleTypeTestCase(APIViewTestCases.APIViewTestCase):
         'airflow': 'not-a-valid-airflow',
         'airflow': 'not-a-valid-airflow',
     }
     }
     user_permissions = ('dcim.view_manufacturer', )
     user_permissions = ('dcim.view_manufacturer', )
+    graphql_filter_tests = (
+        GraphQLFilterTest(
+            name='front_image__exact',
+            filters='front_image: {exact: "moduletype-images/front2.png"}',
+            expected=lambda qs: qs.filter(model='Module Type 2'),
+        ),
+        GraphQLFilterTest(
+            name='rear_image__exact',
+            filters='rear_image: {exact: "moduletype-images/rear3.png"}',
+            expected=lambda qs: qs.filter(model='Module Type 3'),
+        ),
+        GraphQLFilterTest(
+            name='front_image__exact_empty',
+            filters='front_image: {exact: ""}',
+            expected=lambda qs: qs.filter(model__in=['Module Type 1', 'Module Type 3']),
+        ),
+    )
 
 
     @classmethod
     @classmethod
     def setUpTestData(cls):
     def setUpTestData(cls):
@@ -1820,8 +1858,16 @@ class ModuleTypeTestCase(APIViewTestCases.APIViewTestCase):
 
 
         module_types = (
         module_types = (
             ModuleType(manufacturer=manufacturers[0], model='Module Type 1'),
             ModuleType(manufacturer=manufacturers[0], model='Module Type 1'),
-            ModuleType(manufacturer=manufacturers[0], model='Module Type 2'),
-            ModuleType(manufacturer=manufacturers[0], model='Module Type 3'),
+            ModuleType(
+                manufacturer=manufacturers[0],
+                model='Module Type 2',
+                front_image='moduletype-images/front2.png',
+            ),
+            ModuleType(
+                manufacturer=manufacturers[0],
+                model='Module Type 3',
+                rear_image='moduletype-images/rear3.png',
+            ),
         )
         )
         ModuleType.objects.bulk_create(module_types)
         ModuleType.objects.bulk_create(module_types)
 
 
@@ -1851,6 +1897,80 @@ class ModuleTypeTestCase(APIViewTestCases.APIViewTestCase):
             },
             },
         ]
         ]
 
 
+    def test_create_object_with_images(self):
+        """
+        Create a ModuleType with front/rear images via a multipart request.
+        """
+        self.add_permissions('dcim.add_moduletype')
+        # A nested field is read from "<field>.id" in a multipart request
+        data = {
+            'manufacturer.id': Manufacturer.objects.first().pk,
+            'model': 'Module Type 7',
+            'front_image': create_test_image('front.png'),
+            'rear_image': create_test_image('rear.png'),
+        }
+
+        with tempfile.TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root):
+            response = self.client.post(self._get_list_url(), data, format='multipart', **self.header)
+            self.assertHttpStatus(response, status.HTTP_201_CREATED)
+            module_type = ModuleType.objects.get(pk=response.data['id'])
+            for image in (module_type.front_image, module_type.rear_image):
+                self.assertTrue(os.path.exists(image.path))
+                self.assertTrue(image.name.startswith('moduletype-images/'))
+
+    def test_update_object_image(self):
+        """
+        Replace a ModuleType's front image via a multipart request, which should delete the original file.
+        """
+        self.add_permissions('dcim.change_moduletype')
+
+        with tempfile.TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root):
+            module_type = ModuleType.objects.first()
+            module_type.front_image = create_test_image('front.png')
+            module_type.rear_image = create_test_image('rear.png')
+            module_type.save()
+            front_image_path = module_type.front_image.path
+            rear_image_path = module_type.rear_image.path
+
+            data = {
+                'front_image': create_test_image('front2.png'),
+            }
+            with self.captureOnCommitCallbacks(execute=True):
+                response = self.client.patch(
+                    self._get_detail_url(module_type), data, format='multipart', **self.header
+                )
+            self.assertHttpStatus(response, status.HTTP_200_OK)
+            module_type.refresh_from_db()
+            self.assertFalse(os.path.exists(front_image_path))
+            self.assertTrue(os.path.exists(module_type.front_image.path))
+            self.assertNotEqual(module_type.front_image.path, front_image_path)
+            self.assertTrue(os.path.exists(rear_image_path))
+
+    def test_clear_object_image(self):
+        """
+        Clear a ModuleType's rear image via a JSON request, which should delete its file.
+        """
+        self.add_permissions('dcim.change_moduletype')
+
+        with tempfile.TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root):
+            module_type = ModuleType.objects.first()
+            module_type.front_image = create_test_image('front.png')
+            module_type.rear_image = create_test_image('rear.png')
+            module_type.save()
+            front_image_path = module_type.front_image.path
+            rear_image_path = module_type.rear_image.path
+
+            with self.captureOnCommitCallbacks(execute=True):
+                response = self.client.patch(
+                    self._get_detail_url(module_type), {'rear_image': None}, format='json', **self.header
+                )
+            self.assertHttpStatus(response, status.HTTP_200_OK)
+            self.assertIsNone(response.data['rear_image'])
+            module_type.refresh_from_db()
+            self.assertFalse(module_type.rear_image)
+            self.assertFalse(os.path.exists(rear_image_path))
+            self.assertTrue(os.path.exists(front_image_path))
+
 
 
 class ModuleTypeProfileTestCase(APIViewTestCases.APIViewTestCase):
 class ModuleTypeProfileTestCase(APIViewTestCases.APIViewTestCase):
     model = ModuleTypeProfile
     model = ModuleTypeProfile
@@ -3090,6 +3210,23 @@ class DeviceTestCase(Mixins.FieldPrefetchMixin, APIViewTestCases.APIViewTestCase
 
 
         self.assertHttpStatus(response, status.HTTP_400_BAD_REQUEST)
         self.assertHttpStatus(response, status.HTTP_400_BAD_REQUEST)
 
 
+    def test_web_mercator_coordinates(self):
+        """
+        Web Mercator coordinates are calculated from the GPS coordinates and cannot be written.
+        """
+        self.add_permissions('dcim.change_device')
+        device = Device.objects.first()
+        data = {
+            'latitude': 40.7128,
+            'longitude': -74.006,
+            'mercator_x': 1,
+            'mercator_y': 1,
+        }
+        response = self.client.patch(self._get_detail_url(device), data, format='json', **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        self.assertEqual(response.data['mercator_x'], -8238310.24)
+        self.assertEqual(response.data['mercator_y'], 4970071.58)
+
     def test_create_device_replicates_components(self):
     def test_create_device_replicates_components(self):
         """
         """
         Creating a device without specifying replicate_components should instantiate its device type's components.
         Creating a device without specifying replicate_components should instantiate its device type's components.
@@ -3200,6 +3337,32 @@ class DeviceTestCase(Mixins.FieldPrefetchMixin, APIViewTestCases.APIViewTestCase
         self.assertHttpStatus(response, status.HTTP_200_OK)
         self.assertHttpStatus(response, status.HTTP_200_OK)
         self.assertEqual(response.data['content'], f'Config for device {device.name}')
         self.assertEqual(response.data['content'], f'Config for device {device.name}')
 
 
+    def test_render_config_matches_model(self):
+        """
+        The rendered config returned by the REST API matches the output of Device.render_config().
+        """
+        device = Device.objects.first()
+        device.config_template = ConfigTemplate.objects.create(
+            name='Config Template 1',
+            template_code='hostname {{ device.name }}\nntp server {{ ntp_server }}\nsyslog {{ syslog_server }}\n'
+        )
+        device.local_context_data = {'ntp_server': '192.0.2.1'}
+        device.save()
+
+        self.add_permissions('dcim.render_config_device', 'dcim.view_device')
+        url = reverse('dcim-api:device-render-config', kwargs={'pk': device.pk})
+        data = {'syslog_server': '192.0.2.2', 'device': 'spoofed'}
+        response = self.client.post(url, data, format='json', **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        self.assertEqual(
+            response.data['content'],
+            f'hostname {device.name}\nntp server 192.0.2.1\nsyslog 192.0.2.2'
+        )
+        self.assertEqual(
+            response.data['content'],
+            Device.objects.get(pk=device.pk).render_config(extra_context=data)
+        )
+
     def test_render_config_leaves_config_context_cache_unchanged(self):
     def test_render_config_leaves_config_context_cache_unchanged(self):
         """
         """
         A config template which mutates nested context data leaves the cached config context unchanged.
         A config template which mutates nested context data leaves the cached config context unchanged.

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

@@ -1697,7 +1697,7 @@ class DeviceTypeTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
 class ModuleTypeTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
 class ModuleTypeTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
     queryset = ModuleType.objects.all()
     queryset = ModuleType.objects.all()
     filterset = ModuleTypeFilterSet
     filterset = ModuleTypeFilterSet
-    ignore_fields = ['attribute_data']
+    ignore_fields = ['attribute_data', 'front_image', 'rear_image']
 
 
     PROFILE_SCHEMA = {
     PROFILE_SCHEMA = {
         "properties": {
         "properties": {
@@ -1744,6 +1744,8 @@ class ModuleTypeTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
                 airflow=ModuleAirflowChoices.FRONT_TO_REAR,
                 airflow=ModuleAirflowChoices.FRONT_TO_REAR,
                 cooling_method=CoolingMethodChoices.METHOD_LIQUID,
                 cooling_method=CoolingMethodChoices.METHOD_LIQUID,
                 end_of_life='2030-01-01',
                 end_of_life='2030-01-01',
+                front_image='moduletype-images/front1.png',
+                rear_image='moduletype-images/rear1.png',
                 profile=module_type_profiles[0],
                 profile=module_type_profiles[0],
                 attribute_data={
                 attribute_data={
                     'string': 'string1',
                     'string': 'string1',
@@ -1762,6 +1764,7 @@ class ModuleTypeTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
                 airflow=ModuleAirflowChoices.REAR_TO_FRONT,
                 airflow=ModuleAirflowChoices.REAR_TO_FRONT,
                 cooling_method=CoolingMethodChoices.METHOD_HYBRID,
                 cooling_method=CoolingMethodChoices.METHOD_HYBRID,
                 end_of_life='2035-06-30',
                 end_of_life='2035-06-30',
+                front_image='moduletype-images/front2.png',
                 profile=module_type_profiles[1],
                 profile=module_type_profiles[1],
                 attribute_data={
                 attribute_data={
                     'string': 'string2',
                     'string': 'string2',
@@ -1901,6 +1904,24 @@ class ModuleTypeTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
         params = {'module_bays': 'false'}
         params = {'module_bays': 'false'}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
 
 
+    def test_has_front_image(self):
+        """
+        Filter by the presence of a front image.
+        """
+        params = {'has_front_image': True}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+        params = {'has_front_image': False}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+
+    def test_has_rear_image(self):
+        """
+        Filter by the presence of a rear image.
+        """
+        params = {'has_rear_image': True}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+        params = {'has_rear_image': False}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+
     def test_weight(self):
     def test_weight(self):
         params = {'weight': [10, 20]}
         params = {'weight': [10, 20]}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)

+ 49 - 2
netbox/dcim/tests/test_forms.py

@@ -1,8 +1,9 @@
+import tempfile
 from unittest.mock import patch
 from unittest.mock import patch
 
 
 from django import forms
 from django import forms
 from django.template.loader import render_to_string
 from django.template.loader import render_to_string
-from django.test import TestCase
+from django.test import TestCase, override_settings
 
 
 from circuits.models import CircuitTermination
 from circuits.models import CircuitTermination
 from dcim.choices import (
 from dcim.choices import (
@@ -25,7 +26,7 @@ from dcim.tests.test_module_moves import fail_after
 from ipam.models import ASN, RIR, VLAN
 from ipam.models import ASN, RIR, VLAN
 from utilities.exceptions import AbortRequest
 from utilities.exceptions import AbortRequest
 from utilities.forms.rendering import M2MAddRemoveFields
 from utilities.forms.rendering import M2MAddRemoveFields
-from utilities.testing import create_test_device
+from utilities.testing import create_test_device, create_test_image
 from virtualization.models import Cluster, ClusterGroup, ClusterType
 from virtualization.models import Cluster, ClusterGroup, ClusterType
 
 
 
 
@@ -282,6 +283,52 @@ class ModuleTypeFormTestCase(TestCase):
             },
             },
         )
         )
 
 
+    def test_upload_and_clear_images(self):
+        """
+        Upload images through the form, then clear the front image, which should delete only its file.
+        """
+        data = {
+            'manufacturer': self.manufacturer.pk,
+            'model': 'Module Type 1',
+            'profile': self.profile.pk,
+            'attr_media': ['copper', 'qsfp28'],
+        }
+        form = ModuleTypeForm(data=data, files={
+            'front_image': create_test_image('front.png'),
+            'rear_image': create_test_image('rear.png'),
+        })
+        # A profile change re-renders only the profile-attributes fieldset, which must not hold a picked file
+        profile_fieldset = next(fieldset for fieldset in form.fieldsets if fieldset.html_id == 'profile-attributes')
+        self.assertNotIn('front_image', profile_fieldset.items)
+        self.assertNotIn('rear_image', profile_fieldset.items)
+        self.assertTrue(form.is_multipart())
+
+        with (
+            tempfile.TemporaryDirectory() as media_root,
+            override_settings(MEDIA_ROOT=media_root),
+            patch('utilities.forms.fields.dynamic.get_action_url', return_value='/'),
+        ):
+            self.assertTrue(form.is_valid(), form.errors)
+            module_type = form.save()
+            front_image_name = module_type.front_image.name
+            rear_image_name = module_type.rear_image.name
+            storage = module_type.front_image.storage
+            self.assertTrue(storage.exists(front_image_name))
+            self.assertTrue(storage.exists(rear_image_name))
+            self.assertEqual(module_type.attribute_data, {'media': ['copper', 'qsfp28']})
+
+            form = ModuleTypeForm(data={**data, 'front_image-clear': True}, instance=module_type)
+            self.assertTrue(form.is_valid(), form.errors)
+            with self.captureOnCommitCallbacks(execute=True):
+                form.save()
+
+            module_type.refresh_from_db()
+            self.assertFalse(module_type.front_image)
+            self.assertEqual(module_type.rear_image.name, rear_image_name)
+            self.assertFalse(storage.exists(front_image_name))
+            self.assertTrue(storage.exists(rear_image_name))
+            self.assertEqual(module_type.attribute_data, {'media': ['copper', 'qsfp28']})
+
     def test_enum_array_attribute_uses_multiselect_field(self):
     def test_enum_array_attribute_uses_multiselect_field(self):
         form = ModuleTypeForm(data={
         form = ModuleTypeForm(data={
             'manufacturer': self.manufacturer.pk,
             'manufacturer': self.manufacturer.pk,

+ 212 - 1
netbox/dcim/tests/test_models.py

@@ -4,6 +4,7 @@ import uuid
 from decimal import Decimal
 from decimal import Decimal
 from unittest.mock import patch
 from unittest.mock import patch
 
 
+from django.conf import settings
 from django.core.exceptions import ValidationError
 from django.core.exceptions import ValidationError
 from django.db import IntegrityError, connection, transaction
 from django.db import IntegrityError, connection, transaction
 from django.db.models import ProtectedError
 from django.db.models import ProtectedError
@@ -11,6 +12,7 @@ from django.db.models.signals import post_save
 from django.test import RequestFactory, TestCase, override_settings, tag
 from django.test import RequestFactory, TestCase, override_settings, tag
 from django.test.utils import CaptureQueriesContext
 from django.test.utils import CaptureQueriesContext
 from django.utils.text import slugify
 from django.utils.text import slugify
+from jinja2 import TemplateSyntaxError
 from netaddr import EUI
 from netaddr import EUI
 
 
 from circuits.models import *
 from circuits.models import *
@@ -20,7 +22,7 @@ from dcim.choices import *
 from dcim.models import *
 from dcim.models import *
 from dcim.utils import resolve_module_placeholder
 from dcim.utils import resolve_module_placeholder
 from extras.events import serialize_for_event
 from extras.events import serialize_for_event
-from extras.models import CustomField
+from extras.models import ConfigTemplate, CustomField
 from ipam.models import IPAddress, Prefix
 from ipam.models import IPAddress, Prefix
 from netbox.choices import DiameterUnitChoices, FlowRateUnitChoices, WeightUnitChoices
 from netbox.choices import DiameterUnitChoices, FlowRateUnitChoices, WeightUnitChoices
 from netbox.context_managers import event_tracking
 from netbox.context_managers import event_tracking
@@ -130,6 +132,31 @@ class MACAddressTestCase(TestCase):
         new_iface.full_clean()  # must not raise
         new_iface.full_clean()  # must not raise
 
 
 
 
+class WebMercatorTestCase(TestCase):
+
+    def test_web_mercator_coordinates(self):
+        for model in (Site, Device):
+            with self.subTest(model=model.__name__):
+                obj = model(latitude=Decimal('40.712800'), longitude=Decimal('-74.006000'))
+                self.assertEqual(obj.mercator_x, -8238310.24)
+                self.assertEqual(obj.mercator_y, 4970071.58)
+
+    def test_web_mercator_coordinates_missing_gps(self):
+        for latitude, longitude in ((None, None), (Decimal('10'), None), (None, Decimal('10'))):
+            site = Site(latitude=latitude, longitude=longitude)
+            self.assertIsNone(site.mercator_x)
+            self.assertIsNone(site.mercator_y)
+
+    def test_web_mercator_coordinates_at_poles(self):
+        site = Site(latitude=Decimal('90'), longitude=Decimal('180'))
+        self.assertEqual(site.mercator_x, 20037508.34)
+        self.assertEqual(site.mercator_y, 20037508.34)
+
+        site = Site(latitude=Decimal('-90'), longitude=Decimal('-180'))
+        self.assertEqual(site.mercator_x, -20037508.34)
+        self.assertEqual(site.mercator_y, -20037508.34)
+
+
 class MACBlockTestCase(TestCase):
 class MACBlockTestCase(TestCase):
 
 
     def test_prefix_normalized(self):
     def test_prefix_normalized(self):
@@ -671,6 +698,144 @@ class ModuleTypeTestCase(TestCase):
         )
         )
 
 
 
 
+class ModuleTypeImageTestCase(TestCase):
+    """
+    Test the handling of ModuleType front/rear image files.
+    """
+    def setUp(self):
+        media_root = self.enterContext(tempfile.TemporaryDirectory())
+        self.enterContext(override_settings(MEDIA_ROOT=media_root))
+        self.manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
+
+    def _create_module_type(self, model='Module Type 1'):
+        """
+        Create a ModuleType with an uploaded front and rear image.
+        """
+        return ModuleType.objects.create(
+            manufacturer=self.manufacturer,
+            model=model,
+            front_image=create_test_image('front.png'),
+            rear_image=create_test_image('rear.png'),
+        )
+
+    def test_saves_without_image_fields_preserve_files(self):
+        """
+        A save which leaves out or defers the image fields should keep the stored files.
+        """
+        module_type = self._create_module_type()
+        front_image_name = module_type.front_image.name
+        storage = module_type.front_image.storage
+        module_type.front_image = create_test_image('replacement.png')
+        module_type.description = 'Updated description'
+
+        with self.captureOnCommitCallbacks(execute=True):
+            module_type.save(update_fields=iter(['description']))
+
+        self.assertTrue(storage.exists(front_image_name))
+        module_type = ModuleType.objects.defer('front_image', 'rear_image').get(pk=module_type.pk)
+        module_type.description = 'Another description'
+        with self.captureOnCommitCallbacks(execute=True):
+            module_type.save()
+
+        self.assertTrue({'front_image', 'rear_image'}.issubset(module_type.get_deferred_fields()))
+        module_type.refresh_from_db()
+        self.assertEqual(module_type.front_image.name, front_image_name)
+        self.assertTrue(storage.exists(front_image_name))
+
+    def test_image_restored_before_commit(self):
+        """
+        Restoring the original image before the transaction commits should keep it and delete the replacement.
+        """
+        module_type = self._create_module_type()
+        original_name = module_type.front_image.name
+        storage = module_type.front_image.storage
+
+        with self.captureOnCommitCallbacks(execute=True):
+            module_type.front_image = create_test_image('replacement.png')
+            module_type.save()
+            replacement_name = module_type.front_image.name
+            module_type.front_image = original_name
+            module_type.save()
+
+        self.assertTrue(storage.exists(original_name))
+        self.assertFalse(storage.exists(replacement_name))
+
+    @override_settings(STORAGES={
+        **settings.STORAGES,
+        'default': {'BACKEND': 'django.core.files.storage.FileSystemStorage', 'OPTIONS': {'allow_overwrite': True}},
+    })
+    def test_image_shared_between_module_types(self):
+        """
+        An image file stored for two module types should be deleted only once neither references it.
+        """
+        # Overwriting storage (S3 by default) gives two uploads of the same file one stored name
+        module_type = self._create_module_type()
+        other_type = self._create_module_type(model='Module Type 2')
+        front_image_name = module_type.front_image.name
+        rear_image_name = module_type.rear_image.name
+        storage = module_type.front_image.storage
+        self.assertEqual(other_type.front_image.name, front_image_name)
+        self.assertEqual(other_type.rear_image.name, rear_image_name)
+
+        with self.captureOnCommitCallbacks(execute=True):
+            module_type.front_image = ''
+            module_type.save()
+        self.assertTrue(storage.exists(front_image_name))
+
+        with self.captureOnCommitCallbacks(execute=True):
+            other_type.delete()
+        self.assertFalse(storage.exists(front_image_name))
+        self.assertTrue(storage.exists(rear_image_name))
+
+    def test_image_deletion_after_commit(self):
+        """
+        Deleting a module type should delete its stored image files once the deletion commits.
+        """
+        for operation in ('instance', 'deferred', 'unsaved_image', 'queryset'):
+            with self.subTest(operation=operation):
+                module_type = self._create_module_type()
+                images = (module_type.front_image.name, module_type.rear_image.name)
+                storage = module_type.front_image.storage
+                if operation == 'deferred':
+                    module_type = ModuleType.objects.only('pk').get(pk=module_type.pk)
+                elif operation == 'unsaved_image':
+                    module_type.front_image = create_test_image('unsaved.png')
+
+                with self.captureOnCommitCallbacks(execute=True):
+                    if operation == 'queryset':
+                        ModuleType.objects.filter(pk=module_type.pk).delete()
+                    else:
+                        module_type.delete()
+                    for name in images:
+                        self.assertTrue(storage.exists(name))
+
+                for name in images:
+                    self.assertFalse(storage.exists(name))
+
+    def test_image_cleanup_rollback(self):
+        """
+        Replacing an image or deleting a module type in a transaction which is rolled back should keep the file.
+        """
+        for operation in ('replace', 'delete'):
+            with self.subTest(operation=operation):
+                module_type = self._create_module_type(model=operation)
+                pk = module_type.pk
+                original_name = module_type.front_image.name
+                storage = module_type.front_image.storage
+
+                with self.captureOnCommitCallbacks(execute=True), self.assertRaises(RuntimeError):
+                    with transaction.atomic():
+                        if operation == 'replace':
+                            module_type.front_image = create_test_image('replacement.png')
+                            module_type.save()
+                        else:
+                            module_type.delete()
+                        raise RuntimeError('Roll back the transaction')
+
+                self.assertEqual(ModuleType.objects.get(pk=pk).front_image.name, original_name)
+                self.assertTrue(storage.exists(original_name))
+
+
 class RackTypeTestCase(TestCase):
 class RackTypeTestCase(TestCase):
 
 
     @classmethod
     @classmethod
@@ -1438,6 +1603,52 @@ class DeviceTestCase(TestCase):
         self.assertIn('primary_ip4', cm.exception.message_dict)
         self.assertIn('primary_ip4', cm.exception.message_dict)
 
 
 
 
+class DeviceRenderConfigTestCase(TestCase):
+
+    @classmethod
+    def setUpTestData(cls):
+        cls.device = create_test_device('Device 1', local_context_data={'foo': 'context', 'bar': 'context'})
+
+    def test_render_config_without_template(self):
+        self.assertIsNone(self.device.render_config())
+
+    def test_render_config_resolves_template(self):
+        role = self.device.role
+        role.config_template = ConfigTemplate.objects.create(
+            name='Role Template', template_code='Role config for {{ device.name }}'
+        )
+        role.save()
+        self.device.config_template = ConfigTemplate.objects.create(
+            name='Device Template', template_code='Device config for {{ device.name }}'
+        )
+        self.device.save()
+        self.assertEqual(self.device.render_config(), 'Device config for Device 1')
+
+        self.device.config_template = None
+        self.device.save()
+        self.assertEqual(self.device.render_config(), 'Role config for Device 1')
+
+    def test_render_config_with_template_and_extra_context(self):
+        config_template = ConfigTemplate.objects.create(
+            name='Template 1', template_code='{{ device.name }} {{ foo }} {{ bar }} {{ baz }}'
+        )
+        self.assertEqual(
+            self.device.render_config(config_template, extra_context={'bar': 'extra', 'baz': 'extra'}),
+            'Device 1 context extra extra'
+        )
+
+    def test_get_render_context(self):
+        context = self.device.get_render_context({'bar': 'extra', 'device': 'spoofed'})
+        self.assertEqual(context['foo'], 'context')
+        self.assertEqual(context['bar'], 'extra')
+        self.assertEqual(context['device'], self.device)
+
+    def test_render_config_error_propagates(self):
+        config_template = ConfigTemplate.objects.create(name='Template 1', template_code='{{ device.name ')
+        with self.assertRaises(TemplateSyntaxError):
+            self.device.render_config(config_template)
+
+
 class DeviceBayTestCase(TestCase):
 class DeviceBayTestCase(TestCase):
 
 
     @classmethod
     @classmethod

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

@@ -1,6 +1,7 @@
 import csv
 import csv
 import datetime
 import datetime
 import json
 import json
+import tempfile
 from decimal import Decimal
 from decimal import Decimal
 from io import StringIO
 from io import StringIO
 from unittest.mock import patch
 from unittest.mock import patch
@@ -35,7 +36,7 @@ from netbox.choices import (
 from netbox.exporters import get_exporter
 from netbox.exporters import get_exporter
 from tenancy.models import Tenant
 from tenancy.models import Tenant
 from users.models import ObjectPermission, Owner, User
 from users.models import ObjectPermission, Owner, User
-from utilities.testing import ViewTestCases, create_tags, create_test_device, post_data
+from utilities.testing import ViewTestCases, create_tags, create_test_device, create_test_image, post_data
 from wireless.models import WirelessLAN
 from wireless.models import WirelessLAN
 
 
 
 
@@ -1623,6 +1624,58 @@ class ModuleTypeTestCase(ViewTestCases.PrimaryObjectViewTestCase):
             f"{module_types[0].id},test model",
             f"{module_types[0].id},test model",
         )
         )
 
 
+    def test_module_type_detail_includes_images(self):
+        """
+        The module type view should show the front and rear images.
+        """
+        self.add_permissions('dcim.view_moduletype')
+        module_type = self._get_queryset().first()
+        module_type.front_image = 'moduletype-images/front.png'
+        module_type.rear_image = 'moduletype-images/rear.png'
+        module_type.save()
+
+        response = self.client.get(module_type.get_absolute_url())
+
+        self.assertContains(response, f'src="{module_type.front_image.url}"')
+        self.assertContains(response, f'src="{module_type.rear_image.url}"')
+
+    def test_bulk_delete_rollback_keeps_images(self):
+        """
+        A bulk delete which fails on an in-use module type should keep the image files of the others.
+        """
+        self.add_permissions('dcim.delete_moduletype')
+        manufacturer = Manufacturer.objects.get(slug='manufacturer-1')
+
+        with tempfile.TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root):
+            module_type = ModuleType.objects.create(
+                manufacturer=manufacturer,
+                model='Module Type A',
+                front_image=create_test_image('front.png'),
+                rear_image=create_test_image('rear.png'),
+            )
+            in_use_type = ModuleType.objects.create(manufacturer=manufacturer, model='Module Type B')
+            device = create_test_device('Device 1')
+            module_bay = ModuleBay.objects.create(device=device, name='Module Bay 1')
+            Module.objects.create(device=device, module_bay=module_bay, module_type=in_use_type)
+            images = (module_type.front_image.name, module_type.rear_image.name)
+            storage = module_type.front_image.storage
+
+            # The view deletes in the default ordering, so the type with images goes before the in-use type
+            pk_list = [module_type.pk, in_use_type.pk]
+            self.assertEqual(list(ModuleType.objects.filter(pk__in=pk_list).values_list('pk', flat=True)), pk_list)
+            data = {
+                'pk': pk_list,
+                'confirm': True,
+                '_confirm': True,  # Form button
+            }
+            with self.captureOnCommitCallbacks(execute=True):
+                response = self.client.post(self._get_url('bulk_delete'), data)
+
+            self.assertHttpStatus(response, 302)
+            self.assertTrue(ModuleType.objects.filter(pk=module_type.pk).exists())
+            for name in images:
+                self.assertTrue(storage.exists(name))
+
     def test_bulk_update_objects_with_permission(self):
     def test_bulk_update_objects_with_permission(self):
         self.add_permissions(
         self.add_permissions(
             'dcim.add_consoleporttemplate',
             'dcim.add_consoleporttemplate',
@@ -3295,6 +3348,24 @@ class DeviceTestCase(ViewTestCases.PrimaryObjectViewTestCase):
         self.remove_permissions('dcim.view_device')
         self.remove_permissions('dcim.view_device')
         self.assertHttpStatus(self.client.get(url), 403)
         self.assertHttpStatus(self.client.get(url), 403)
 
 
+    def test_device_renderconfig_matches_model(self):
+        """
+        The rendered config exported from the UI matches the output of Device.render_config().
+        """
+        device = Device.objects.first()
+        device.config_template = ConfigTemplate.objects.create(
+            name='Test Config Template',
+            template_code='hostname {{ device.name }}\nntp server {{ ntp_server }}\n'
+        )
+        device.local_context_data = {'ntp_server': '192.0.2.1'}
+        device.save()
+
+        self.add_permissions('dcim.view_device', 'dcim.render_config_device')
+        url = reverse('dcim:device_render-config', kwargs={'pk': device.pk})
+        response = self.client.get(url, {'export': 1})
+        self.assertHttpStatus(response, 200)
+        self.assertEqual(response.content.decode(), Device.objects.get(pk=device.pk).render_config())
+
     def test_device_renderconfig_with_config_template_id(self):
     def test_device_renderconfig_with_config_template_id(self):
         default_template = ConfigTemplate.objects.create(
         default_template = ConfigTemplate.objects.create(
             name='Default Template',
             name='Default Template',
@@ -3599,6 +3670,22 @@ class ModuleTestCase(
 
 
         self.assertContains(response, 'Module Type Profile 1')
         self.assertContains(response, 'Module Type Profile 1')
 
 
+    def test_module_detail_includes_module_type_images(self):
+        """
+        The module view should show the front and rear images of its module type.
+        """
+        self.add_permissions('dcim.view_module')
+        module = self._get_queryset().first()
+        module_type = module.module_type
+        module_type.front_image = 'moduletype-images/front.png'
+        module_type.rear_image = 'moduletype-images/rear.png'
+        module_type.save()
+
+        response = self.client.get(module.get_absolute_url())
+
+        self.assertContains(response, f'src="{module_type.front_image.url}"')
+        self.assertContains(response, f'src="{module_type.rear_image.url}"')
+
     @tag('regression')
     @tag('regression')
     def test_module_detail_renders_module_type_attribute_lists(self):
     def test_module_detail_renders_module_type_attribute_lists(self):
         self.add_permissions(
         self.add_permissions(

+ 29 - 5
netbox/dcim/ui/panels.py

@@ -37,9 +37,20 @@ class SitePanel(panels.ObjectAttributesPanel):
     facility = attrs.TextAttr('facility')
     facility = attrs.TextAttr('facility')
     description = attrs.TextAttr('description')
     description = attrs.TextAttr('description')
     timezone = attrs.TimezoneAttr('time_zone')
     timezone = attrs.TimezoneAttr('time_zone')
+
+
+class SiteLocationPanel(panels.ObjectAttributesPanel):
+    title = _('Location')
+
     physical_address = attrs.AddressAttr('physical_address', map_url=True, copy_button=True)
     physical_address = attrs.AddressAttr('physical_address', map_url=True, copy_button=True)
     shipping_address = attrs.AddressAttr('shipping_address', map_url=True, copy_button=True)
     shipping_address = attrs.AddressAttr('shipping_address', map_url=True, copy_button=True)
     gps_coordinates = attrs.GPSCoordinatesAttr()
     gps_coordinates = attrs.GPSCoordinatesAttr()
+    mercator_x = attrs.NumericAttr(
+        'mercator_x', label=_('Web Mercator X (EPSG:3857, meters)'), copy_button=True, localize=False
+    )
+    mercator_y = attrs.NumericAttr(
+        'mercator_y', label=_('Web Mercator Y (EPSG:3857, meters)'), copy_button=True, localize=False
+    )
 
 
 
 
 class LocationPanel(panels.NestedGroupObjectPanel):
 class LocationPanel(panels.NestedGroupObjectPanel):
@@ -113,13 +124,8 @@ class RackTypePanel(panels.ObjectAttributesPanel):
 
 
 
 
 class DevicePanel(panels.ObjectAttributesPanel):
 class DevicePanel(panels.ObjectAttributesPanel):
-    region = attrs.NestedObjectAttr('site.region', linkify=True)
-    site = attrs.RelatedObjectAttr('site', linkify=True, grouped_by='group')
-    location = attrs.NestedObjectAttr('location', linkify=True)
-    rack = attrs.TemplatedAttr('rack', template_name='dcim/device/attrs/rack.html')
     virtual_chassis = attrs.RelatedObjectAttr('virtual_chassis', linkify=True)
     virtual_chassis = attrs.RelatedObjectAttr('virtual_chassis', linkify=True)
     parent_device = attrs.TemplatedAttr('parent_bay', template_name='dcim/device/attrs/parent_device.html')
     parent_device = attrs.TemplatedAttr('parent_bay', template_name='dcim/device/attrs/parent_device.html')
-    gps_coordinates = attrs.GPSCoordinatesAttr()
     tenant = attrs.RelatedObjectAttr('tenant', linkify=True, grouped_by='group')
     tenant = attrs.RelatedObjectAttr('tenant', linkify=True, grouped_by='group')
     description = attrs.TextAttr('description')
     description = attrs.TextAttr('description')
     cooling_method = attrs.ChoiceAttr('cooling_method')
     cooling_method = attrs.ChoiceAttr('cooling_method')
@@ -129,6 +135,22 @@ class DevicePanel(panels.ObjectAttributesPanel):
     config_template = attrs.RelatedObjectAttr('config_template', linkify=True)
     config_template = attrs.RelatedObjectAttr('config_template', linkify=True)
 
 
 
 
+class DeviceLocationPanel(panels.ObjectAttributesPanel):
+    title = _('Location')
+
+    region = attrs.NestedObjectAttr('site.region', linkify=True)
+    site = attrs.RelatedObjectAttr('site', linkify=True, grouped_by='group')
+    location = attrs.NestedObjectAttr('location', linkify=True)
+    rack = attrs.TemplatedAttr('rack', template_name='dcim/device/attrs/rack.html')
+    gps_coordinates = attrs.GPSCoordinatesAttr()
+    mercator_x = attrs.NumericAttr(
+        'mercator_x', label=_('Web Mercator X (EPSG:3857, meters)'), copy_button=True, localize=False
+    )
+    mercator_y = attrs.NumericAttr(
+        'mercator_y', label=_('Web Mercator Y (EPSG:3857, meters)'), copy_button=True, localize=False
+    )
+
+
 class DeviceManagementPanel(panels.ObjectAttributesPanel):
 class DeviceManagementPanel(panels.ObjectAttributesPanel):
     title = _('Management')
     title = _('Management')
 
 
@@ -228,6 +250,8 @@ class ModuleTypePanel(panels.ObjectAttributesPanel):
     module_bay_types = attrs.RelatedObjectListAttr(
     module_bay_types = attrs.RelatedObjectListAttr(
         'module_bay_types', label=_('Bay Type Compatibility'), linkify=True
         'module_bay_types', label=_('Bay Type Compatibility'), linkify=True
     )
     )
+    front_image = attrs.ImageAttr('front_image')
+    rear_image = attrs.ImageAttr('rear_image')
 
 
 
 
 class PlatformPanel(panels.NestedGroupObjectPanel):
 class PlatformPanel(panels.NestedGroupObjectPanel):

+ 2 - 0
netbox/dcim/views.py

@@ -550,6 +550,7 @@ class SiteView(GetRelatedModelsMixin, generic.ObjectView):
     layout = layout.SimpleLayout(
     layout = layout.SimpleLayout(
         left_panels=[
         left_panels=[
             panels.SitePanel(),
             panels.SitePanel(),
+            panels.SiteLocationPanel(),
             CustomFieldsPanel(),
             CustomFieldsPanel(),
             TagsPanel(),
             TagsPanel(),
             CommentsPanel(),
             CommentsPanel(),
@@ -2964,6 +2965,7 @@ class DeviceView(generic.ObjectView):
     layout = layout.SimpleLayout(
     layout = layout.SimpleLayout(
         left_panels=[
         left_panels=[
             panels.DevicePanel(),
             panels.DevicePanel(),
+            panels.DeviceLocationPanel(),
             panels.VirtualChassisMembersPanel(),
             panels.VirtualChassisMembersPanel(),
             CustomFieldsPanel(),
             CustomFieldsPanel(),
             TagsPanel(),
             TagsPanel(),

+ 1 - 3
netbox/extras/api/mixins.py

@@ -141,8 +141,6 @@ class RenderConfigMixin(ConfigTemplateRenderMixin):
                 }, status=HTTP_400_BAD_REQUEST)
                 }, status=HTTP_400_BAD_REQUEST)
 
 
         # Compile context data
         # Compile context data
-        context_data = instance.get_config_context()
-        context_data.update({k: v for k, v in request.data.items() if k != 'config_template_id'})
-        context_data.update({object_type: instance})
+        context_data = instance.get_render_context({k: v for k, v in request.data.items() if k != 'config_template_id'})
 
 
         return self.render_configtemplate(request, configtemplate, context_data)
         return self.render_configtemplate(request, configtemplate, context_data)

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

@@ -368,8 +368,8 @@ class ConfigContextModel(models.Model):
         (`_config_context_data`), return a copy of it unless copy_data is False. Otherwise, fall
         (`_config_context_data`), return a copy of it unless copy_data is False. Otherwise, fall
         back to rendering on demand.
         back to rendering on demand.
 
 
-        By default, the returned dict is safe for callers to mutate (e.g. ObjectRenderConfigView merges
-        in additional context with .update()): the cached blob is deep-copied so mutations cannot
+        By default, the returned dict is safe for callers to mutate (e.g. RenderConfigMixin.get_render_context()
+        merges in additional context): the cached blob is deep-copied so mutations cannot
         leak back into this instance's in-memory cache, matching the fresh-dict guarantee of the
         leak back into this instance's in-memory cache, matching the fresh-dict guarantee of the
         on-demand render path. Read-only callers may pass copy_data=False to skip the copy. The
         on-demand render path. Read-only callers may pass copy_data=False to skip the copy. The
         cached blob is then returned as is and must not be modified.
         cached blob is then returned as is and must not be modified.

+ 13 - 0
netbox/extras/models/mixins.py

@@ -3,6 +3,7 @@ import importlib.util
 import logging
 import logging
 import os
 import os
 import sys
 import sys
+import warnings
 from collections import defaultdict
 from collections import defaultdict
 
 
 from django.core.exceptions import ValidationError
 from django.core.exceptions import ValidationError
@@ -26,6 +27,9 @@ __all__ = (
 
 
 logger = logging.getLogger(__name__)
 logger = logging.getLogger(__name__)
 
 
+# (model name, pk) of templates that have already emitted the stored 'finalize' deprecation warning (#23498)
+_stored_finalize_warned = set()
+
 
 
 class CustomStoragesLoader(importlib.abc.Loader):
 class CustomStoragesLoader(importlib.abc.Loader):
     """
     """
@@ -253,6 +257,15 @@ class RenderTemplateMixin(models.Model):
                 type(self).__name__, self.pk,
                 type(self).__name__, self.pk,
             )
             )
             return {key: value for key, value in params.items() if key != 'finalize'}
             return {key: value for key, value in params.items() if key != 'finalize'}
+        # Track warned templates here: the warnings registry resets whenever any code changes the warning filters.
+        warned_key = (type(self).__name__, self.pk)
+        if warned_key not in _stored_finalize_warned:
+            _stored_finalize_warned.add(warned_key)
+            warnings.warn(
+                f'The "finalize" environment parameter stored on {type(self).__name__} (pk={self.pk}) is deprecated '
+                'and will be removed in NetBox v5.0. Move its logic into the template code.',
+                FutureWarning,
+            )
         return {**params, 'finalize': stored_finalize}
         return {**params, 'finalize': stored_finalize}
 
 
     def get_environment_params(self):
     def get_environment_params(self):

+ 104 - 0
netbox/extras/tests/test_models.py

@@ -2,6 +2,7 @@ import io
 import os
 import os
 import sys
 import sys
 import tempfile
 import tempfile
+import warnings
 from pathlib import Path
 from pathlib import Path
 from types import SimpleNamespace
 from types import SimpleNamespace
 from unittest.mock import patch
 from unittest.mock import patch
@@ -1709,6 +1710,109 @@ class ExportTemplateStoredOnlyFinalizeTestCase(TestCase):
             t.get_environment_params()
             t.get_environment_params()
 
 
 
 
+class StoredFinalizeDeprecationWarningTestCase(TestCase):
+    """
+    A stored 'finalize' stays honored until v5.0, so operators get a once-per-template FutureWarning and unchanged
+    output (#23498).
+    """
+    TEMPLATE_CODE = '{{ "netbox" }}'
+    SHARED_PK = 9001
+
+    def setUp(self):
+        # Start each test with no templates marked as already warned
+        self.enterContext(patch('extras.models.mixins._stored_finalize_warned', set()))
+
+    def _create(self, model, name, **kwargs):
+        # create() does not call clean(). This matches a value stored before clean() blocked it.
+        return model.objects.create(name=name, template_code=self.TEMPLATE_CODE, **kwargs)
+
+    def _create_stored(self, model, name='stored'):
+        return self._create(model, name, environment_params={'finalize': 'builtins.len'})
+
+    def _render_recording(self, *templates):
+        """
+        Use the 'always' filter so any dedupe comes from the template mixin, not from the warnings registry.
+        """
+        with warnings.catch_warnings(record=True) as caught:
+            warnings.simplefilter('always')
+            for template in templates:
+                template.render()
+        return [w for w in caught if issubclass(w.category, FutureWarning)]
+
+    def test_render_output_unchanged_with_stored_finalize(self):
+        for model in (ExportTemplate, ConfigTemplate):
+            with self.subTest(model=model.__name__):
+                self._create_stored(model)
+                t = model.objects.get(name='stored')
+                with warnings.catch_warnings():
+                    warnings.simplefilter('ignore')
+                    self.assertEqual(t.render(), '6')
+
+    def test_warning_names_model_pk_and_removal_version(self):
+        for model in (ExportTemplate, ConfigTemplate):
+            with self.subTest(model=model.__name__):
+                t = self._create_stored(model, name=f'stored-{model.__name__}')
+                with self.assertNoLogs('extras.models.mixins', 'WARNING'):
+                    caught = self._render_recording(t)
+                self.assertEqual(len(caught), 1)
+                self.assertIs(caught[0].category, FutureWarning)
+                message = str(caught[0].message)
+                self.assertIn(model.__name__, message)
+                self.assertIn(f'pk={t.pk}', message)
+                self.assertIn('v5.0', message)
+                # Must read differently from the "Ignoring the deprecated..." log for in-memory values
+                self.assertNotIn('Ignoring', message)
+
+    def test_warns_once_per_template_per_process(self):
+        first = self._create_stored(ExportTemplate, name='first')
+        second = self._create_stored(ExportTemplate, name='second')
+        caught = self._render_recording(first, first, second, first, second)
+        self.assertEqual(len(caught), 2)
+        self.assertIn(f'pk={first.pk}', str(caught[0].message))
+        self.assertIn(f'pk={second.pk}', str(caught[1].message))
+
+    def test_warns_once_when_warning_filters_change_between_renders(self):
+        """
+        Changing the warning filters (catch_warnings(), filterwarnings(), urllib3.disable_warnings()) clears the
+        warnings registry. The once-per-template dedupe must not depend on it.
+        """
+        t = self._create_stored(ExportTemplate)
+        caught = []
+        for _ in range(3):
+            caught += self._render_recording(t)
+        self.assertEqual(len(caught), 1)
+
+    def test_warns_separately_for_models_sharing_a_pk(self):
+        params = {'finalize': 'builtins.len'}
+        export_template = self._create(ExportTemplate, 'export', pk=self.SHARED_PK, environment_params=params)
+        config_template = self._create(ConfigTemplate, 'config', pk=self.SHARED_PK, environment_params=params)
+        caught = self._render_recording(export_template, config_template)
+        self.assertEqual(len(caught), 2)
+
+    def test_no_warning_without_finalize(self):
+        for model in (ExportTemplate, ConfigTemplate):
+            with self.subTest(model=model.__name__):
+                t = self._create(model, f'plain-{model.__name__}', environment_params={'trim_blocks': True})
+                self.assertEqual(self._render_recording(t), [])
+
+    def test_no_warning_when_finalize_exists_only_in_memory(self):
+        t = self._create(ExportTemplate, 'saved')
+        t.environment_params = {'finalize': 'builtins.len'}
+        with self.assertLogs('extras.models.mixins', 'WARNING'):
+            caught = self._render_recording(t)
+        self.assertEqual(caught, [])
+
+    def test_no_warning_for_unsaved_template(self):
+        t = ExportTemplate(
+            name='unsaved',
+            template_code=self.TEMPLATE_CODE,
+            environment_params={'finalize': 'builtins.len'},
+        )
+        with self.assertLogs('extras.models.mixins', 'WARNING'):
+            caught = self._render_recording(t)
+        self.assertEqual(caught, [])
+
+
 class WebhookPayloadUrlValidationTestCase(TestCase):
 class WebhookPayloadUrlValidationTestCase(TestCase):
     """Tests for Webhook.clean()'s validation of payload_url (#22828)."""
     """Tests for Webhook.clean()'s validation of payload_url (#22828)."""
 
 

+ 5 - 5
netbox/extras/views.py

@@ -1298,14 +1298,14 @@ class ObjectRenderConfigView(generic.ObjectView):
         )
         )
 
 
     def get_extra_context_data(self, request, instance):
     def get_extra_context_data(self, request, instance):
-        return {
-            f'{instance._meta.model_name}': instance,
-        }
+        """
+        Return additional context for rendering the config template. The object itself is always included.
+        """
+        return {}
 
 
     def get_extra_context(self, request, instance):
     def get_extra_context(self, request, instance):
         # Compile context data
         # Compile context data
-        context_data = instance.get_config_context()
-        context_data.update(self.get_extra_context_data(request, instance))
+        context_data = instance.get_render_context(self.get_extra_context_data(request, instance))
 
 
         # Check for an optional config_template_id override in the query params
         # Check for an optional config_template_id override in the query params
         config_template = None
         config_template = None

+ 1 - 1
netbox/ipam/tests/test_views.py

@@ -724,7 +724,7 @@ class PrefixTestCase(ViewTestCases.PrimaryObjectViewTestCase):
         data = {
         data = {
             'pk': [prefix.pk],
             'pk': [prefix.pk],
             'scope_content_type': ContentType.objects.get_for_model(Site).pk,
             'scope_content_type': ContentType.objects.get_for_model(Site).pk,
-            # The client-side hx-on::config-request clears the paired object id on a type change.
+            # The client-side data-htmx-clear-param listener clears the paired object id on a type change.
             'scope_object_id': '',
             'scope_object_id': '',
         }
         }
         response = self.client.post(self._get_url('bulk_edit'), data, headers={'HX-Request': 'true'})
         response = self.client.post(self._get_url('bulk_edit'), data, headers={'HX-Request': 'true'})

+ 3 - 1
netbox/netbox/forms/search.py

@@ -22,7 +22,9 @@ class SearchForm(forms.Form):
             attrs={
             attrs={
                 'hx-get': '',
                 'hx-get': '',
                 'hx-target': '#object_list',
                 'hx-target': '#object_list',
-                'hx-trigger': 'keyup[target.value.length >= 3] changed delay:500ms',
+                # netbox:search-input is dispatched by htmx.ts once the value reaches data-search-min-length
+                'hx-trigger': 'netbox:search-input changed delay:500ms',
+                'data-search-min-length': '3',
             }
             }
         )
         )
     )
     )

+ 34 - 0
netbox/netbox/middleware.py

@@ -28,6 +28,7 @@ __all__ = (
     'CoreMiddleware',
     'CoreMiddleware',
     'LoginRequiredMiddleware',
     'LoginRequiredMiddleware',
     'MaintenanceModeMiddleware',
     'MaintenanceModeMiddleware',
+    'PermissionsPolicyMiddleware',
     'PrometheusAfterMiddleware',
     'PrometheusAfterMiddleware',
     'PrometheusBeforeMiddleware',
     'PrometheusBeforeMiddleware',
     'RemoteUserMiddleware',
     'RemoteUserMiddleware',
@@ -52,6 +53,39 @@ class CommonMiddleware(DjangoCommonMiddleware):
         return super().should_redirect_with_slash(request)
         return super().should_redirect_with_slash(request)
 
 
 
 
+class PermissionsPolicyMiddleware:
+    """
+    Send a Permissions-Policy header built from the PERMISSIONS_POLICY setting on HTML responses only, since only a
+    browser rendering a document uses it. 3XX responses get none, as the browser never renders their body. Each feature
+    maps to a list of allowed origins, where an empty list denies the feature. An empty setting sends no header, and
+    a header already set by a view is left alone. The header is built once, when the middleware is instantiated.
+    """
+    def __init__(self, get_response):
+        self.get_response = get_response
+        self.header = self.build_header(settings.PERMISSIONS_POLICY) if settings.PERMISSIONS_POLICY else None
+
+    def __call__(self, request):
+        response = self.get_response(request)
+        if (
+            self.header is not None
+            and 'Permissions-Policy' not in response
+            and not 300 <= response.status_code < 400
+            and response.get('Content-Type', '').lower().startswith('text/html')
+        ):
+            response['Permissions-Policy'] = self.header
+        return response
+
+    @staticmethod
+    def build_header(policy):
+        directives = []
+        for feature, origins in policy.items():
+            # "self" and "*" are structured-field tokens. Anything else is an origin, sent as a quoted string.
+            items = ' '.join(origin if origin in ('self', '*') else f'"{origin}"' for origin in origins)
+            # A lone wildcard is sent as a bare token, which the spec treats the same as "(*)".
+            directives.append(f'{feature}=*' if list(origins) == ['*'] else f'{feature}=({items})')
+        return ', '.join(directives)
+
+
 class CoreMiddleware:
 class CoreMiddleware:
 
 
     def __init__(self, get_response):
     def __init__(self, get_response):

+ 16 - 0
netbox/netbox/settings.py

@@ -26,6 +26,7 @@ from netbox.settings_utils import (
     parse_job_timeout,
     parse_job_timeout,
     resolve_install_paths,
     resolve_install_paths,
     secret_key_hint,
     secret_key_hint,
+    validate_permissions_policy,
     validate_webhook_default_timeout,
     validate_webhook_default_timeout,
 )
 )
 from utilities.release import load_release_data
 from utilities.release import load_release_data
@@ -167,6 +168,16 @@ LOGIN_FORM_HIDDEN = param('LOGIN_FORM_HIDDEN', False, types=bool)
 LOGOUT_REDIRECT_URL = param('LOGOUT_REDIRECT_URL', 'home', types=str)
 LOGOUT_REDIRECT_URL = param('LOGOUT_REDIRECT_URL', 'home', types=str)
 MEDIA_ROOT = param('MEDIA_ROOT', os.path.join(NETBOX_ROOT, 'media'), types=str).rstrip('/')
 MEDIA_ROOT = param('MEDIA_ROOT', os.path.join(NETBOX_ROOT, 'media'), types=str).rstrip('/')
 METRICS_ENABLED = param('METRICS_ENABLED', False, types=bool)
 METRICS_ENABLED = param('METRICS_ENABLED', False, types=bool)
+PERMISSIONS_POLICY = param('PERMISSIONS_POLICY', {
+    'camera': [],
+    'microphone': [],
+    'geolocation': [],
+    'payment': [],
+    'usb': [],
+    'hid': [],
+    'serial': [],
+    'bluetooth': [],
+}, types=dict, validators=[validate_permissions_policy])
 PLUGINS = param('PLUGINS', [], types=(list, tuple))
 PLUGINS = param('PLUGINS', [], types=(list, tuple))
 PLUGINS_CONFIG = param('PLUGINS_CONFIG', {}, types=dict)
 PLUGINS_CONFIG = param('PLUGINS_CONFIG', {}, types=dict)
 PLUGINS_CATALOG_CONFIG = param('PLUGINS_CATALOG_CONFIG', {}, types=dict)
 PLUGINS_CATALOG_CONFIG = param('PLUGINS_CATALOG_CONFIG', {}, types=dict)
@@ -205,6 +216,8 @@ RQ_RETRY_MAX = param('RQ_RETRY_MAX', 0, types=int, min_value=0)
 SCRIPTS_ROOT = param('SCRIPTS_ROOT', os.path.join(NETBOX_ROOT, 'scripts'), types=str).rstrip('/')
 SCRIPTS_ROOT = param('SCRIPTS_ROOT', os.path.join(NETBOX_ROOT, 'scripts'), types=str).rstrip('/')
 SEARCH_BACKEND = param('SEARCH_BACKEND', 'netbox.search.backends.CachedValueSearchBackend', types=str)
 SEARCH_BACKEND = param('SEARCH_BACKEND', 'netbox.search.backends.CachedValueSearchBackend', types=str)
 SECRET_KEY = param('SECRET_KEY', types=str)  # Required
 SECRET_KEY = param('SECRET_KEY', types=str)  # Required
+SECURE_CSP = param('SECURE_CSP', {}, types=dict)
+SECURE_CSP_REPORT_ONLY = param('SECURE_CSP_REPORT_ONLY', {}, types=dict)
 SECURE_HSTS_INCLUDE_SUBDOMAINS = param('SECURE_HSTS_INCLUDE_SUBDOMAINS', False, types=bool)
 SECURE_HSTS_INCLUDE_SUBDOMAINS = param('SECURE_HSTS_INCLUDE_SUBDOMAINS', False, types=bool)
 SECURE_HSTS_PRELOAD = param('SECURE_HSTS_PRELOAD', False, types=bool)
 SECURE_HSTS_PRELOAD = param('SECURE_HSTS_PRELOAD', False, types=bool)
 SECURE_HSTS_SECONDS = param('SECURE_HSTS_SECONDS', 0, types=int, min_value=0)
 SECURE_HSTS_SECONDS = param('SECURE_HSTS_SECONDS', 0, types=int, min_value=0)
@@ -529,6 +542,8 @@ MIDDLEWARE = [
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware',
     'django.middleware.security.SecurityMiddleware',
     'django.middleware.security.SecurityMiddleware',
+    'django.middleware.csp.ContentSecurityPolicyMiddleware',
+    'netbox.middleware.PermissionsPolicyMiddleware',
     'django_htmx.middleware.HtmxMiddleware',
     'django_htmx.middleware.HtmxMiddleware',
     'netbox.middleware.RemoteUserMiddleware',
     'netbox.middleware.RemoteUserMiddleware',
     'netbox.middleware.LoginRequiredMiddleware',
     'netbox.middleware.LoginRequiredMiddleware',
@@ -570,6 +585,7 @@ TEMPLATES = [
                 'django.template.context_processors.debug',
                 'django.template.context_processors.debug',
                 'django.template.context_processors.request',
                 'django.template.context_processors.request',
                 'django.template.context_processors.media',
                 'django.template.context_processors.media',
+                'django.template.context_processors.csp',
                 'django.contrib.auth.context_processors.auth',
                 'django.contrib.auth.context_processors.auth',
                 'django.contrib.messages.context_processors.messages',
                 'django.contrib.messages.context_processors.messages',
                 'netbox.context_processors.settings',
                 'netbox.context_processors.settings',

+ 64 - 0
netbox/netbox/settings_utils.py

@@ -3,10 +3,12 @@
 import importlib
 import importlib
 import importlib.util
 import importlib.util
 import os
 import os
+import re
 import sys
 import sys
 import threading
 import threading
 import warnings
 import warnings
 from typing import NamedTuple
 from typing import NamedTuple
+from urllib.parse import urlsplit
 
 
 from django.core.exceptions import ImproperlyConfigured
 from django.core.exceptions import ImproperlyConfigured
 from rq.exceptions import TimeoutFormatError
 from rq.exceptions import TimeoutFormatError
@@ -22,6 +24,7 @@ __all__ = (
     'parse_job_timeout',
     'parse_job_timeout',
     'resolve_install_paths',
     'resolve_install_paths',
     'secret_key_hint',
     'secret_key_hint',
+    'validate_permissions_policy',
     'validate_webhook_default_timeout',
     'validate_webhook_default_timeout',
 )
 )
 
 
@@ -121,6 +124,67 @@ def validate_webhook_default_timeout(timeout, job_timeout):
         )
         )
 
 
 
 
+_LABEL = r'[A-Za-z0-9_]([A-Za-z0-9_-]*[A-Za-z0-9_])?'
+ORIGIN_NETLOC_RE = re.compile(rf'(\*\.)?{_LABEL}(\.{_LABEL})*(:[0-9]+)?|\[[0-9A-Fa-f:.]+\](:[0-9]+)?')
+
+
+FEATURE_NAME_RE = re.compile(r'[a-z][a-z0-9-]*')
+
+
+def validate_permissions_policy(name, value):
+    """Validate PERMISSIONS_POLICY.
+
+    Feature names are checked for header-safe characters only, not against a list of known features.
+
+    Each value must be a list or tuple whose entries are 'self', '*', or a bare http(s) origin.
+    Anything else would be emitted into the header verbatim and silently discarded by browsers.
+    """
+    for feature, entries in value.items():
+        if not isinstance(feature, str) or FEATURE_NAME_RE.fullmatch(feature) is None:
+            raise ImproperlyConfigured(
+                f"{name} contains the invalid feature name {feature!r}: names start with a lowercase letter, then "
+                "lowercase letters, digits and hyphens"
+            )
+        if not isinstance(entries, (list, tuple)):
+            raise ImproperlyConfigured(
+                f"{name}[{feature!r}] must be a list or tuple of allowed origins (found {entries!r})"
+            )
+        for entry in entries:
+            if entry in ('self', '*'):
+                continue
+            if entry in ("'self'", "'none'"):
+                raise ImproperlyConfigured(
+                    f"{name}[{feature!r}] contains the CSP keyword {entry!r}: use 'self' without the CSP quotes "
+                    f"(CSP.SELF is not accepted), or an empty list to deny the feature"
+                )
+            if not _is_origin(entry):
+                raise ImproperlyConfigured(
+                    f"{name}[{feature!r}] contains {entry!r}, which is not 'self', '*', or an origin such as "
+                    f"'https://scan.example.com'"
+                )
+
+
+def _is_origin(entry):
+    """
+    Return True if entry is exactly a lowercase http(s) scheme, an ASCII host and an optional valid port.
+
+    The host charset is strict because the entry is written into a structured-field header, where one
+    bad character makes the browser drop the whole policy.
+    """
+    if not isinstance(entry, str):
+        return False
+    try:
+        parts = urlsplit(entry)
+        parts.port  # Raises ValueError if the port is not a number from 0 to 65535
+    except ValueError:
+        return False
+    return (
+        parts.scheme in ('http', 'https')
+        and entry == f'{parts.scheme}://{parts.netloc}'
+        and ORIGIN_NETLOC_RE.fullmatch(parts.netloc) is not None
+    )
+
+
 def _import_module(name):
 def _import_module(name):
     """Import a configuration module by dotted path.
     """Import a configuration module by dotted path.
 
 

+ 170 - 0
netbox/netbox/tests/test_csp.py

@@ -0,0 +1,170 @@
+import re
+from html.parser import HTMLParser
+from urllib.parse import urlsplit
+
+from django.conf import settings
+from django.contrib.staticfiles import finders
+from django.test import Client, override_settings
+from django.urls import reverse
+from django.utils.csp import CSP
+from drf_spectacular.settings import patched_settings
+
+from dcim.models import Site
+from utilities.testing import TestCase
+
+CSP_POLICY = {
+    'script-src': [CSP.SELF, CSP.NONCE],
+}
+
+
+class ScriptCollector(HTMLParser):
+    """
+    Record the attributes of every <script> element, and every inline event handler attribute (e.g. onerror) on any
+    element.
+    """
+    def __init__(self):
+        super().__init__()
+        self.scripts = []
+        self.handlers = []
+
+    def handle_starttag(self, tag, attrs):
+        attrs = dict(attrs)
+        if tag == 'script':
+            self.scripts.append(attrs)
+        for name in attrs:
+            # Inline event handler attributes are the only standard attributes starting with "on"
+            if name.startswith('on'):
+                self.handlers.append(f'<{tag} {name}="{attrs[name]}">')
+
+
+class HxTriggerCollector(HTMLParser):
+    """
+    Record the attributes of every <input> element that has an hx-trigger attribute.
+    """
+    def __init__(self):
+        super().__init__()
+        self.inputs = []
+
+    def handle_starttag(self, tag, attrs):
+        attrs = dict(attrs)
+        if tag == 'input' and 'hx-trigger' in attrs:
+            self.inputs.append(attrs)
+
+
+@override_settings(SECURE_CSP=CSP_POLICY, DEBUG=False)
+class ScriptNonceTestCase(TestCase):
+    """
+    Every <script> NetBox renders carries the request's CSP nonce, and no page uses inline event handler attributes
+    (which a nonce cannot cover). Together these let NetBox run under a policy without 'unsafe-inline'.
+    """
+
+    @classmethod
+    def setUpTestData(cls):
+        cls.site = Site.objects.create(name='Site 1', slug='site-1')
+
+    def setUp(self):
+        super().setUp()
+
+        self.user.is_superuser = True
+        self.user.save()
+
+    @staticmethod
+    def collect(response):
+        parser = ScriptCollector()
+        parser.feed(response.content.decode())
+        return parser
+
+    def assertScriptsNonced(self, response):
+        self.assertHttpStatus(response, 200)
+        match = re.search(r"'nonce-([^']+)'", response['Content-Security-Policy'])
+        self.assertIsNotNone(match, f"No nonce in header: {response['Content-Security-Policy']}")
+        nonce = match.group(1)
+
+        parser = self.collect(response)
+        self.assertTrue(parser.scripts, 'No <script> elements found')
+        for script in parser.scripts:
+            self.assertEqual(script.get('nonce'), nonce, f'<script> without the request nonce: {script}')
+        self.assertEqual(parser.handlers, [], 'Inline event handler attributes found')
+
+    def test_login(self):
+        self.assertScriptsNonced(Client().get(reverse('login')))
+
+    def test_object_list(self):
+        self.assertScriptsNonced(self.client.get(reverse('dcim:site_list')))
+
+    def test_object_detail(self):
+        self.assertScriptsNonced(self.client.get(self.site.get_absolute_url()))
+
+    def test_user_token_edit(self):
+        self.assertScriptsNonced(self.client.get(reverse('account:usertoken_add')))
+
+    def test_token_edit(self):
+        self.assertScriptsNonced(self.client.get(reverse('users:token_add')))
+
+    def test_copilot_script(self):
+        # Copilot is enabled globally by default. Each user opts in with a preference.
+        self.user.config.set('ui.copilot_enabled', 'true', commit=True)
+
+        response = self.client.get(reverse('dcim:site_list'))
+        self.assertScriptsNonced(response)
+        self.assertIn(settings.NETBOX_COPILOT_URL, [script.get('src') for script in self.collect(response).scripts])
+
+    def test_graphiql(self):
+        self.assertScriptsNonced(self.client.get(reverse('graphql'), HTTP_ACCEPT='text/html'))
+
+    def test_swagger_ui(self):
+        self.assertScriptsNonced(self.client.get(reverse('api_docs')))
+
+    def test_redoc(self):
+        self.assertScriptsNonced(self.client.get(reverse('api_redocs')))
+
+    def test_redoc_with_settings(self):
+        # With REDOC_UI_SETTINGS set, Redoc renders an inline Redoc.init script. drf-spectacular reads its settings
+        # once at import and has no setting_changed hook, so override_settings(SPECTACULAR_SETTINGS=...) has no
+        # effect. patched_settings is its own supported way to override them temporarily.
+        with patched_settings({'REDOC_UI_SETTINGS': {'hideDownloadButton': True}}):
+            response = self.client.get(reverse('api_redocs'))
+        self.assertScriptsNonced(response)
+        inline = [script for script in self.collect(response).scripts if 'src' not in script]
+        self.assertEqual(len(inline), 1)
+        self.assertIn('Redoc.init', response.content.decode())
+
+    def test_browsable_api(self):
+        self.assertScriptsNonced(self.client.get(reverse('api-root'), HTTP_ACCEPT='text/html'))
+        self.assertScriptsNonced(self.client.get(reverse('dcim-api:site-list'), HTTP_ACCEPT='text/html'))
+
+    def test_api_script_sources_exist(self):
+        # The overrides copy upstream script tags, so an upgrade that renames a bundled file (e.g. jQuery) would
+        # leave a dead src. Every same-origin script src must resolve to a static file.
+        static_url = settings.STATIC_URL
+        responses = [
+            self.client.get(reverse('api_docs')),
+            self.client.get(reverse('api_redocs')),
+            self.client.get(reverse('api-root'), HTTP_ACCEPT='text/html'),
+        ]
+        for response in responses:
+            self.assertHttpStatus(response, 200)
+            checked = 0
+            for script in self.collect(response).scripts:
+                src = script.get('src')
+                if not src:
+                    continue
+                path = urlsplit(src).path
+                if not path.startswith(static_url):
+                    continue
+                checked += 1
+                relative = path.removeprefix(static_url)
+                self.assertTrue(finders.find(relative), f'No static file for script src {src}')
+            self.assertGreater(checked, 0, f'No same-origin scripts found on {response.request["PATH_INFO"]}')
+
+    def test_search_has_no_runtime_eval(self):
+        # A trigger filter such as keyup[...] is compiled with eval by htmx, which a policy without
+        # 'unsafe-eval' blocks (htmx then fires with no filter at all).
+        response = self.client.get(reverse('search'))
+        self.assertHttpStatus(response, 200)
+        collector = HxTriggerCollector()
+        collector.feed(response.content.decode())
+        self.assertEqual(len(collector.inputs), 1)
+        attrs = collector.inputs[0]
+        self.assertEqual(attrs['hx-trigger'], 'netbox:search-input changed delay:500ms')
+        self.assertEqual(attrs['data-search-min-length'], '3')

+ 64 - 0
netbox/netbox/tests/test_middleware.py

@@ -1,4 +1,5 @@
 import json
 import json
+import re
 from contextlib import contextmanager
 from contextlib import contextmanager
 from types import SimpleNamespace
 from types import SimpleNamespace
 from unittest import skipIf
 from unittest import skipIf
@@ -10,6 +11,7 @@ from django.core.signals import got_request_exception
 from django.db.utils import InternalError
 from django.db.utils import InternalError
 from django.test import Client, RequestFactory, override_settings
 from django.test import Client, RequestFactory, override_settings
 from django.urls import ResolverMatch, reverse
 from django.urls import ResolverMatch, reverse
+from django.utils.csp import CSP
 from django.views.generic import View
 from django.views.generic import View
 from rest_framework import status
 from rest_framework import status
 from rest_framework.views import APIView
 from rest_framework.views import APIView
@@ -17,6 +19,11 @@ from rest_framework.views import APIView
 from netbox.middleware import CoreMiddleware, LoginRequiredMiddleware, MaintenanceModeMiddleware
 from netbox.middleware import CoreMiddleware, LoginRequiredMiddleware, MaintenanceModeMiddleware
 from utilities.testing import TestCase
 from utilities.testing import TestCase
 
 
+CSP_POLICY = {
+    'default-src': [CSP.SELF],
+    'script-src': [CSP.SELF, CSP.NONCE],
+}
+
 
 
 class CoreMiddlewareTestCase(TestCase):
 class CoreMiddlewareTestCase(TestCase):
 
 
@@ -249,3 +256,60 @@ class LoginRequiredMiddlewareTestCase(TestCase):
     def test_plugin_views_login_not_required(self):
     def test_plugin_views_login_not_required(self):
         response = self.anonymous_client.get(reverse('plugins:dummy_plugin:dummy_model_list'))
         response = self.anonymous_client.get(reverse('plugins:dummy_plugin:dummy_model_list'))
         self.assertHttpStatus(response, 200)
         self.assertHttpStatus(response, 200)
+
+
+class ContentSecurityPolicyTestCase(TestCase):
+    """
+    SECURE_CSP and SECURE_CSP_REPORT_ONLY are passed through to Django's CSP middleware.
+    """
+
+    def setUp(self):
+        super().setUp()
+
+        self.anonymous_client = Client()
+
+    def get_nonce(self, response, header='Content-Security-Policy'):
+        match = re.search(r"'nonce-([^']+)'", response[header])
+        self.assertIsNotNone(match, f'No nonce in {header}: {response[header]}')
+        return match.group(1)
+
+    @override_settings(SECURE_CSP=CSP_POLICY)
+    def test_policy_sends_header_with_nonce(self):
+        response = self.anonymous_client.get(reverse('login'))
+        self.assertHttpStatus(response, 200)
+        self.assertIn("default-src 'self'", response['Content-Security-Policy'])
+        nonce = self.get_nonce(response)
+        self.assertIn(f'nonce="{nonce}"', response.content.decode())
+
+    @override_settings(SECURE_CSP=CSP_POLICY)
+    def test_nonce_differs_between_requests(self):
+        nonce1 = self.get_nonce(self.anonymous_client.get(reverse('login')))
+        nonce2 = self.get_nonce(self.anonymous_client.get(reverse('login')))
+        self.assertNotEqual(nonce1, nonce2)
+
+    @override_settings(SECURE_CSP_REPORT_ONLY=CSP_POLICY)
+    def test_report_only_policy(self):
+        response = self.anonymous_client.get(reverse('login'))
+        self.assertHttpStatus(response, 200)
+        self.assertNotIn('Content-Security-Policy', response)
+        nonce = self.get_nonce(response, header='Content-Security-Policy-Report-Only')
+        self.assertIn(f'nonce="{nonce}"', response.content.decode())
+
+    def test_no_header_by_default(self):
+        response = self.anonymous_client.get(reverse('login'))
+        self.assertHttpStatus(response, 200)
+        self.assertNotIn('Content-Security-Policy', response)
+        self.assertNotIn('Content-Security-Policy-Report-Only', response)
+
+    @override_settings(SECURE_CSP=CSP_POLICY, LOGIN_REQUIRED=True, DEBUG=False)
+    def test_header_on_non_html_responses(self):
+        requests = (
+            (reverse('home'), 302),
+            (reverse('api-root'), 403),
+            ('/no-such-page/', 404),
+        )
+        for url, status_code in requests:
+            with self.subTest(url=url):
+                response = self.anonymous_client.get(url)
+                self.assertHttpStatus(response, status_code)
+                self.assertIn("default-src 'self'", response['Content-Security-Policy'])

+ 127 - 0
netbox/netbox/tests/test_permissions_policy.py

@@ -0,0 +1,127 @@
+from unittest.mock import patch
+
+from django.http import HttpResponse
+from django.test import RequestFactory, SimpleTestCase, TestCase, override_settings
+from django.urls import reverse
+
+from netbox.middleware import PermissionsPolicyMiddleware
+from utilities.testing import TestCase as NetBoxTestCase
+
+HEADER = 'Permissions-Policy'
+
+DEFAULT_HEADER = 'camera=(), microphone=(), geolocation=(), payment=(), usb=(), hid=(), serial=(), bluetooth=()'
+
+
+class PermissionsPolicyHeaderTestCase(TestCase):
+    """
+    Check the header on real responses, through the whole middleware stack.
+    """
+
+    def test_default_denies_the_default_deny_list(self):
+        response = self.client.get(reverse('login'))
+        self.assertEqual(response[HEADER], DEFAULT_HEADER)
+
+    @override_settings(PERMISSIONS_POLICY={'camera': ['self'], 'geolocation': []})
+    def test_custom_policy_replaces_default(self):
+        response = self.client.get(reverse('login'))
+        self.assertEqual(response[HEADER], 'camera=(self), geolocation=()')
+
+    @override_settings(PERMISSIONS_POLICY={'camera': ['self', 'https://scan.example.com']})
+    def test_origins_are_quoted_and_self_is_a_token(self):
+        response = self.client.get(reverse('login'))
+        self.assertEqual(response[HEADER], 'camera=(self "https://scan.example.com")')
+
+    @override_settings(PERMISSIONS_POLICY={})
+    def test_empty_policy_sends_no_header(self):
+        response = self.client.get(reverse('login'))
+        self.assertNotIn(HEADER, response)
+
+
+class PermissionsPolicyContentTypeTestCase(NetBoxTestCase):
+    """
+    The header is only useful to a browser rendering a document, so raw API data responses carry none.
+    """
+
+    def setUp(self):
+        super().setUp()
+
+        self.user.is_superuser = True
+        self.user.save()
+
+    def test_rest_api_json_has_no_header(self):
+        response = self.client.get(reverse('api-root'), HTTP_ACCEPT='application/json')
+        self.assertEqual(response.status_code, 200)
+        self.assertTrue(response['Content-Type'].startswith('application/json'))
+        self.assertNotIn(HEADER, response)
+
+    def test_graphql_json_has_no_header(self):
+        response = self.client.post(
+            reverse('graphql'),
+            data='{"query": "{ __typename }"}',
+            content_type='application/json',
+        )
+        self.assertEqual(response.status_code, 200)
+        self.assertTrue(response['Content-Type'].startswith('application/json'))
+        self.assertNotIn(HEADER, response)
+
+    def test_browsable_api_html_has_header(self):
+        response = self.client.get(reverse('api-root'), HTTP_ACCEPT='text/html')
+        self.assertEqual(response.status_code, 200)
+        self.assertTrue(response['Content-Type'].startswith('text/html'))
+        self.assertEqual(response[HEADER], DEFAULT_HEADER)
+
+    def test_ui_page_has_header(self):
+        response = self.client.get(reverse('home'))
+        self.assertEqual(response.status_code, 200)
+        self.assertEqual(response[HEADER], DEFAULT_HEADER)
+
+
+class PermissionsPolicyMiddlewareTestCase(SimpleTestCase):
+    """
+    Check the middleware in isolation, with a view that sets the header itself.
+    """
+
+    def test_header_set_by_view_is_untouched(self):
+        def view(request):
+            response = HttpResponse()
+            response[HEADER] = 'fullscreen=(self)'
+            return response
+
+        response = PermissionsPolicyMiddleware(view)(RequestFactory().get('/'))
+        self.assertEqual(response[HEADER], 'fullscreen=(self)')
+
+    def test_redirects_and_not_modified_have_no_header(self):
+        for status in (301, 302, 304):
+            with self.subTest(status=status):
+                response = HttpResponse(status=status, content_type='text/html')
+                middleware = PermissionsPolicyMiddleware(lambda request, response=response: response)
+                self.assertNotIn(HEADER, middleware(RequestFactory().get('/')))
+
+    def test_html_200_has_header(self):
+        middleware = PermissionsPolicyMiddleware(lambda request: HttpResponse(content_type='text/html'))
+        self.assertEqual(middleware(RequestFactory().get('/'))[HEADER], DEFAULT_HEADER)
+
+    @override_settings(PERMISSIONS_POLICY={'camera': ['*']})
+    def test_lone_wildcard_is_a_bare_token(self):
+        response = PermissionsPolicyMiddleware(lambda request: HttpResponse(content_type='text/html'))(
+            RequestFactory().get('/')
+        )
+        self.assertEqual(response[HEADER], 'camera=*')
+
+    @override_settings(PERMISSIONS_POLICY={'camera': ['*', 'self']})
+    def test_wildcard_with_other_origins_stays_an_inner_list(self):
+        response = PermissionsPolicyMiddleware(lambda request: HttpResponse(content_type='text/html'))(
+            RequestFactory().get('/')
+        )
+        self.assertEqual(response[HEADER], 'camera=(* self)')
+
+    def test_header_is_built_once_per_instance(self):
+        with patch.object(
+            PermissionsPolicyMiddleware, 'build_header', wraps=PermissionsPolicyMiddleware.build_header
+        ) as build_header:
+            middleware = PermissionsPolicyMiddleware(lambda request: HttpResponse())
+            first = middleware(RequestFactory().get('/'))
+            second = middleware(RequestFactory().get('/'))
+        build_header.assert_called_once()
+        self.assertEqual(first[HEADER], DEFAULT_HEADER)
+        self.assertEqual(second[HEADER], DEFAULT_HEADER)

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

@@ -222,7 +222,7 @@ class SearchBackendTestCase(TestCase):
             # Unnamed devices render as "<manufacturer> <model> (<pk>)"; prefixes display their scope (a site)
             # Unnamed devices render as "<manufacturer> <model> (<pk>)"; prefixes display their scope (a site)
             for site in sites:
             for site in sites:
                 Device.objects.create(site=site, device_type=device_type, role=role, description='Batched')
                 Device.objects.create(site=site, device_type=device_type, role=role, description='Batched')
-                Prefix.objects.create(prefix=f'10.0.{site.pk}.0/24', scope=site, description='Batched')
+                Prefix.objects.create(prefix=f'10.0.{all_sites.index(site)}.0/24', scope=site, description='Batched')
             search_backend.cache(Device.objects.all())
             search_backend.cache(Device.objects.all())
             search_backend.cache(Prefix.objects.all())
             search_backend.cache(Prefix.objects.all())
 
 
@@ -232,15 +232,15 @@ class SearchBackendTestCase(TestCase):
                 rendered = [(result.name, list(result.display_attrs.values())) for result in results]
                 rendered = [(result.name, list(result.display_attrs.values())) for result in results]
             return rendered, len(queries)
             return rendered, len(queries)
 
 
-        sites = list(Site.objects.order_by('name'))
-        rendered, query_count = render_results(sites[:1])
+        all_sites = list(Site.objects.order_by('name'))
+        rendered, query_count = render_results(all_sites[:1])
         self.assertEqual(len(rendered), 2)
         self.assertEqual(len(rendered), 2)
-        rendered, more_query_count = render_results(sites[1:])
+        rendered, more_query_count = render_results(all_sites[1:])
         self.assertEqual(len(rendered), 6)
         self.assertEqual(len(rendered), 6)
         self.assertEqual(more_query_count, query_count)
         self.assertEqual(more_query_count, query_count)
 
 
         self.assertEqual(sum(name.startswith('Manufacturer 1 Device Type 1') for name, _ in rendered), 3)
         self.assertEqual(sum(name.startswith('Manufacturer 1 Device Type 1') for name, _ in rendered), 3)
-        self.assertCountEqual([attrs[0] for name, attrs in rendered if name.startswith('10.0.')], sites)
+        self.assertCountEqual([attrs[0] for name, attrs in rendered if name.startswith('10.0.')], all_sites)
 
 
 
 
 class DeferredCachingTestCase(RQQueueTestMixin, TestCase):
 class DeferredCachingTestCase(RQQueueTestMixin, TestCase):

+ 67 - 0
netbox/netbox/tests/test_settings_utils.py

@@ -397,6 +397,73 @@ class ValidateWebhookDefaultTimeoutTest(SimpleTestCase):
                     settings_utils.validate_webhook_default_timeout(timeout, 300)
                     settings_utils.validate_webhook_default_timeout(timeout, 300)
 
 
 
 
+class ValidatePermissionsPolicyTest(SimpleTestCase):
+    """validate_permissions_policy() is the startup check applied to PERMISSIONS_POLICY."""
+
+    def test_valid_policies(self):
+        valid = (
+            {},
+            {'camera': []},
+            {'camera': ['self']},
+            {'camera': ['*']},
+            {'camera': ('self',)},
+            {'camera': ['self', 'https://scan.example.com'], 'usb': []},
+            {'camera': ['http://localhost:8000']},
+            {'camera': ['https://[::1]:8443']},
+            {'camera': ['https://*.example.com']},
+            {'camera': ['https://*.example.com:8443']},
+            {'camera': ['https://localhost']},
+            {'camera': ['https://xn--bcher-kva.example']},
+            {'camera': ['https://scan_1.example.com']},
+            {'camera': ['https://_service.example.com']},
+        )
+        for value in valid:
+            with self.subTest(value=value):
+                settings_utils.validate_permissions_policy('PERMISSIONS_POLICY', value)
+
+    def test_csp_quoted_keywords_raise(self):
+        for entry in ("'self'", "'none'"):
+            with self.subTest(entry=entry):
+                with self.assertRaisesMessage(ImproperlyConfigured, 'without the CSP quotes'):
+                    settings_utils.validate_permissions_policy('PERMISSIONS_POLICY', {'camera': [entry]})
+
+    def test_error_names_feature_and_entry(self):
+        with self.assertRaisesMessage(ImproperlyConfigured, "camera"):
+            settings_utils.validate_permissions_policy('PERMISSIONS_POLICY', {'camera': ['scan.example.com']})
+        with self.assertRaisesMessage(ImproperlyConfigured, "'scan.example.com'"):
+            settings_utils.validate_permissions_policy('PERMISSIONS_POLICY', {'camera': ['scan.example.com']})
+
+    def test_malformed_feature_names_raise(self):
+        for feature in ('camera ()', 'cam=era', 'Camera', '', 5, '1camera', '-camera'):
+            with self.subTest(feature=feature):
+                with self.assertRaisesMessage(ImproperlyConfigured, repr(feature)):
+                    settings_utils.validate_permissions_policy('PERMISSIONS_POLICY', {feature: []})
+
+    def test_well_formed_feature_names_are_not_checked_against_a_list(self):
+        for feature in ('camera', 'publickey-credentials-get', 'future-feature'):
+            with self.subTest(feature=feature):
+                settings_utils.validate_permissions_policy('PERMISSIONS_POLICY', {feature: []})
+
+    def test_bare_string_value_raises(self):
+        with self.assertRaisesMessage(ImproperlyConfigured, 'must be a list or tuple'):
+            settings_utils.validate_permissions_policy('PERMISSIONS_POLICY', {'camera': 'self'})
+
+    def test_invalid_origins_raise(self):
+        invalid = (
+            'scan.example.com', 'ftp://scan.example.com', 'https://', 'https://example.com/path', '', 5,
+            'https://u@x', 'https://x:abc', 'https://x:99999', 'https://x:', 'https://x?', 'https://x#',
+            'https://x y', 'https:// x', 'HTTPS://x',
+            'https://x"y', 'https://x,y', 'https://x;y', 'https://x%20y', 'https://x\x00', 'https://x\x7f',
+            'https://bücher.example',
+            'https://*', 'https://ex*ample.com', 'https://a*b.example.com', 'https://*.*.example.com',
+            'https://-', 'https://..', 'https://.example.com', 'https://example.com.', 'https://*.example.com:',
+        )
+        for entry in invalid:
+            with self.subTest(entry=entry):
+                with self.assertRaises(ImproperlyConfigured):
+                    settings_utils.validate_permissions_policy('PERMISSIONS_POLICY', {'camera': [entry]})
+
+
 class LoadLdapConfigTest(SimpleTestCase):
 class LoadLdapConfigTest(SimpleTestCase):
     def test_loads_sibling_ldap_config(self):
     def test_loads_sibling_ldap_config(self):
         with tempfile.TemporaryDirectory() as conf_dir:
         with tempfile.TemporaryDirectory() as conf_dir:

+ 13 - 0
netbox/netbox/tests/test_ui.py

@@ -4,6 +4,7 @@ from types import SimpleNamespace
 from django.template import Context, Template
 from django.template import Context, Template
 from django.test import RequestFactory, SimpleTestCase, TestCase
 from django.test import RequestFactory, SimpleTestCase, TestCase
 from django.urls import reverse
 from django.urls import reverse
+from django.utils import translation
 from netaddr import IPNetwork
 from netaddr import IPNetwork
 
 
 from account.models import UserToken
 from account.models import UserToken
@@ -313,6 +314,12 @@ class NumericAttrTestCase(TestCase):
         context = attr.get_context(obj, 'speed', 1000, {})
         context = attr.get_context(obj, 'speed', 1000, {})
         self.assertTrue(context['copy_button'])
         self.assertTrue(context['copy_button'])
 
 
+    def test_render_localize(self):
+        obj = SimpleNamespace(x=-8238310.24)
+        with translation.override('de'):
+            self.assertIn('-8238310,24', attrs.NumericAttr('x').render(obj, {'name': 'x'}))
+            self.assertIn('-8238310.24', attrs.NumericAttr('x', localize=False).render(obj, {'name': 'x'}))
+
 
 
 class BooleanAttrTestCase(TestCase):
 class BooleanAttrTestCase(TestCase):
 
 
@@ -745,6 +752,12 @@ class WeightAttrTestCase(SimpleTestCase):
         self.assertIn('10', result)
         self.assertIn('10', result)
         self.assertIn('lbs', result)
         self.assertIn('lbs', result)
 
 
+    def test_render_localized(self):
+        attr = attrs.WeightAttr('weight')
+        obj = self._obj(Decimal('2.5'), 'kg', 2500, 'Kilograms')
+        with translation.override('de'):
+            self.assertIn('2,5', attr.render(obj, self._ctx()))
+
 
 
 class DistanceAttrTestCase(SimpleTestCase):
 class DistanceAttrTestCase(SimpleTestCase):
 
 

+ 69 - 3
netbox/netbox/tests/test_views.py

@@ -10,9 +10,9 @@ from django.test import Client, TransactionTestCase, override_settings, tag
 from django.urls import reverse
 from django.urls import reverse
 from django.utils import timezone
 from django.utils import timezone
 
 
-from core.models import DataFile, DataSource, ObjectChange
+from core.models import DataFile, DataSource, ObjectChange, ObjectType
 from dcim.choices import DeviceStatusChoices, InterfaceTypeChoices, SiteStatusChoices
 from dcim.choices import DeviceStatusChoices, InterfaceTypeChoices, SiteStatusChoices
-from dcim.models import Device, DeviceRole, DeviceType, Interface, Manufacturer, Site, VirtualChassis
+from dcim.models import Device, DeviceRole, DeviceType, Interface, Manufacturer, ModuleType, Site, VirtualChassis
 from dcim.tables import SiteTable
 from dcim.tables import SiteTable
 from extras.events import enqueue_event
 from extras.events import enqueue_event
 from extras.models import ImageAttachment
 from extras.models import ImageAttachment
@@ -25,7 +25,7 @@ from netbox.constants import EMPTY_TABLE_TEXT
 from netbox.search.backends import search_backend
 from netbox.search.backends import search_backend
 from netbox.views import generic
 from netbox.views import generic
 from users.constants import TOKEN_PREFIX
 from users.constants import TOKEN_PREFIX
-from users.models import Token, User
+from users.models import ObjectPermission, Token, User
 from utilities.exceptions import AbortRequest
 from utilities.exceptions import AbortRequest
 from utilities.testing import TestCase
 from utilities.testing import TestCase
 from utilities.views import get_action_url
 from utilities.views import get_action_url
@@ -337,6 +337,12 @@ class MediaViewTestCase(TestCase):
             manufacturer=manufacturer,
             manufacturer=manufacturer,
             front_image='devicetype-images/front.jpg',
             front_image='devicetype-images/front.jpg',
         )
         )
+        cls.module_type = ModuleType.objects.create(
+            model='Module Type 1',
+            manufacturer=manufacturer,
+            front_image='moduletype-images/front.jpg',
+            rear_image='moduletype-images/rear.jpg',
+        )
 
 
     def test_media_login_required(self):
     def test_media_login_required(self):
         url = reverse('media', kwargs={'path': 'foo.txt'})
         url = reverse('media', kwargs={'path': 'foo.txt'})
@@ -404,6 +410,66 @@ class MediaViewTestCase(TestCase):
         response = self.client.get(url)
         response = self.client.get(url)
         self.assertHttpStatus(response, 404)
         self.assertHttpStatus(response, 404)
 
 
+    def test_module_type_with_permission(self):
+        """
+        A user who can view a module type should receive both of its images.
+        """
+        self.add_permissions('dcim.view_moduletype')
+        for image in (self.module_type.front_image, self.module_type.rear_image):
+            url = reverse('media', kwargs={'path': image.name})
+            with patch('netbox.views.misc.serve', return_value=HttpResponse(status=200)):
+                response = self.client.get(url)
+            self.assertHttpStatus(response, 200)
+            self.assertEqual(response['Content-Security-Policy'], "sandbox; default-src 'none'")
+            self.assertEqual(response['X-Content-Type-Options'], "nosniff")
+
+    def test_module_type_without_permission(self):
+        """
+        A user who cannot view a module type should get a 404 for its image.
+        """
+        # serve() is stubbed because it would 404 anyway, the fixture files not being on disk
+        url = reverse('media', kwargs={'path': self.module_type.front_image.name})
+        with patch('netbox.views.misc.serve', return_value=HttpResponse(status=200)) as serve:
+            response = self.client.get(url)
+        self.assertHttpStatus(response, 404)
+        serve.assert_not_called()
+
+    def test_module_type_traversal_without_permission(self):
+        """
+        A traversal path that normalizes to a module type image should still be denied.
+        """
+        traversal_path = 'foo/../' + self.module_type.front_image.name
+        url = reverse('media', kwargs={'path': traversal_path})
+        with patch('netbox.views.misc.serve', return_value=HttpResponse(status=200)) as serve:
+            response = self.client.get(url)
+        self.assertHttpStatus(response, 404)
+        serve.assert_not_called()
+
+    def test_module_type_with_constrained_permission(self):
+        """
+        A constrained view permission should serve only the images of the module types it covers.
+        """
+        hidden_type = ModuleType.objects.create(
+            model='Module Type 2',
+            manufacturer=self.module_type.manufacturer,
+            front_image='moduletype-images/hidden.jpg',
+        )
+        obj_perm = ObjectPermission(
+            name='Test permission',
+            actions=['view'],
+            constraints={'pk': self.module_type.pk},
+        )
+        obj_perm.save()
+        obj_perm.users.add(self.user)
+        obj_perm.object_types.add(ObjectType.objects.get_for_model(ModuleType))
+
+        with patch('netbox.views.misc.serve', return_value=HttpResponse(status=200)) as serve:
+            response = self.client.get(reverse('media', kwargs={'path': self.module_type.front_image.name}))
+            self.assertHttpStatus(response, 200)
+            response = self.client.get(reverse('media', kwargs={'path': hidden_type.front_image.name}))
+            self.assertHttpStatus(response, 404)
+        serve.assert_called_once()
+
 
 
 class DeleteAtomicityMixin:
 class DeleteAtomicityMixin:
     """
     """

+ 4 - 1
netbox/netbox/ui/attrs.py

@@ -169,19 +169,22 @@ class NumericAttr(ObjectAttribute):
     Parameters:
     Parameters:
          unit_accessor (str): Accessor for the unit of measurement to display alongside the value (if any)
          unit_accessor (str): Accessor for the unit of measurement to display alongside the value (if any)
          copy_button (bool): Set to True to include a copy-to-clipboard button
          copy_button (bool): Set to True to include a copy-to-clipboard button
+         localize (bool): Set to False to render the value without locale-specific formatting
     """
     """
     template_name = 'ui/attrs/numeric.html'
     template_name = 'ui/attrs/numeric.html'
 
 
-    def __init__(self, *args, unit_accessor=None, copy_button=False, **kwargs):
+    def __init__(self, *args, unit_accessor=None, copy_button=False, localize=True, **kwargs):
         super().__init__(*args, **kwargs)
         super().__init__(*args, **kwargs)
         self.unit_accessor = unit_accessor
         self.unit_accessor = unit_accessor
         self.copy_button = copy_button
         self.copy_button = copy_button
+        self.localize = localize
 
 
     def get_context(self, obj, attr, value, context):
     def get_context(self, obj, attr, value, context):
         unit = resolve_attr_path(obj, self.unit_accessor) if self.unit_accessor else None
         unit = resolve_attr_path(obj, self.unit_accessor) if self.unit_accessor else None
         return {
         return {
             'unit': unit,
             'unit': unit,
             'copy_button': self.copy_button,
             'copy_button': self.copy_button,
+            'localize': self.localize,
         }
         }
 
 
 
 

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

@@ -18,7 +18,7 @@ from django.views.static import serve
 from django_tables2 import RequestConfig
 from django_tables2 import RequestConfig
 from packaging import version
 from packaging import version
 
 
-from dcim.models import DeviceType
+from dcim.models import DeviceType, ModuleType
 from extras.constants import DEFAULT_DASHBOARD
 from extras.constants import DEFAULT_DASHBOARD
 from extras.dashboard.utils import get_dashboard, get_default_dashboard
 from extras.dashboard.utils import get_dashboard, get_default_dashboard
 from extras.models import ImageAttachment
 from extras.models import ImageAttachment
@@ -158,6 +158,11 @@ class MediaView(TokenConditionalLoginRequiredMixin, View):
                 Q(front_image=path) | Q(rear_image=path)
                 Q(front_image=path) | Q(rear_image=path)
             ).exists():
             ).exists():
                 raise Http404
                 raise Http404
+        elif path.startswith('moduletype-images/'):
+            if not ModuleType.objects.restrict(request.user, 'view').filter(
+                Q(front_image=path) | Q(rear_image=path)
+            ).exists():
+                raise Http404
 
 
         response = serve(request, path, document_root=settings.MEDIA_ROOT)
         response = serve(request, path, document_root=settings.MEDIA_ROOT)
         response['Content-Security-Policy'] = "sandbox; default-src 'none'"
         response['Content-Security-Policy'] = "sandbox; default-src 'none'"

Dosya farkı çok büyük olduğundan ihmal edildi
+ 0 - 0
netbox/project-static/dist/netbox.js


Dosya farkı çok büyük olduğundan ihmal edildi
+ 0 - 0
netbox/project-static/dist/netbox.js.map


+ 5 - 0
netbox/project-static/src/global.d.ts

@@ -96,5 +96,10 @@ interface HTMLElementEventMap {
     parameters: Record<string, string>;
     parameters: Record<string, string>;
     formData: FormData;
     formData: FormData;
     headers: Record<string, string>;
     headers: Record<string, string>;
+    elt: Element;
   }>;
   }>;
 }
 }
+
+interface DocumentEventMap {
+  'htmx:configRequest': HTMLElementEventMap['htmx:configRequest'];
+}

+ 35 - 0
netbox/project-static/src/htmx.ts

@@ -45,11 +45,46 @@ function revealSubmissionErrors(event: Event): void {
   }
   }
 }
 }
 
 
+/**
+ * Dispatch `netbox:search-input` on an input once its value reaches the length in
+ * `data-search-min-length`. The input's `hx-trigger` listens for this event instead of using a
+ * `keyup[...]` filter, which htmx compiles with runtime eval.
+ */
+function dispatchSearchInput(event: KeyboardEvent): void {
+  const input = event.target;
+  if (!(input instanceof HTMLInputElement)) return;
+  const rawMinLength = input.dataset.searchMinLength;
+  if (!rawMinLength) return;
+  const minLength = Number(rawMinLength);
+  if (Number.isNaN(minLength)) return;
+  if (input.value.length >= minLength) {
+    input.dispatchEvent(new CustomEvent('netbox:search-input', { bubbles: true }));
+  }
+}
+
+/**
+ * Blank the request parameter named by `data-htmx-clear-param` on the requesting element. The
+ * generic object selector uses this so a stale object ID can't cross content types. It replaces
+ * an `hx-on::config-request` attribute, which htmx evaluates at runtime.
+ */
+function clearConfiguredParam(event: HTMLElementEventMap['htmx:configRequest']): void {
+  const { elt, parameters } = event.detail;
+  const param = elt.getAttribute('data-htmx-clear-param');
+  if (param) {
+    parameters[param] = '';
+  }
+}
+
 /**
 /**
  * Hook into HTMX's event system to reinitialize specific native event listeners when HTMX swaps
  * Hook into HTMX's event system to reinitialize specific native event listeners when HTMX swaps
  * elements.
  * elements.
  */
  */
 export function initHtmx(): void {
 export function initHtmx(): void {
+  // htmx.config.allowEval stays at its default: a CSP without 'unsafe-eval' already blocks eval,
+  // and disabling it would break plugins that use hx-on or trigger filters. See #23503.
+  document.addEventListener('keyup', dispatchSearchInput);
+  document.addEventListener('htmx:configRequest', clearConfiguredParam);
+
   document.addEventListener('htmx:afterSettle', event => {
   document.addEventListener('htmx:afterSettle', event => {
     initDepedencies();
     initDepedencies();
     revealSubmissionErrors(event);
     revealSubmissionErrors(event);

+ 1 - 1
netbox/templates/account/usertoken_edit.html

@@ -8,7 +8,7 @@
 
 
 {% block javascript %}
 {% block javascript %}
 {{ block.super }}
 {{ block.super }}
-<script>
+<script nonce="{{ csp_nonce }}">
   (function () {
   (function () {
     const versionField = document.getElementById('id_version');
     const versionField = document.getElementById('id_version');
     const v1Warning = document.getElementById('v1-deprecation-warning');
     const v1Warning = document.getElementById('v1-deprecation-warning');

+ 18 - 7
netbox/templates/base/base.html

@@ -24,19 +24,29 @@
     {# Page title #}
     {# Page title #}
     <title>{% block title %}{% trans "Home" %}{% endblock %} | NetBox</title>
     <title>{% block title %}{% trans "Home" %}{% endblock %} | NetBox</title>
 
 
+    {# Redirect to the media failure page if a core static asset fails to load. Must precede those assets. #}
+    <script type="text/javascript" nonce="{{ csp_nonce }}">
+      window.addEventListener('error', function (event) {
+        if (event.target instanceof Element && event.target.dataset.mediaFailure) {
+          window.location = '{% url 'media_failure' %}?filename=' + event.target.dataset.mediaFailure;
+        }
+      }, true);
+    </script>
+
     {# Initialize color mode and sidebar folding #}
     {# Initialize color mode and sidebar folding #}
     <script
     <script
       type="text/javascript"
       type="text/javascript"
       src="{% static_with_params 'setmode.js' v=settings.RELEASE.version %}"
       src="{% static_with_params 'setmode.js' v=settings.RELEASE.version %}"
-      onerror="window.location='{% url 'media_failure' %}?filename=setmode.js'">
+      data-media-failure="setmode.js"
+      nonce="{{ csp_nonce }}">
     </script>
     </script>
-    <script type="text/javascript">
+    <script type="text/javascript" nonce="{{ csp_nonce }}">
       (function () {
       (function () {
         initMode()
         initMode()
       })();
       })();
       window.CSRF_TOKEN = "{{ csrf_token }}";
       window.CSRF_TOKEN = "{{ csrf_token }}";
     </script>
     </script>
-    <script type="text/javascript">
+    <script type="text/javascript" nonce="{{ csp_nonce }}">
       initSidebar();
       initSidebar();
     </script>
     </script>
 
 
@@ -44,12 +54,12 @@
     <link
     <link
       rel="stylesheet"
       rel="stylesheet"
       href="{% static_with_params 'netbox-external.css' v=settings.RELEASE.version %}"
       href="{% static_with_params 'netbox-external.css' v=settings.RELEASE.version %}"
-      onerror="window.location='{% url 'media_failure' %}?filename=netbox-external.css'"
+      data-media-failure="netbox-external.css"
     />
     />
     <link
     <link
       rel="stylesheet"
       rel="stylesheet"
       href="{% static_with_params 'netbox.css' v=settings.RELEASE.version %}"
       href="{% static_with_params 'netbox.css' v=settings.RELEASE.version %}"
-      onerror="window.location='{% url 'media_failure' %}?filename=netbox.css'"
+      data-media-failure="netbox.css"
     />
     />
     <link rel="icon" type="image/png" href="{% static 'netbox.ico' %}" />
     <link rel="icon" type="image/png" href="{% static 'netbox.ico' %}" />
     <link rel="apple-touch-icon" type="image/png" href="{% static 'netbox_touch-icon-180.png' %}" />
     <link rel="apple-touch-icon" type="image/png" href="{% static 'netbox_touch-icon-180.png' %}" />
@@ -58,7 +68,8 @@
     <script
     <script
       type="text/javascript"
       type="text/javascript"
       src="{% static_with_params 'netbox.js' v=settings.RELEASE.version %}"
       src="{% static_with_params 'netbox.js' v=settings.RELEASE.version %}"
-      onerror="window.location='{% url 'media_failure' %}?filename=netbox.js'">
+      data-media-failure="netbox.js"
+      nonce="{{ csp_nonce }}">
     </script>
     </script>
     {% django_htmx_script %}
     {% django_htmx_script %}
 
 
@@ -74,7 +85,7 @@
 
 
     {# Additional Javascript #}
     {# Additional Javascript #}
     {% if copilot_enabled and request.user.is_authenticated %}
     {% if copilot_enabled and request.user.is_authenticated %}
-      <script src="{{ settings.NETBOX_COPILOT_URL }}" defer></script>
+      <script src="{{ settings.NETBOX_COPILOT_URL }}" defer nonce="{{ csp_nonce }}"></script>
     {% endif %}
     {% endif %}
     {% block javascript %}{% endblock %}
     {% block javascript %}{% endblock %}
 
 

+ 20 - 0
netbox/templates/dcim/panels/module_type.html

@@ -27,5 +27,25 @@
         </td>
         </td>
       </tr>
       </tr>
     {% endfor %}
     {% endfor %}
+    <tr>
+      <th scope="row">{% trans "Front image" %}</th>
+      <td>
+        {% if object.module_type.front_image %}
+          {% include "ui/attrs/image.html" with value=object.module_type.front_image load_lazy=True decoding="async" only %}
+        {% else %}
+          {{ ''|placeholder }}
+        {% endif %}
+      </td>
+    </tr>
+    <tr>
+      <th scope="row">{% trans "Rear image" %}</th>
+      <td>
+        {% if object.module_type.rear_image %}
+          {% include "ui/attrs/image.html" with value=object.module_type.rear_image load_lazy=True decoding="async" only %}
+        {% else %}
+          {{ ''|placeholder }}
+        {% endif %}
+      </td>
+    </tr>
   </table>
   </table>
 {% endblock panel_content %}
 {% endblock panel_content %}

+ 16 - 0
netbox/templates/drf_spectacular/redoc.html

@@ -0,0 +1,16 @@
+{# Extends the upstream drf_spectacular template of the same name. The body block copies upstream to add CSP nonces: re-sync it when drf-spectacular is upgraded. #}
+{% extends 'drf_spectacular/redoc.html' %}
+
+{% block body %}
+  {% if settings %}
+    <div id="redoc-container"></div>
+    <script src="{{ redoc_standalone }}" nonce="{{ csp_nonce }}"></script>
+    <script nonce="{{ csp_nonce }}">
+      const redocSettings = {{ settings|safe }};
+      Redoc.init("{{ schema_url }}", redocSettings, document.getElementById('redoc-container'))
+    </script>
+  {% else %}
+    <redoc spec-url="{{ schema_url }}"></redoc>
+    <script src="{{ redoc_standalone }}" nonce="{{ csp_nonce }}"></script>
+  {% endif %}
+{% endblock body %}

+ 15 - 0
netbox/templates/drf_spectacular/swagger_ui.html

@@ -0,0 +1,15 @@
+{# Extends the upstream drf_spectacular template of the same name. The body block copies upstream to add CSP nonces: re-sync it when drf-spectacular is upgraded. #}
+{% extends 'drf_spectacular/swagger_ui.html' %}
+
+{% block body %}
+  <div id="swagger-ui"></div>
+  <script src="{{ swagger_ui_bundle }}" nonce="{{ csp_nonce }}"></script>
+  <script src="{{ swagger_ui_standalone }}" nonce="{{ csp_nonce }}"></script>
+  {% if script_url %}
+    <script src="{{ script_url }}" nonce="{{ csp_nonce }}"></script>
+  {% else %}
+    <script nonce="{{ csp_nonce }}">
+      {% include template_name_js %}
+    </script>
+  {% endif %}
+{% endblock body %}

+ 1 - 1
netbox/templates/graphql/graphiql.html

@@ -56,6 +56,6 @@
       data-graphql-worker="{% url 'graphiql_worker' name='graphql' %}"
       data-graphql-worker="{% url 'graphiql_worker' name='graphql' %}"
       data-json-worker="{% url 'graphiql_worker' name='json' %}"
       data-json-worker="{% url 'graphiql_worker' name='json' %}"
     >Loading...</div>
     >Loading...</div>
-    <script src="{% static_with_params 'graphiql/graphiql.js' v=settings.RELEASE.version %}"></script>
+    <script src="{% static_with_params 'graphiql/graphiql.js' v=settings.RELEASE.version %}" nonce="{{ csp_nonce }}"></script>
   </body>
   </body>
 </html>
 </html>

+ 17 - 0
netbox/templates/rest_framework/api.html

@@ -7,6 +7,23 @@
   <link rel="icon" type="image/png" href="{% static 'rest-api.ico' %}" />
   <link rel="icon" type="image/png" href="{% static 'rest-api.ico' %}" />
 {% endblock head %}
 {% endblock head %}
 
 
+{% block script %}
+  {# Copies the upstream DRF script block to add CSP nonces: re-sync it when djangorestframework is upgraded. #}
+  <script type="application/json" id="drf_csrf" nonce="{{ csp_nonce }}">
+    {
+      "csrfHeaderName": "{{ csrf_header_name|default:'X-CSRFToken' }}",
+      "csrfToken": "{% if request %}{{ csrf_token }}{% endif %}"
+    }
+  </script>
+  <script src="{% static 'rest_framework/js/jquery-3.7.1.min.js' %}" nonce="{{ csp_nonce }}"></script>
+  <script src="{% static 'rest_framework/js/ajax-form.js' %}" nonce="{{ csp_nonce }}"></script>
+  <script src="{% static 'rest_framework/js/csrf.js' %}" nonce="{{ csp_nonce }}"></script>
+  <script src="{% static 'rest_framework/js/bootstrap.min.js' %}" nonce="{{ csp_nonce }}"></script>
+  <script src="{% static 'rest_framework/js/prettify-min.js' %}" nonce="{{ csp_nonce }}"></script>
+  <script src="{% static 'rest_framework/js/default.js' %}" nonce="{{ csp_nonce }}"></script>
+  <script src="{% static 'rest_framework/js/load-ajax-form.js' %}" nonce="{{ csp_nonce }}"></script>
+{% endblock script %}
+
 {% block title %}{% if name %}{{ name }} | {% endif %}NetBox {% trans "REST API" %}{% endblock %}
 {% block title %}{% if name %}{{ name }} | {% endif %}NetBox {% trans "REST API" %}{% endblock %}
 
 
 {% block branding %}
 {% block branding %}

+ 2 - 2
netbox/templates/ui/attrs/numeric.html

@@ -1,6 +1,6 @@
-{% load i18n %}
+{% load i18n l10n %}
 <span>
 <span>
-  <span{% if name %} id="attr_{{ name }}"{% endif %}>{{ value }}</span>
+  <span{% if name %} id="attr_{{ name }}"{% endif %}>{% if localize is False %}{{ value|unlocalize }}{% else %}{{ value }}{% endif %}</span>
   {% if unit %}
   {% if unit %}
     {{ unit|lower }}
     {{ unit|lower }}
   {% endif %}
   {% endif %}

+ 1 - 1
netbox/templates/users/token_edit.html

@@ -20,7 +20,7 @@
 
 
 {% block javascript %}
 {% block javascript %}
 {{ block.super }}
 {{ block.super }}
-<script>
+<script nonce="{{ csp_nonce }}">
   (function () {
   (function () {
     const versionField = document.getElementById('id_version');
     const versionField = document.getElementById('id_version');
     const v1Warning = document.getElementById('v1-deprecation-warning');
     const v1Warning = document.getElementById('v1-deprecation-warning');

+ 2 - 3
netbox/utilities/forms/fields/generic.py

@@ -195,9 +195,8 @@ class GenericObjectChoiceField(forms.MultiValueField):
 
 
         # Clear the paired object selection client-side when the content type changes, so a stale object_id
         # Clear the paired object selection client-side when the content type changes, so a stale object_id
         # cannot cross model boundaries on the HTMX re-render (a Site pk must not resurface as a Region pk).
         # cannot cross model boundaries on the HTMX re-render (a Site pk must not resurface as a Region pk).
-        self.content_type_field.widget.attrs['hx-on::config-request'] = (
-            f"event.detail.parameters['{field_name}_object_id'] = ''"
-        )
+        # The htmx:configRequest listener in htmx.ts blanks the parameter named here.
+        self.content_type_field.widget.attrs['data-htmx-clear-param'] = f'{field_name}_object_id'
 
 
         content_type_value = self._resolve_subvalue(form, field_name, 'content_type')
         content_type_value = self._resolve_subvalue(form, field_name, 'content_type')
         object_value = self._resolve_subvalue(form, field_name, 'object_id')
         object_value = self._resolve_subvalue(form, field_name, 'object_id')

+ 4 - 4
netbox/utilities/tests/test_forms.py

@@ -909,10 +909,10 @@ class GenericObjectChoiceFieldTestCase(TestCase):
         form = self._make_form(initial={'obj': self.site})
         form = self._make_form(initial={'obj': self.site})
         field = form.fields['obj']
         field = form.fields['obj']
         field.get_bound_field(form, 'obj')
         field.get_bound_field(form, 'obj')
-        self.assertEqual(
-            field.content_type_field.widget.attrs.get('hx-on::config-request'),
-            "event.detail.parameters['obj_object_id'] = ''",
-        )
+        attrs = field.content_type_field.widget.attrs
+        self.assertEqual(attrs.get('data-htmx-clear-param'), 'obj_object_id')
+        # The clearing is done by a listener in the static bundle, not by htmx runtime eval.
+        self.assertNotIn('hx-on::config-request', attrs)
 
 
     def test_content_type_lookup_is_cached(self):
     def test_content_type_lookup_is_cached(self):
         """Repeated content-type resolution hits the database only once per field instance."""
         """Repeated content-type resolution hits the database only once per field instance."""

+ 21 - 0
netbox/virtualization/tests/test_models.py

@@ -5,6 +5,7 @@ from django.test import TestCase, tag
 from netaddr import IPNetwork
 from netaddr import IPNetwork
 
 
 from dcim.models import Platform, Region, Site, SiteGroup
 from dcim.models import Platform, Region, Site, SiteGroup
+from extras.models import ConfigTemplate
 from ipam.models import IPAddress
 from ipam.models import IPAddress
 from tenancy.models import Tenant
 from tenancy.models import Tenant
 from utilities.testing import create_test_device, create_test_virtualmachine
 from utilities.testing import create_test_device, create_test_virtualmachine
@@ -745,3 +746,23 @@ class VirtualMachineTestCase(TestCase):
                 with self.assertRaises(ValidationError) as context:
                 with self.assertRaises(ValidationError) as context:
                     VirtualMachine(name='vm2', cluster=vm.cluster, **{field: ip}).full_clean()
                     VirtualMachine(name='vm2', cluster=vm.cluster, **{field: ip}).full_clean()
                 self.assertIn(field, context.exception.message_dict)
                 self.assertIn(field, context.exception.message_dict)
+
+
+class VirtualMachineRenderConfigTestCase(TestCase):
+
+    def test_render_config(self):
+        vm = create_test_virtualmachine('VM 1')
+        vm.local_context_data = {'foo': 'context'}
+        vm.save()
+        self.assertIsNone(vm.render_config())
+
+        vm.platform = Platform.objects.create(
+            name='Platform 1',
+            slug='platform-1',
+            config_template=ConfigTemplate.objects.create(
+                name='Template 1', template_code='{{ virtualmachine.name }} {{ foo }} {{ bar }}'
+            ),
+        )
+        vm.save()
+        self.assertEqual(vm.render_config(extra_context={'bar': 'extra'}), 'VM 1 context extra')
+        self.assertEqual(vm.get_render_context({'virtualmachine': 'spoofed'})['virtualmachine'], vm)

Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor