Arthur 2 giorni fa
parent
commit
4b83429565
59 ha cambiato i file con 2015 aggiunte e 77 eliminazioni
  1. 6 0
      docs/features/contacts.md
  2. 2 0
      docs/features/devices-cabling.md
  3. 1 1
      docs/features/l2vpn-overlay.md
  4. 2 0
      docs/models/dcim/macaddress.md
  5. 33 0
      docs/models/dcim/macblock.md
  6. 1 1
      docs/models/vpn/l2vpn.md
  7. 5 3
      docs/models/vpn/l2vpntermination.md
  8. 1 0
      mkdocs.yml
  9. 34 1
      netbox/dcim/api/serializers_/devices.py
  10. 13 1
      netbox/dcim/api/urls.py
  11. 43 0
      netbox/dcim/api/views.py
  12. 9 0
      netbox/dcim/constants.py
  13. 45 0
      netbox/dcim/filtersets.py
  14. 20 0
      netbox/dcim/forms/bulk_edit.py
  15. 10 0
      netbox/dcim/forms/bulk_import.py
  16. 38 1
      netbox/dcim/forms/filtersets.py
  17. 21 0
      netbox/dcim/forms/model_forms.py
  18. 11 0
      netbox/dcim/graphql/filters.py
  19. 3 0
      netbox/dcim/graphql/schema.py
  20. 11 0
      netbox/dcim/graphql/types.py
  21. 77 0
      netbox/dcim/migrations/0253_macblock.py
  22. 229 2
      netbox/dcim/models/devices.py
  23. 30 0
      netbox/dcim/querysets.py
  24. 12 0
      netbox/dcim/search.py
  25. 51 0
      netbox/dcim/tables/devices.py
  26. 2 0
      netbox/dcim/tests/query_counts.json
  27. 127 0
      netbox/dcim/tests/test_api.py
  28. 67 0
      netbox/dcim/tests/test_filtersets.py
  29. 148 0
      netbox/dcim/tests/test_models.py
  30. 4 0
      netbox/dcim/tests/test_tables.py
  31. 81 0
      netbox/dcim/tests/test_views.py
  32. 11 0
      netbox/dcim/ui/panels.py
  33. 2 0
      netbox/dcim/urls.py
  34. 81 0
      netbox/dcim/views.py
  35. 4 1
      netbox/ipam/graphql/filters.py
  36. 2 1
      netbox/ipam/graphql/types.py
  37. 7 1
      netbox/ipam/models/ip.py
  38. 6 0
      netbox/ipam/views.py
  39. 1 0
      netbox/netbox/constants.py
  40. 45 3
      netbox/netbox/forms/bulk_edit.py
  41. 1 0
      netbox/netbox/navigation/menu.py
  42. 79 0
      netbox/netbox/views/generic/bulk_views.py
  43. 13 0
      netbox/templates/generic/bulk_edit.html
  44. 191 1
      netbox/tenancy/tests/test_views.py
  45. 6 0
      netbox/vpn/constants.py
  46. 51 6
      netbox/vpn/filtersets.py
  47. 49 13
      netbox/vpn/forms/bulk_import.py
  48. 7 2
      netbox/vpn/forms/filtersets.py
  49. 18 5
      netbox/vpn/forms/model_forms.py
  50. 3 1
      netbox/vpn/graphql/types.py
  51. 26 0
      netbox/vpn/migrations/0014_l2vpntermination_unique_per_l2vpn.py
  52. 26 13
      netbox/vpn/models/l2vpn.py
  53. 1 1
      netbox/vpn/tests/query_counts.json
  54. 24 5
      netbox/vpn/tests/test_api.py
  55. 26 6
      netbox/vpn/tests/test_filtersets.py
  56. 82 0
      netbox/vpn/tests/test_forms.py
  57. 48 1
      netbox/vpn/tests/test_models.py
  58. 50 6
      netbox/vpn/tests/test_views.py
  59. 18 1
      netbox/vpn/views.py

+ 6 - 0
docs/features/contacts.md

@@ -44,3 +44,9 @@ The following models support the assignment of contacts:
 * virtualization.Cluster
 * virtualization.Cluster
 * virtualization.ClusterGroup
 * virtualization.ClusterGroup
 * virtualization.VirtualMachine
 * virtualization.VirtualMachine
+
+### Bulk Assignment
+
+Contacts can be assigned to or removed from many objects at once using the bulk edit form of any supported object type. When adding contacts, a role (and optionally a priority) must be selected to apply to each new assignment. If a contact is already assigned to an object with the selected role, no duplicate is created; instead, the selected priority (if any) is applied to the existing assignment. Removing a contact deletes all of its assignments to the selected objects, regardless of role. Removals are processed before additions, so a contact's role can be replaced in a single operation.
+
+When importing contact assignments in bulk, contacts are matched by name by default. Where contact names are not unique, use the `contact.id` column header to reference contacts by their numeric ID instead.

+ 2 - 0
docs/features/devices-cabling.md

@@ -91,6 +91,8 @@ One especially nice feature of modules is that templated components can be autom
 
 
 [MAC addresses](../models/dcim/macaddress.md) are modeled as first-class objects in NetBox so that an interface may have multiple MAC addresses assigned to it, with one optionally designated as the interface's primary MAC. This accommodates virtual interfaces and modular hardware where the link-layer address is not necessarily fixed at the factory. MAC addresses can be assigned to both [device interfaces](../models/dcim/interface.md) and [virtual machine interfaces](../models/virtualization/vminterface.md).
 [MAC addresses](../models/dcim/macaddress.md) are modeled as first-class objects in NetBox so that an interface may have multiple MAC addresses assigned to it, with one optionally designated as the interface's primary MAC. This accommodates virtual interfaces and modular hardware where the link-layer address is not necessarily fixed at the factory. MAC addresses can be assigned to both [device interfaces](../models/dcim/interface.md) and [virtual machine interfaces](../models/virtualization/vminterface.md).
 
 
+[MAC address blocks](../models/dcim/macblock.md) represent blocks of MAC addresses, such as organizationally unique identifiers (OUIs). They can be used to track the utilization of a block, to create MAC addresses from the next available address in a block, and to prevent duplicate MAC addresses within a block.
+
 ## Cables
 ## Cables
 
 
 NetBox models cables as connections among certain types of device components and other objects. Each cable can be assigned a type, color, length, and label. NetBox will enforce basic sanity checks to prevent invalid connections. (For example, a network interface cannot be connected to a power outlet.)
 NetBox models cables as connections among certain types of device components and other objects. Each cable can be assigned a type, color, length, and label. NetBox will enforce basic sanity checks to prevent invalid connections. (For example, a network interface cannot be connected to a power outlet.)

+ 1 - 1
docs/features/l2vpn-overlay.md

@@ -2,4 +2,4 @@
 
 
 L2VPN and overlay networks, such as VXLAN and EVPN, can be defined in NetBox and tied to interfaces and VLANs. This allows for easy tracking of overlay assets and their relationships with underlay resources.
 L2VPN and overlay networks, such as VXLAN and EVPN, can be defined in NetBox and tied to interfaces and VLANs. This allows for easy tracking of overlay assets and their relationships with underlay resources.
 
 
-Each L2VPN instance has a type and optional unique identifier. Like VRFs, L2VPNs can also have import and export route targets assigned to them. Terminations can then be created to assign VLANs and/or device and virtual machine interfaces to the overlay.
+Each L2VPN instance has a type and optional unique identifier. Like VRFs, L2VPNs can also have import and export route targets assigned to them. Terminations can then be created to assign VLANs, device and virtual machine interfaces, and/or IP addresses (such as the far-end of a pseudowire) to the overlay.

+ 2 - 0
docs/models/dcim/macaddress.md

@@ -4,6 +4,8 @@ A MAC address object in NetBox represents a single Ethernet link-layer address a
 
 
 Most physical interfaces have only a single MAC address, hard-coded at the factory. However, some interfaces (particularly virtual interfaces and modular hardware) support multiple or reassignable MAC addresses. To accommodate this, NetBox models MAC addresses as first-class objects which may be created, modified, and reassigned independently of any specific interface.
 Most physical interfaces have only a single MAC address, hard-coded at the factory. However, some interfaces (particularly virtual interfaces and modular hardware) support multiple or reassignable MAC addresses. To accommodate this, NetBox models MAC addresses as first-class objects which may be created, modified, and reassigned independently of any specific interface.
 
 
+Blocks of MAC addresses, such as organizationally unique identifiers (OUIs), can be tracked as [MAC address blocks](./macblock.md).
+
 ## Fields
 ## Fields
 
 
 ### MAC Address
 ### MAC Address

+ 33 - 0
docs/models/dcim/macblock.md

@@ -0,0 +1,33 @@
+# MAC Address Blocks
+
+A MAC address block represents a contiguous range of [MAC addresses](./macaddress.md), defined by a prefix (the first address in the block) and a prefix length (the number of leading bits shared by every address in it). This mirrors the blocks assigned by the IEEE: an organizationally unique identifier (OUI, or MA-L block) such as `BC:24:11` is a MAC address block with a prefix length of 24, spanning the MAC addresses `BC:24:11:00:00:00` through `BC:24:11:FF:FF:FF`. The smaller MA-M and MA-S blocks have lengths of 28 and 36 bits, respectively. Blocks can also represent ranges within an assigned block which are set aside for a particular purpose, such as a virtualization cluster.
+
+A MAC address belongs to every MAC address block which contains it: MAC addresses are not explicitly assigned to blocks. The MAC address view shows the most specific block which contains it.
+
+Each MAC address block shows its utilization (the percentage of its MAC addresses which exist in NetBox), and its MAC addresses. A new MAC address can be created from the first available address within the block, using either the UI or the REST API (`/api/dcim/mac-blocks/<id>/available-mac-addresses/`).
+
+## Fields
+
+### Prefix
+
+The first MAC address in the block, for example `BC:24:11:00:00:00`. Any bits beyond the prefix length are cleared when the prefix is saved.
+
+### Prefix Length
+
+The number of leading bits which are shared by all MAC addresses in the block (1 to 48). Defaults to 24, the length of an OUI.
+
+### Name
+
+An optional name for the block, such as the organization to which it is assigned.
+
+### Enforce Unique
+
+If enabled, duplicate MAC addresses are not permitted within this block. Uniqueness cannot be enforced on a block which already contains duplicate MAC addresses.
+
+### Description
+
+An optional human-readable description of the MAC address block.
+
+### Comments
+
+Free-form Markdown-supported notes regarding the MAC address block.

+ 1 - 1
docs/models/vpn/l2vpn.md

@@ -1,6 +1,6 @@
 # L2VPN
 # L2VPN
 
 
-A L2VPN object is NetBox is a representation of a layer 2 bridge technology such as VXLAN, VPLS, or EPL. Each L2VPN can be identified by name as well as by an optional unique identifier (VNI would be an example). Once created, L2VPNs can be terminated to [interfaces](../dcim/interface.md) and [VLANs](../ipam/vlan.md).
+A L2VPN object is NetBox is a representation of a layer 2 bridge technology such as VXLAN, VPLS, or EPL. Each L2VPN can be identified by name as well as by an optional unique identifier (VNI would be an example). Once created, L2VPNs can be terminated to [interfaces](../dcim/interface.md), [VLANs](../ipam/vlan.md), and [IP addresses](../ipam/ipaddress.md).
 
 
 ## Fields
 ## Fields
 
 

+ 5 - 3
docs/models/vpn/l2vpntermination.md

@@ -1,6 +1,6 @@
 # L2VPN Termination
 # L2VPN Termination
 
 
-A L2VPN termination is the attachment of an [L2VPN](./l2vpn.md) to an [interface](../dcim/interface.md) or [VLAN](../ipam/vlan.md). Note that the L2VPNs of the following types may have only two terminations assigned to them:
+A L2VPN termination is the attachment of an [L2VPN](./l2vpn.md) to an [interface](../dcim/interface.md), [VLAN](../ipam/vlan.md), or [IP address](../ipam/ipaddress.md). Note that the L2VPNs of the following types may have only two terminations assigned to them:
 
 
 * VPWS
 * VPWS
 * EPL
 * EPL
@@ -13,6 +13,8 @@ A L2VPN termination is the attachment of an [L2VPN](./l2vpn.md) to an [interface
 
 
 The [L2VPN](./l2vpn.md) instance.
 The [L2VPN](./l2vpn.md) instance.
 
 
-### VLAN or Interface
+### VLAN, Interface, or IP Address
 
 
-The [VLAN](../ipam/vlan.md), [device interface](../dcim/interface.md), or [virtual machine interface](../virtualization/virtualmachine.md) attached to the L2VPN.
+The [VLAN](../ipam/vlan.md), [device interface](../dcim/interface.md), [virtual machine interface](../virtualization/virtualmachine.md), or [IP address](../ipam/ipaddress.md) attached to the L2VPN.
+
+An interface or VLAN can terminate only one L2VPN. An IP address can terminate any number of L2VPNs, but each L2VPN only once. For example, a pseudowire can be terminated to the IP address of its far-end provider edge (PE) device, with the pseudowire ID recorded as the L2VPN's identifier.

+ 1 - 0
mkdocs.yml

@@ -225,6 +225,7 @@ nav:
             - InventoryItemTemplate: 'models/dcim/inventoryitemtemplate.md'
             - InventoryItemTemplate: 'models/dcim/inventoryitemtemplate.md'
             - Location: 'models/dcim/location.md'
             - Location: 'models/dcim/location.md'
             - MACAddress: 'models/dcim/macaddress.md'
             - MACAddress: 'models/dcim/macaddress.md'
+            - MACBlock: 'models/dcim/macblock.md'
             - Manufacturer: 'models/dcim/manufacturer.md'
             - Manufacturer: 'models/dcim/manufacturer.md'
             - Module: 'models/dcim/module.md'
             - Module: 'models/dcim/module.md'
             - ModuleBay: 'models/dcim/modulebay.md'
             - ModuleBay: 'models/dcim/modulebay.md'

+ 34 - 1
netbox/dcim/api/serializers_/devices.py

@@ -8,7 +8,7 @@ from rest_framework import serializers
 
 
 from dcim.choices import *
 from dcim.choices import *
 from dcim.constants import MACADDRESS_ASSIGNMENT_MODELS
 from dcim.constants import MACADDRESS_ASSIGNMENT_MODELS
-from dcim.models import Device, DeviceBay, MACAddress, Module, VirtualDeviceContext
+from dcim.models import Device, DeviceBay, MACAddress, MACBlock, Module, VirtualDeviceContext
 from dcim.utils import get_module_bay_positions, resolve_module_placeholder
 from dcim.utils import get_module_bay_positions, resolve_module_placeholder
 from extras.api.serializers_.configtemplates import ConfigTemplateSerializer
 from extras.api.serializers_.configtemplates import ConfigTemplateSerializer
 from ipam.api.serializers_.ip import IPAddressSerializer
 from ipam.api.serializers_.ip import IPAddressSerializer
@@ -27,8 +27,10 @@ from .sites import LocationSerializer, SiteSerializer
 from .virtualchassis import VirtualChassisSerializer
 from .virtualchassis import VirtualChassisSerializer
 
 
 __all__ = (
 __all__ = (
+    'AvailableMACAddressSerializer',
     'DeviceSerializer',
     'DeviceSerializer',
     'MACAddressSerializer',
     'MACAddressSerializer',
+    'MACBlockSerializer',
     'ModuleSerializer',
     'ModuleSerializer',
     'VirtualDeviceContextSerializer',
     'VirtualDeviceContextSerializer',
 )
 )
@@ -362,3 +364,34 @@ class MACAddressSerializer(PrimaryModelSerializer):
             'last_updated',
             'last_updated',
         ]
         ]
         brief_fields = ('id', 'url', 'display', 'mac_address', 'description')
         brief_fields = ('id', 'url', 'display', 'mac_address', 'description')
+
+
+class MACBlockSerializer(PrimaryModelSerializer):
+    last_address = serializers.CharField(read_only=True)
+    size = serializers.IntegerField(read_only=True)
+    mac_address_count = serializers.IntegerField(read_only=True)
+    utilization = serializers.FloatField(read_only=True)
+
+    class Meta:
+        model = MACBlock
+        fields = [
+            'id', 'url', 'display_url', 'display', 'prefix', 'prefix_length', 'last_address', 'size', 'name',
+            'enforce_unique', 'mac_address_count', 'utilization', 'description', 'owner', 'comments', 'tags',
+            'custom_fields', 'created', 'last_updated',
+        ]
+        brief_fields = ('id', 'url', 'display', 'prefix', 'prefix_length', 'name', 'description')
+        # Preserve the prefix as normalized by MACBlock.clean()
+        model_clean_fields = ('prefix',)
+
+
+class AvailableMACAddressSerializer(serializers.Serializer):
+    """
+    Representation of a MAC address which does not exist in the database.
+    """
+    mac_address = serializers.CharField(read_only=True)
+    description = serializers.CharField(required=False)
+
+    def to_representation(self, instance):
+        return {
+            'mac_address': str(instance),
+        }

+ 13 - 1
netbox/dcim/api/urls.py

@@ -1,3 +1,5 @@
+from django.urls import path
+
 from netbox.api.routers import NetBoxRouter
 from netbox.api.routers import NetBoxRouter
 
 
 from . import views
 from . import views
@@ -65,6 +67,7 @@ router.register('inventory-item-roles', views.InventoryItemRoleViewSet)
 
 
 # Addressing
 # Addressing
 router.register('mac-addresses', views.MACAddressViewSet)
 router.register('mac-addresses', views.MACAddressViewSet)
+router.register('mac-blocks', views.MACBlockViewSet)
 
 
 # Cables
 # Cables
 router.register('cables', views.CableViewSet)
 router.register('cables', views.CableViewSet)
@@ -86,4 +89,13 @@ router.register('cooling-feeds', views.CoolingFeedViewSet)
 router.register('connected-device', views.ConnectedDeviceViewSet, basename='connected-device')
 router.register('connected-device', views.ConnectedDeviceViewSet, basename='connected-device')
 
 
 app_name = 'dcim-api'
 app_name = 'dcim-api'
-urlpatterns = router.urls
+
+urlpatterns = [
+    path(
+        'mac-blocks/<int:pk>/available-mac-addresses/',
+        views.MACBlockAvailableMACAddressesView.as_view(),
+        name='macblock-available-mac-addresses'
+    ),
+]
+
+urlpatterns += router.urls

+ 43 - 0
netbox/dcim/api/views.py

@@ -1,3 +1,5 @@
+from itertools import islice
+
 from django.contrib.contenttypes.prefetch import GenericPrefetch
 from django.contrib.contenttypes.prefetch import GenericPrefetch
 from django.db.models import FETCH_PEERS, Prefetch
 from django.db.models import FETCH_PEERS, Prefetch
 from django.http import Http404, HttpResponse
 from django.http import Http404, HttpResponse
@@ -14,10 +16,12 @@ from dcim.constants import CABLE_TRACE_SVG_DEFAULT_WIDTH
 from dcim.models import *
 from dcim.models import *
 from dcim.svg import CableTraceSVG
 from dcim.svg import CableTraceSVG
 from extras.api.mixins import ConfigContextQuerySetMixin, RenderConfigMixin
 from extras.api.mixins import ConfigContextQuerySetMixin, RenderConfigMixin
+from ipam.api.views import AvailableObjectsView
 from netbox.api.authentication import IsAuthenticatedOrLoginNotRequired
 from netbox.api.authentication import IsAuthenticatedOrLoginNotRequired
 from netbox.api.metadata import ContentTypeMetadata
 from netbox.api.metadata import ContentTypeMetadata
 from netbox.api.pagination import StripCountAnnotationsPaginator
 from netbox.api.pagination import StripCountAnnotationsPaginator
 from netbox.api.viewsets import NetBoxModelViewSet, NetBoxReadOnlyModelViewSet
 from netbox.api.viewsets import NetBoxModelViewSet, NetBoxReadOnlyModelViewSet
+from netbox.config import get_config
 from utilities.api import get_serializer_for_model
 from utilities.api import get_serializer_for_model
 from utilities.query import count_related
 from utilities.query import count_related
 from utilities.query_functions import CollateAsChar
 from utilities.query_functions import CollateAsChar
@@ -603,6 +607,45 @@ class MACAddressViewSet(NetBoxModelViewSet):
     filterset_class = filtersets.MACAddressFilterSet
     filterset_class = filtersets.MACAddressFilterSet
 
 
 
 
+class MACBlockViewSet(NetBoxModelViewSet):
+    queryset = MACBlock.objects.annotate_mac_address_count()
+    serializer_class = serializers.MACBlockSerializer
+    filterset_class = filtersets.MACBlockFilterSet
+
+
+class MACBlockAvailableMACAddressesView(AvailableObjectsView):
+    queryset = MACAddress.objects.all()
+    read_serializer_class = serializers.AvailableMACAddressSerializer
+    write_serializer_class = serializers.AvailableMACAddressSerializer
+    advisory_lock_key = 'available-mac-addresses'
+
+    def get_parent(self, request, pk):
+        return get_object_or_404(MACBlock.objects.restrict(request.user), pk=pk)
+
+    def get_available_objects(self, parent, limit=None):
+        # A block may contain millions of available MAC addresses, so always apply a limit
+        if not limit or limit < 0:
+            limit = get_config().PAGINATE_COUNT
+        return list(islice(parent.iter_available_mac_addresses(), limit))
+
+    def prep_object_data(self, requested_objects, available_objects, parent):
+        for i, request_data in enumerate(requested_objects):
+            request_data['mac_address'] = str(available_objects[i])
+        return requested_objects
+
+    @extend_schema(methods=['get'], responses={200: serializers.AvailableMACAddressSerializer(many=True)})
+    def get(self, request, pk):
+        return super().get(request, pk)
+
+    @extend_schema(
+        methods=['post'],
+        responses={201: serializers.MACAddressSerializer(many=True)},
+        request=serializers.MACAddressSerializer(many=True),
+    )
+    def post(self, request, pk):
+        return super().post(request, pk)
+
+
 #
 #
 # Cables
 # Cables
 #
 #

+ 9 - 0
netbox/dcim/constants.py

@@ -95,6 +95,15 @@ NONCONNECTABLE_IFACE_TYPES = VIRTUAL_IFACE_TYPES + WIRELESS_IFACE_TYPES + [
 ]
 ]
 
 
 
 
+#
+# MAC blocks
+#
+
+MACBLOCK_LENGTH_MIN = 1
+MACBLOCK_LENGTH_MAX = 48
+MACBLOCK_LENGTH_DEFAULT = 24  # An organizationally unique identifier (OUI)
+
+
 #
 #
 # Device components
 # Device components
 #
 #

+ 45 - 0
netbox/dcim/filtersets.py

@@ -79,6 +79,7 @@ __all__ = (
     'InventoryItemTemplateFilterSet',
     'InventoryItemTemplateFilterSet',
     'LocationFilterSet',
     'LocationFilterSet',
     'MACAddressFilterSet',
     'MACAddressFilterSet',
+    'MACBlockFilterSet',
     'ManufacturerFilterSet',
     'ManufacturerFilterSet',
     'ModuleBayFilterSet',
     'ModuleBayFilterSet',
     'ModuleBayTemplateFilterSet',
     'ModuleBayTemplateFilterSet',
@@ -2287,6 +2288,10 @@ class MACAddressFilterSet(PrimaryModelFilterSet):
         method='filter_primary',
         method='filter_primary',
         label=_('Is primary'),
         label=_('Is primary'),
     )
     )
+    mac_block_id = MultiValueBigNumberFilter(
+        method='filter_mac_block',
+        label=_('MAC address block (ID)'),
+    )
 
 
     class Meta:
     class Meta:
         model = MACAddress
         model = MACAddress
@@ -2344,6 +2349,46 @@ class MACAddressFilterSet(PrimaryModelFilterSet):
             return queryset.filter(query)
             return queryset.filter(query)
         return queryset.exclude(query)
         return queryset.exclude(query)
 
 
+    def filter_mac_block(self, queryset, name, value):
+        query = Q()
+        for mac_block in MACBlock.objects.filter(pk__in=value):
+            query |= Q(mac_address__gte=mac_block.first_address, mac_address__lte=mac_block.last_address)
+        if not query:
+            return queryset.none()
+        return queryset.filter(query)
+
+
+@register_filterset
+class MACBlockFilterSet(PrimaryModelFilterSet):
+    prefix = MultiValueMACAddressFilter()
+    contains = django_filters.CharFilter(
+        method='filter_contains',
+        label=_('Contains MAC address'),
+    )
+
+    class Meta:
+        model = MACBlock
+        fields = ('id', 'prefix_length', 'name', 'enforce_unique', 'description')
+
+    def search(self, queryset, name, value):
+        if not value.strip():
+            return queryset
+        qs_filter = (
+            Q(prefix__icontains=value) |
+            Q(name__icontains=value) |
+            Q(description__icontains=value)
+        )
+        return queryset.filter(qs_filter)
+
+    def filter_contains(self, queryset, name, value):
+        if not value.strip():
+            return queryset
+        try:
+            mac_address = netaddr.EUI(value.strip(), version=48)
+        except (AddrFormatError, TypeError, ValueError):
+            return queryset.none()
+        return queryset.filter(prefix__lte=mac_address, _last_address__gte=mac_address)
+
 
 
 class CommonInterfaceFilterSet(django_filters.FilterSet):
 class CommonInterfaceFilterSet(django_filters.FilterSet):
     mode = django_filters.MultipleChoiceFilter(
     mode = django_filters.MultipleChoiceFilter(

+ 20 - 0
netbox/dcim/forms/bulk_edit.py

@@ -63,6 +63,7 @@ __all__ = (
     'InventoryItemTemplateBulkEditForm',
     'InventoryItemTemplateBulkEditForm',
     'LocationBulkEditForm',
     'LocationBulkEditForm',
     'MACAddressBulkEditForm',
     'MACAddressBulkEditForm',
+    'MACBlockBulkEditForm',
     'ManufacturerBulkEditForm',
     'ManufacturerBulkEditForm',
     'ModuleBayBulkEditForm',
     'ModuleBayBulkEditForm',
     'ModuleBayTemplateBulkEditForm',
     'ModuleBayTemplateBulkEditForm',
@@ -2283,3 +2284,22 @@ class MACAddressBulkEditForm(PrimaryModelBulkEditForm):
         FieldSet('description'),
         FieldSet('description'),
     )
     )
     nullable_fields = ('description', 'comments')
     nullable_fields = ('description', 'comments')
+
+
+class MACBlockBulkEditForm(PrimaryModelBulkEditForm):
+    name = forms.CharField(
+        label=_('Name'),
+        max_length=100,
+        required=False
+    )
+    enforce_unique = forms.NullBooleanField(
+        label=_('Enforce unique'),
+        required=False,
+        widget=BulkEditNullBooleanSelect
+    )
+
+    model = MACBlock
+    fieldsets = (
+        FieldSet('name', 'enforce_unique', 'description'),
+    )
+    nullable_fields = ('name', 'description', 'comments')

+ 10 - 0
netbox/dcim/forms/bulk_import.py

@@ -55,6 +55,7 @@ __all__ = (
     'InventoryItemRoleImportForm',
     'InventoryItemRoleImportForm',
     'LocationImportForm',
     'LocationImportForm',
     'MACAddressImportForm',
     'MACAddressImportForm',
+    'MACBlockImportForm',
     'ManufacturerImportForm',
     'ManufacturerImportForm',
     'ModuleBayImportForm',
     'ModuleBayImportForm',
     'ModuleBayTypeImportForm',
     'ModuleBayTypeImportForm',
@@ -1710,6 +1711,15 @@ class MACAddressImportForm(PrimaryModelImportForm):
         return instance
         return instance
 
 
 
 
+class MACBlockImportForm(PrimaryModelImportForm):
+
+    class Meta:
+        model = MACBlock
+        fields = [
+            'prefix', 'prefix_length', 'name', 'enforce_unique', 'description', 'owner', 'comments', 'tags',
+        ]
+
+
 #
 #
 # Cables
 # Cables
 #
 #

+ 38 - 1
netbox/dcim/forms/filtersets.py

@@ -60,6 +60,7 @@ __all__ = (
     'InventoryItemTemplateFilterForm',
     'InventoryItemTemplateFilterForm',
     'LocationFilterForm',
     'LocationFilterForm',
     'MACAddressFilterForm',
     'MACAddressFilterForm',
+    'MACBlockFilterForm',
     'ManufacturerFilterForm',
     'ManufacturerFilterForm',
     'ModuleBayFilterForm',
     'ModuleBayFilterForm',
     'ModuleBayTemplateFilterForm',
     'ModuleBayTemplateFilterForm',
@@ -2452,7 +2453,7 @@ class MACAddressFilterForm(PrimaryModelFilterSetForm):
     model = MACAddress
     model = MACAddress
     fieldsets = (
     fieldsets = (
         FieldSet('q', 'filter_id', 'tag'),
         FieldSet('q', 'filter_id', 'tag'),
-        FieldSet('mac_address', name=_('Attributes')),
+        FieldSet('mac_address', 'mac_block_id', name=_('Attributes')),
         FieldSet('device_id', 'virtual_machine_id', 'assigned', 'primary', name=_('Assignments')),
         FieldSet('device_id', 'virtual_machine_id', 'assigned', 'primary', name=_('Assignments')),
         FieldSet('owner_group_id', 'owner_id', name=_('Ownership')),
         FieldSet('owner_group_id', 'owner_id', name=_('Ownership')),
     )
     )
@@ -2461,6 +2462,11 @@ class MACAddressFilterForm(PrimaryModelFilterSetForm):
         required=False,
         required=False,
         label=_('MAC address'),
         label=_('MAC address'),
     )
     )
+    mac_block_id = DynamicModelMultipleChoiceField(
+        queryset=MACBlock.objects.all(),
+        required=False,
+        label=_('MAC address block'),
+    )
     device_id = DynamicModelMultipleChoiceField(
     device_id = DynamicModelMultipleChoiceField(
         queryset=Device.objects.all(),
         queryset=Device.objects.all(),
         required=False,
         required=False,
@@ -2488,6 +2494,37 @@ class MACAddressFilterForm(PrimaryModelFilterSetForm):
     tag = TagFilterField(model)
     tag = TagFilterField(model)
 
 
 
 
+class MACBlockFilterForm(PrimaryModelFilterSetForm):
+    model = MACBlock
+    fieldsets = (
+        FieldSet('q', 'filter_id', 'tag'),
+        FieldSet('prefix', 'prefix_length', 'contains', 'enforce_unique', name=_('Attributes')),
+        FieldSet('owner_group_id', 'owner_id', name=_('Ownership')),
+    )
+    prefix = forms.CharField(
+        required=False,
+        label=_('Prefix'),
+    )
+    prefix_length = forms.IntegerField(
+        required=False,
+        min_value=MACBLOCK_LENGTH_MIN,
+        max_value=MACBLOCK_LENGTH_MAX,
+        label=_('Prefix length'),
+    )
+    contains = forms.CharField(
+        required=False,
+        label=_('Contains MAC address'),
+    )
+    enforce_unique = forms.NullBooleanField(
+        required=False,
+        label=_('Enforce unique'),
+        widget=forms.Select(
+            choices=BOOLEAN_WITH_BLANK_CHOICES
+        ),
+    )
+    tag = TagFilterField(model)
+
+
 #
 #
 # Connections
 # Connections
 #
 #

+ 21 - 0
netbox/dcim/forms/model_forms.py

@@ -73,6 +73,7 @@ __all__ = (
     'InventoryItemTemplateForm',
     'InventoryItemTemplateForm',
     'LocationForm',
     'LocationForm',
     'MACAddressForm',
     'MACAddressForm',
+    'MACBlockForm',
     'ManufacturerForm',
     'ManufacturerForm',
     'ModuleBayForm',
     'ModuleBayForm',
     'ModuleBayTemplateForm',
     'ModuleBayTemplateForm',
@@ -2603,3 +2604,23 @@ class MACAddressForm(PrimaryModelForm):
             self.instance.assigned_object = self.cleaned_data[selected_objects[0]]
             self.instance.assigned_object = self.cleaned_data[selected_objects[0]]
         else:
         else:
             self.instance.assigned_object = None
             self.instance.assigned_object = None
+
+
+class MACBlockForm(PrimaryModelForm):
+    prefix = forms.CharField(
+        required=True,
+        label=_('Prefix'),
+        help_text=_('The first MAC address in the block (e.g. BC:24:11:00:00:00)')
+    )
+
+    fieldsets = (
+        FieldSet(
+            'prefix', 'prefix_length', 'name', 'enforce_unique', 'description', 'tags', name=_('MAC Address Block')
+        ),
+    )
+
+    class Meta:
+        model = MACBlock
+        fields = [
+            'prefix', 'prefix_length', 'name', 'enforce_unique', 'description', 'owner', 'comments', 'tags',
+        ]

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

@@ -97,6 +97,7 @@ __all__ = (
     'InventoryItemTemplateFilter',
     'InventoryItemTemplateFilter',
     'LocationFilter',
     'LocationFilter',
     'MACAddressFilter',
     'MACAddressFilter',
+    'MACBlockFilter',
     'ManufacturerFilter',
     'ManufacturerFilter',
     'ModuleBayFilter',
     'ModuleBayFilter',
     'ModuleBayTemplateFilter',
     'ModuleBayTemplateFilter',
@@ -538,6 +539,16 @@ class MACAddressFilter(PrimaryModelFilter):
         return ~Q(query)
         return ~Q(query)
 
 
 
 
+@register_filter(models.MACBlock, lookups=True)
+class MACBlockFilter(PrimaryModelFilter):
+    prefix: StrFilterLookup | None = strawberry_django.filter_field()
+    prefix_length: Annotated['IntegerLookup', strawberry.lazy('netbox.graphql.filter_lookups')] | None = (
+        strawberry_django.filter_field()
+    )
+    name: StrFilterLookup | None = strawberry_django.filter_field()
+    enforce_unique: FilterLookup[bool] | None = strawberry_django.filter_field()
+
+
 @register_filter(models.Interface, lookups=True)
 @register_filter(models.Interface, lookups=True)
 class InterfaceFilter(
 class InterfaceFilter(
     ModularComponentFilterMixin,
     ModularComponentFilterMixin,

+ 3 - 0
netbox/dcim/graphql/schema.py

@@ -66,6 +66,9 @@ class DCIMQuery:
     mac_address: MACAddressType = strawberry_django.field()
     mac_address: MACAddressType = strawberry_django.field()
     mac_address_list: list[MACAddressType] = strawberry_django.field()
     mac_address_list: list[MACAddressType] = strawberry_django.field()
 
 
+    mac_block: MACBlockType = strawberry_django.field()
+    mac_block_list: list[MACBlockType] = strawberry_django.field()
+
     interface: InterfaceType = strawberry_django.field()
     interface: InterfaceType = strawberry_django.field()
     interface_list: list[InterfaceType] = strawberry_django.field()
     interface_list: list[InterfaceType] = strawberry_django.field()
 
 

+ 11 - 0
netbox/dcim/graphql/types.py

@@ -74,6 +74,7 @@ __all__ = (
     'InventoryItemType',
     'InventoryItemType',
     'LocationType',
     'LocationType',
     'MACAddressType',
     'MACAddressType',
+    'MACBlockType',
     'ManufacturerType',
     'ManufacturerType',
     'ModularComponentType',
     'ModularComponentType',
     'ModuleBayTemplateType',
     'ModuleBayTemplateType',
@@ -524,6 +525,16 @@ class FrontPortTemplateType(ModularComponentTemplateType):
     mappings: list[Annotated["PortMappingTemplateType", strawberry.lazy('dcim.graphql.types')]]
     mappings: list[Annotated["PortMappingTemplateType", strawberry.lazy('dcim.graphql.types')]]
 
 
 
 
+@register_type(
+    models.MACBlock,
+    exclude=['_last_address'],
+    filters=MACBlockFilter,
+    pagination=True
+)
+class MACBlockType(PrimaryObjectType):
+    prefix: str
+
+
 @register_type(
 @register_type(
     models.MACAddress,
     models.MACAddress,
     exclude=['assigned_object_type', 'assigned_object_id'],
     exclude=['assigned_object_type', 'assigned_object_id'],

+ 77 - 0
netbox/dcim/migrations/0253_macblock.py

@@ -0,0 +1,77 @@
+# Generated by Django 6.1.1 on 2026-11-12 14:04
+
+import django.core.validators
+import django.db.models.deletion
+import taggit.managers
+from django.db import migrations, models
+
+import dcim.fields
+import netbox.models.deletion
+import utilities.json
+
+
+class Migration(migrations.Migration):
+    dependencies = [
+        ('dcim', '0252_generated_fields'),
+        ('extras', '0145_taggeditem_object_id_bigint'),
+        ('users', '0016_default_ordering_indexes'),
+    ]
+
+    operations = [
+        migrations.CreateModel(
+            name='MACBlock',
+            fields=[
+                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False)),
+                ('created', models.DateTimeField(auto_now_add=True, null=True)),
+                ('last_updated', models.DateTimeField(auto_now=True, null=True)),
+                (
+                    'custom_field_data',
+                    models.JSONField(blank=True, default=dict, encoder=utilities.json.CustomFieldJSONEncoder),
+                ),
+                ('description', models.CharField(blank=True, max_length=200)),
+                ('comments', models.TextField(blank=True)),
+                ('prefix', dcim.fields.MACAddressField()),
+                (
+                    'prefix_length',
+                    models.PositiveSmallIntegerField(
+                        default=24,
+                        validators=[
+                            django.core.validators.MinValueValidator(1),
+                            django.core.validators.MaxValueValidator(48),
+                        ],
+                    ),
+                ),
+                ('name', models.CharField(blank=True, max_length=100)),
+                ('enforce_unique', models.BooleanField(default=False)),
+                ('_last_address', dcim.fields.MACAddressField(blank=True, editable=False)),
+                (
+                    'owner',
+                    models.ForeignKey(
+                        blank=True,
+                        null=True,
+                        on_delete=django.db.models.deletion.PROTECT,
+                        related_name='+',
+                        to='users.owner',
+                    ),
+                ),
+                ('tags', taggit.managers.TaggableManager(through='extras.TaggedItem', to='extras.Tag')),
+            ],
+            options={
+                'verbose_name': 'MAC address block',
+                'verbose_name_plural': 'MAC address blocks',
+                'ordering': ('prefix', 'prefix_length', 'pk'),
+                'indexes': [
+                    models.Index(fields=['prefix', 'prefix_length', 'id'], name='dcim_macblo_prefix_221d31_idx'),
+                    models.Index(fields=['prefix', '_last_address'], name='dcim_macblo_prefix_5acee2_idx'),
+                ],
+                'constraints': [
+                    models.UniqueConstraint(
+                        fields=('prefix', 'prefix_length'),
+                        name='dcim_macblock_unique_prefix_prefix_length',
+                        violation_error_message='A MAC address block with this prefix and length already exists.',
+                    )
+                ],
+            },
+            bases=(netbox.models.deletion.DeleteMixin, models.Model),
+        ),
+    ]

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

@@ -9,16 +9,18 @@ from django.core.exceptions import ValidationError
 from django.core.files.storage import default_storage
 from django.core.files.storage import default_storage
 from django.core.validators import MaxValueValidator, MinValueValidator
 from django.core.validators import MaxValueValidator, MinValueValidator
 from django.db import models, router, transaction
 from django.db import models, router, transaction
-from django.db.models import F, ProtectedError, prefetch_related_objects
+from django.db.models import Count, F, ProtectedError, prefetch_related_objects
 from django.db.models.functions import Lower
 from django.db.models.functions import Lower
 from django.db.models.signals import post_save
 from django.db.models.signals import post_save
 from django.urls import reverse
 from django.urls import reverse
 from django.utils.safestring import mark_safe
 from django.utils.safestring import mark_safe
 from django.utils.translation import gettext_lazy as _
 from django.utils.translation import gettext_lazy as _
+from netaddr import EUI, AddrFormatError
 
 
 from dcim.choices import *
 from dcim.choices import *
 from dcim.constants import *
 from dcim.constants import *
-from dcim.fields import MACAddressField
+from dcim.fields import MACAddressField, mac_unix_expanded_uppercase
+from dcim.querysets import MACBlockQuerySet
 from dcim.utils import create_port_mappings, update_interface_bridges, update_interface_parents
 from dcim.utils import create_port_mappings, update_interface_bridges, update_interface_parents
 from extras.models import ConfigContextModel, CustomField
 from extras.models import ConfigContextModel, CustomField
 from extras.querysets import ConfigContextModelQuerySet
 from extras.querysets import ConfigContextModelQuerySet
@@ -42,6 +44,7 @@ __all__ = (
     'DeviceRole',
     'DeviceRole',
     'DeviceType',
     'DeviceType',
     'MACAddress',
     'MACAddress',
+    'MACBlock',
     'Manufacturer',
     'Manufacturer',
     'Platform',
     'Platform',
     'VirtualChassis',
     'VirtualChassis',
@@ -1560,3 +1563,227 @@ class MACAddress(PrimaryModel):
                     raise ValidationError(
                     raise ValidationError(
                         _("Cannot reassign MAC Address while it is designated as the primary MAC for an object")
                         _("Cannot reassign MAC Address while it is designated as the primary MAC for an object")
                     )
                     )
+
+        # Enforce uniqueness within any MAC block which requires it
+        if self.mac_address and (
+            mac_block := self.get_mac_blocks().filter(enforce_unique=True).order_by('-prefix_length').first()
+        ):
+            duplicates = MACAddress.objects.filter(mac_address=self.mac_address).exclude(pk=self.pk)
+            if duplicates.exists():
+                raise ValidationError({
+                    'mac_address': _(
+                        "Duplicate MAC address found within MAC address block {mac_block}, which enforces uniqueness"
+                    ).format(mac_block=mac_block)
+                })
+
+    def get_mac_blocks(self):
+        """
+        Return all MACBlocks which contain this MAC address.
+        """
+        return MACBlock.objects.filter(prefix__lte=self.mac_address, _last_address__gte=self.mac_address)
+
+    @cached_property
+    def mac_block(self):
+        """
+        Return the most specific MACBlock which contains this MAC address (if any).
+        """
+        if not self.mac_address:
+            return None
+        return self.get_mac_blocks().order_by('-prefix_length').first()
+
+
+class MACBlock(PrimaryModel):
+    """
+    A block of MAC addresses which share a common prefix, such as an organizationally unique identifier (OUI).
+    """
+    prefix = MACAddressField(
+        verbose_name=_('prefix'),
+        help_text=_('The first MAC address in the block')
+    )
+    prefix_length = models.PositiveSmallIntegerField(
+        verbose_name=_('prefix length'),
+        default=MACBLOCK_LENGTH_DEFAULT,
+        validators=(
+            MinValueValidator(MACBLOCK_LENGTH_MIN),
+            MaxValueValidator(MACBLOCK_LENGTH_MAX),
+        ),
+        help_text=_('Number of leading bits shared by all MAC addresses in the block (e.g. 24 for an OUI)')
+    )
+    name = models.CharField(
+        verbose_name=_('name'),
+        max_length=100,
+        blank=True,
+        help_text=_('For example, the organization to which the block is assigned')
+    )
+    enforce_unique = models.BooleanField(
+        verbose_name=_('enforce unique'),
+        default=False,
+        help_text=_('Prevent duplicate MAC addresses within this block')
+    )
+
+    # Cached last MAC address in the block, for finding the MAC addresses and blocks it contains
+    _last_address = MACAddressField(
+        blank=True,
+        editable=False
+    )
+
+    objects = MACBlockQuerySet.as_manager()
+
+    clone_fields = ('prefix_length', 'enforce_unique', 'description')
+
+    class Meta:
+        ordering = ('prefix', 'prefix_length', 'pk')
+        indexes = (
+            models.Index(fields=('prefix', 'prefix_length', 'id')),  # Default ordering
+            models.Index(fields=('prefix', '_last_address')),
+        )
+        constraints = (
+            models.UniqueConstraint(
+                fields=('prefix', 'prefix_length'),
+                name='%(app_label)s_%(class)s_unique_prefix_prefix_length',
+                violation_error_message=_("A MAC address block with this prefix and length already exists.")
+            ),
+        )
+        verbose_name = _('MAC address block')
+        verbose_name_plural = _('MAC address blocks')
+
+    def __str__(self):
+        return f'{self.prefix}/{self.prefix_length}'
+
+    def _get_bounds(self):
+        """
+        Return the first and last MAC addresses in the block as integers, or None if the prefix or its length is
+        invalid.
+        """
+        try:
+            prefix = int(EUI(self.prefix, version=48))
+            prefix_length = int(self.prefix_length)
+        except (AddrFormatError, TypeError, ValueError):
+            return None
+        if not MACBLOCK_LENGTH_MIN <= prefix_length <= MACBLOCK_LENGTH_MAX:
+            return None
+        host_mask = (1 << (48 - prefix_length)) - 1
+        return prefix & ~host_mask, prefix | host_mask
+
+    @property
+    def first_address(self):
+        """
+        Return the first MAC address in the block (the prefix with any host bits cleared).
+        """
+        if bounds := self._get_bounds():
+            return EUI(bounds[0], version=48, dialect=mac_unix_expanded_uppercase)
+        return None
+
+    @property
+    def last_address(self):
+        """
+        Return the last MAC address in the block.
+        """
+        if bounds := self._get_bounds():
+            return EUI(bounds[1], version=48, dialect=mac_unix_expanded_uppercase)
+        return None
+
+    @property
+    def size(self):
+        """
+        Return the number of MAC addresses in the block.
+        """
+        return 2 ** (48 - self.prefix_length)
+
+    def clean(self):
+        super().clean()
+
+        # Clear any host bits from the prefix, so that its uniqueness is validated against the value to be saved
+        if (first_address := self.first_address) is not None:
+            self.prefix = first_address
+            self._last_address = self.last_address
+
+        # Uniqueness cannot be enforced if the block already contains duplicate MAC addresses
+        if self.enforce_unique and self.first_address is not None:
+            duplicate = self.get_mac_addresses().values('mac_address').annotate(
+                count=Count('pk')
+            ).filter(count__gt=1).order_by('mac_address').first()
+            if duplicate:
+                raise ValidationError({
+                    'enforce_unique': _(
+                        "Cannot enforce uniqueness: duplicate MAC address {mac_address} exists within this block"
+                    ).format(mac_address=duplicate['mac_address'])
+                })
+
+    def save(self, *args, **kwargs):
+        if self.first_address is None:
+            raise ValueError(f"Invalid MAC address block: {self.prefix}/{self.prefix_length}")
+
+        # Clear any host bits from the prefix, and cache the last address in the block
+        self.prefix = self.first_address
+        self._last_address = self.last_address
+
+        super().save(*args, **kwargs)
+
+    def get_mac_addresses(self):
+        """
+        Return all MACAddresses within this block.
+        """
+        return MACAddress.objects.filter(mac_address__gte=self.first_address, mac_address__lte=self.last_address)
+
+    def get_child_blocks(self):
+        """
+        Return all MACBlocks within this block.
+        """
+        return MACBlock.objects.filter(
+            prefix__gte=self.first_address,
+            _last_address__lte=self.last_address,
+            prefix_length__gt=self.prefix_length,
+        )
+
+    @cached_property
+    def mac_address_count(self):
+        """
+        Return the number of distinct MAC addresses within the block. (May be annotated by
+        MACBlockQuerySet.annotate_mac_address_count().)
+        """
+        return self.get_mac_addresses().order_by().values('mac_address').distinct().count()
+
+    @property
+    def utilization(self):
+        """
+        Return the percentage of MAC addresses within the block which exist in NetBox.
+        """
+        return self.mac_address_count / self.size * 100
+
+    def _iter_occupied(self, batch_size=5000):
+        """
+        Yield the distinct MAC addresses within the block which exist in NetBox as integers, in ascending order.
+        Addresses are fetched in batches, so that stopping early stops reading from the database.
+        """
+        resume = self.first_address
+        while True:
+            mac_addresses = list(
+                MACAddress.objects.filter(mac_address__gte=resume, mac_address__lte=self.last_address)
+                .order_by('mac_address')
+                .values_list('mac_address', flat=True)
+                .distinct()[:batch_size]
+            )
+            for mac_address in mac_addresses:
+                yield int(mac_address)
+            if len(mac_addresses) < batch_size or mac_addresses[-1] == self.last_address:
+                return
+            resume = EUI(int(mac_addresses[-1]) + 1, version=48)
+
+    def iter_available_mac_addresses(self):
+        """
+        Yield the MAC addresses within the block which do not exist in NetBox, in ascending order.
+        """
+        candidate = int(self.first_address)
+        for occupied in self._iter_occupied():
+            for value in range(candidate, occupied):
+                yield EUI(value, version=48, dialect=mac_unix_expanded_uppercase)
+            candidate = occupied + 1
+        for value in range(candidate, int(self.last_address) + 1):
+            yield EUI(value, version=48, dialect=mac_unix_expanded_uppercase)
+
+    def get_first_available_mac_address(self):
+        """
+        Return the first MAC address within the block which does not exist in NetBox (or None).
+        """
+        return next(self.iter_available_mac_addresses(), None)

+ 30 - 0
netbox/dcim/querysets.py

@@ -0,0 +1,30 @@
+from django.db.models import Count, IntegerField, OuterRef, Subquery, Value
+from django.db.models.functions import Coalesce
+
+from utilities.querysets import RestrictedQuerySet
+
+__all__ = (
+    'MACBlockQuerySet',
+)
+
+
+class MACBlockQuerySet(RestrictedQuerySet):
+
+    def annotate_mac_address_count(self):
+        """
+        Annotate the number of distinct MAC addresses within each MACBlock.
+        """
+        from .models import MACAddress
+
+        mac_addresses = MACAddress.objects.filter(
+            mac_address__gte=OuterRef('prefix'),
+            mac_address__lte=OuterRef('_last_address'),
+        ).order_by().annotate(
+            group=Value(1)
+        ).values('group').annotate(
+            count=Count('mac_address', distinct=True)
+        ).values('count')
+
+        return self.annotate(
+            mac_address_count=Coalesce(Subquery(mac_addresses, output_field=IntegerField()), 0)
+        )

+ 12 - 0
netbox/dcim/search.py

@@ -167,6 +167,18 @@ class MACAddressIndex(SearchIndex):
     display_attrs = ('assigned_object', 'description')
     display_attrs = ('assigned_object', 'description')
 
 
 
 
+@register_search
+class MACBlockIndex(SearchIndex):
+    model = models.MACBlock
+    fields = (
+        ('prefix', 100),
+        ('name', 100),
+        ('description', 500),
+        ('comments', 5000),
+    )
+    display_attrs = ('name', 'description')
+
+
 @register_search
 @register_search
 class InterfaceIndex(SearchIndex):
 class InterfaceIndex(SearchIndex):
     model = models.Interface
     model = models.Interface

+ 51 - 0
netbox/dcim/tables/devices.py

@@ -38,6 +38,7 @@ __all__ = (
     'InventoryItemRoleTable',
     'InventoryItemRoleTable',
     'InventoryItemTable',
     'InventoryItemTable',
     'MACAddressTable',
     'MACAddressTable',
+    'MACBlockTable',
     'ModuleBayTable',
     'ModuleBayTable',
     'PlatformTable',
     'PlatformTable',
     'PowerOutletTable',
     'PowerOutletTable',
@@ -1330,3 +1331,53 @@ class MACAddressTable(PrimaryModelTable):
         default_columns = (
         default_columns = (
             'pk', 'mac_address', 'is_primary', 'assigned_object_parent', 'assigned_object', 'description',
             'pk', 'mac_address', 'is_primary', 'assigned_object_parent', 'assigned_object', 'description',
         )
         )
+
+
+class MACBlockTable(PrimaryModelTable):
+    prefix = tables.Column(
+        verbose_name=_('Prefix'),
+        linkify=True
+    )
+    prefix_length = tables.Column(
+        verbose_name=_('Length')
+    )
+    name = tables.Column(
+        verbose_name=_('Name')
+    )
+    size = tables.Column(
+        verbose_name=_('Size'),
+        orderable=False
+    )
+    mac_address_count = columns.LinkedCountColumn(
+        viewname='dcim:macaddress_list',
+        url_params={'mac_block_id': 'pk'},
+        verbose_name=_('MAC Addresses'),
+        orderable=False
+    )
+    utilization = columns.UtilizationColumn(
+        verbose_name=_('Utilization'),
+        orderable=False
+    )
+    enforce_unique = columns.BooleanColumn(
+        verbose_name=_('Enforce Unique')
+    )
+    tags = columns.TagColumn(
+        url_name='dcim:macblock_list'
+    )
+
+    def render_prefix(self, record):
+        # Include the prefix length, to distinguish blocks which start at the same address
+        return str(record)
+
+    def value_prefix(self, record):
+        return str(record.prefix)
+
+    class Meta(PrimaryModelTable.Meta):
+        model = models.MACBlock
+        fields = (
+            'pk', 'id', 'prefix', 'prefix_length', 'name', 'size', 'mac_address_count', 'utilization',
+            'enforce_unique', 'description', 'comments', 'tags', 'created', 'last_updated',
+        )
+        default_columns = (
+            'pk', 'prefix', 'name', 'mac_address_count', 'utilization', 'enforce_unique', 'description',
+        )

+ 2 - 0
netbox/dcim/tests/query_counts.json

@@ -46,6 +46,8 @@
   "location:list_objects_with_permission": 18,
   "location:list_objects_with_permission": 18,
   "macaddress:api_list_objects": 16,
   "macaddress:api_list_objects": 16,
   "macaddress:list_objects_with_permission": 20,
   "macaddress:list_objects_with_permission": 20,
+  "macblock:api_list_objects": 12,
+  "macblock:list_objects_with_permission": 16,
   "manufacturer:api_list_objects": 12,
   "manufacturer:api_list_objects": 12,
   "manufacturer:list_objects_with_permission": 16,
   "manufacturer:list_objects_with_permission": 16,
   "module:api_list_objects": 19,
   "module:api_list_objects": 19,

+ 127 - 0
netbox/dcim/tests/test_api.py

@@ -32,6 +32,7 @@ from extras.models import ConfigContext, ConfigTemplate, ExportTemplate, Tag
 from ipam.choices import FHRPGroupProtocolChoices, VLANQinQRoleChoices
 from ipam.choices import FHRPGroupProtocolChoices, VLANQinQRoleChoices
 from ipam.models import ASN, RIR, VLAN, VRF, FHRPGroup, FHRPGroupAssignment, IPAddress
 from ipam.models import ASN, RIR, VLAN, VRF, FHRPGroup, FHRPGroupAssignment, IPAddress
 from netbox.api.serializers import GenericObjectSerializer
 from netbox.api.serializers import GenericObjectSerializer
+from netbox.config import get_config
 from tenancy.models import Tenant
 from tenancy.models import Tenant
 from users.constants import TOKEN_PREFIX
 from users.constants import TOKEN_PREFIX
 from users.models import ObjectPermission, Token, User
 from users.models import ObjectPermission, Token, User
@@ -7438,3 +7439,129 @@ class MACAddressTestCase(APIViewTestCases.APIViewTestCase):
         url = reverse('dcim-api:macaddress-detail', kwargs={'pk': non_primary_mac.pk})
         url = reverse('dcim-api:macaddress-detail', kwargs={'pk': non_primary_mac.pk})
         response = self.client.get(url, **self.header)
         response = self.client.get(url, **self.header)
         self.assertFalse(response.data['is_primary'])
         self.assertFalse(response.data['is_primary'])
+
+
+class MACBlockTestCase(APIViewTestCases.APIViewTestCase):
+    model = MACBlock
+    graphql_base_name = 'mac_block'
+    brief_fields = ['description', 'display', 'id', 'name', 'prefix', 'prefix_length', 'url']
+    bulk_update_data = {
+        'description': 'New description',
+    }
+    bulk_update_invalid_data = {
+        'prefix_length': 99,
+    }
+
+    @classmethod
+    def setUpTestData(cls):
+        MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=24, name='Block 1')
+        MACBlock.objects.create(prefix='BC:24:12:00:00:00', prefix_length=24, name='Block 2')
+        MACBlock.objects.create(prefix='BC:24:13:00:00:00', prefix_length=24, name='Block 3')
+
+        cls.create_data = [
+            {
+                'prefix': 'BC:24:14:00:00:00',
+                'prefix_length': 24,
+                'name': 'Block 4',
+            },
+            {
+                'prefix': 'BC:24:14:50:00:00',
+                'prefix_length': 28,
+                'enforce_unique': True,
+            },
+            {
+                'prefix': 'BC:24:15:00:00:00',
+            },
+        ]
+
+    def test_read_only_fields(self):
+        self.add_permissions('dcim.view_macblock')
+        mac_block = MACBlock.objects.create(prefix='BC:24:16:00:00:00', prefix_length=46)
+        MACAddress.objects.bulk_create((
+            MACAddress(mac_address='BC:24:16:00:00:01'),
+            MACAddress(mac_address='BC:24:16:00:00:01'),
+            MACAddress(mac_address='BC:24:16:00:00:02'),
+        ))
+        response = self.client.get(self._get_detail_url(mac_block), **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        self.assertEqual(response.data['last_address'], 'BC:24:16:00:00:03')
+        self.assertEqual(response.data['size'], 4)
+        self.assertEqual(response.data['mac_address_count'], 2)
+        self.assertEqual(response.data['utilization'], 50)
+
+    def test_create_normalizes_prefix(self):
+        self.add_permissions('dcim.add_macblock')
+        data = {'prefix': 'BC:24:16:AA:BB:CC', 'prefix_length': 24}
+        response = self.client.post(self._get_list_url(), data, format='json', **self.header)
+        self.assertHttpStatus(response, status.HTTP_201_CREATED)
+        self.assertEqual(response.data['prefix'], 'BC:24:16:00:00:00')
+
+        # A block whose host bits differ from an existing block is a duplicate
+        data = {'prefix': 'BC:24:11:AA:BB:CC', 'prefix_length': 24}
+        response = self.client.post(self._get_list_url(), data, format='json', **self.header)
+        self.assertHttpStatus(response, status.HTTP_400_BAD_REQUEST)
+
+    def test_list_available_mac_addresses(self):
+        mac_block = MACBlock.objects.create(prefix='BC:24:16:00:00:00', prefix_length=45)
+        MACAddress.objects.create(mac_address='BC:24:16:00:00:01')
+        url = reverse('dcim-api:macblock-available-mac-addresses', kwargs={'pk': mac_block.pk})
+        self.add_permissions('dcim.view_macblock', 'dcim.view_macaddress')
+
+        response = self.client.get(url, **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        self.assertEqual(
+            [mac['mac_address'] for mac in response.data],
+            ['BC:24:16:00:00:00', 'BC:24:16:00:00:02', 'BC:24:16:00:00:03', 'BC:24:16:00:00:04',
+             'BC:24:16:00:00:05', 'BC:24:16:00:00:06', 'BC:24:16:00:00:07']
+        )
+
+        # The number of results is limited
+        response = self.client.get(url, {'limit': 2}, **self.header)
+        self.assertEqual(len(response.data), 2)
+
+        # An invalid limit falls back to the default
+        response = self.client.get(url, {'limit': -1}, **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        self.assertEqual(len(response.data), 7)
+
+        # A large block returns a single page of results
+        mac_block = MACBlock.objects.get(name='Block 1')
+        url = reverse('dcim-api:macblock-available-mac-addresses', kwargs={'pk': mac_block.pk})
+        response = self.client.get(url, **self.header)
+        self.assertEqual(len(response.data), get_config().PAGINATE_COUNT)
+
+    def test_create_single_available_mac_address(self):
+        mac_block = MACBlock.objects.create(prefix='BC:24:16:00:00:00', prefix_length=47)
+        url = reverse('dcim-api:macblock-available-mac-addresses', kwargs={'pk': mac_block.pk})
+        self.add_permissions('dcim.view_macblock', 'dcim.add_macaddress')
+
+        # Create both available MAC addresses with individual requests
+        for i in range(2):
+            data = {'description': f'MAC address {i}'}
+            response = self.client.post(url, data, format='json', **self.header)
+            self.assertHttpStatus(response, status.HTTP_201_CREATED)
+            self.assertEqual(response.data['mac_address'], f'BC:24:16:00:00:0{i}')
+            self.assertEqual(response.data['description'], data['description'])
+
+        # Try to create one more MAC address
+        response = self.client.post(url, {}, format='json', **self.header)
+        self.assertHttpStatus(response, status.HTTP_409_CONFLICT)
+        self.assertIn('detail', response.data)
+
+    def test_create_multiple_available_mac_addresses(self):
+        mac_block = MACBlock.objects.create(prefix='BC:24:16:00:00:00', prefix_length=46)
+        url = reverse('dcim-api:macblock-available-mac-addresses', kwargs={'pk': mac_block.pk})
+        self.add_permissions('dcim.view_macblock', 'dcim.add_macaddress')
+
+        # Try to create five MAC addresses (only four are available)
+        data = [{'description': f'MAC address {i}'} for i in range(5)]
+        response = self.client.post(url, data, format='json', **self.header)
+        self.assertHttpStatus(response, status.HTTP_409_CONFLICT)
+
+        # Create all four available MAC addresses in a single request
+        response = self.client.post(url, data[:4], format='json', **self.header)
+        self.assertHttpStatus(response, status.HTTP_201_CREATED)
+        self.assertEqual(
+            [mac['mac_address'] for mac in response.data],
+            ['BC:24:16:00:00:00', 'BC:24:16:00:00:01', 'BC:24:16:00:00:02', 'BC:24:16:00:00:03']
+        )

+ 67 - 0
netbox/dcim/tests/test_filtersets.py

@@ -9170,3 +9170,70 @@ class MACAddressTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 6)
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 6)
         params = {'primary': False}
         params = {'primary': False}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 3)
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 3)
+
+    def test_mac_block(self):
+        mac_blocks = (
+            MACBlock.objects.create(prefix='00:00:00:01:00:00', prefix_length=32),
+            MACBlock.objects.create(prefix='00:00:00:03:00:00', prefix_length=32),
+        )
+        params = {'mac_block_id': [mac_blocks[0].pk]}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+        params = {'mac_block_id': [mac_blocks[0].pk, mac_blocks[1].pk]}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 3)
+
+
+class MACBlockTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
+    queryset = MACBlock.objects.all()
+    filterset = MACBlockFilterSet
+    ignore_fields = ('_last_address',)
+
+    @classmethod
+    def setUpTestData(cls):
+        MACBlock.objects.create(
+            prefix='BC:24:11:00:00:00', prefix_length=24, name='Block 1', enforce_unique=True,
+            description='foobar1'
+        )
+        MACBlock.objects.create(
+            prefix='BC:24:11:50:00:00', prefix_length=28, name='Block 2', description='foobar2'
+        )
+        MACBlock.objects.create(
+            prefix='BC:24:12:00:00:00', prefix_length=36, name='Block 3', description='foobar3'
+        )
+
+    def test_q(self):
+        params = {'q': 'Block 1'}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+        params = {'q': 'BC:24:11'}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+
+    def test_prefix(self):
+        params = {'prefix': ['BC:24:11:00:00:00', 'bc-24-12-00-00-00']}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+
+    def test_prefix_length(self):
+        params = {'prefix_length': [24, 28]}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+
+    def test_name(self):
+        params = {'name': ['Block 1', 'Block 2']}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+
+    def test_enforce_unique(self):
+        params = {'enforce_unique': True}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+        params = {'enforce_unique': False}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+
+    def test_description(self):
+        params = {'description': ['foobar1', 'foobar2']}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+
+    def test_contains(self):
+        params = {'contains': 'BC:24:11:51:00:00'}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+        params = {'contains': 'BC:24:11:61:00:00'}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+        params = {'contains': 'BC:24:13:00:00:00'}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 0)
+        params = {'contains': 'invalid'}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 0)

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

@@ -11,6 +11,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 netaddr import EUI
 
 
 from circuits.models import *
 from circuits.models import *
 from core.choices import ObjectChangeActionChoices
 from core.choices import ObjectChangeActionChoices
@@ -154,6 +155,153 @@ class WebMercatorTestCase(TestCase):
         self.assertEqual(site.mercator_y, -20037508.34)
         self.assertEqual(site.mercator_y, -20037508.34)
 
 
 
 
+class MACBlockTestCase(TestCase):
+
+    def test_prefix_normalized(self):
+        mac_block = MACBlock.objects.create(prefix='BC:24:11:12:34:56', prefix_length=24)
+        mac_block.refresh_from_db()
+        self.assertEqual(str(mac_block.prefix), 'BC:24:11:00:00:00')
+        self.assertEqual(str(mac_block.last_address), 'BC:24:11:FF:FF:FF')
+        self.assertEqual(str(mac_block._last_address), 'BC:24:11:FF:FF:FF')
+        self.assertEqual(str(mac_block), 'BC:24:11:00:00:00/24')
+
+    def test_invalid_prefix(self):
+        for prefix, prefix_length in (('invalid', 24), ('BC:24:11:00:00:00', 49), ('BC:24:11:00:00:00', 'x')):
+            mac_block = MACBlock(prefix=prefix, prefix_length=prefix_length, enforce_unique=True)
+            self.assertIsNone(mac_block.first_address)
+            with self.assertRaises(ValidationError):
+                mac_block.full_clean()
+
+    def test_duplicate_prefix_with_host_bits(self):
+        MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=24)
+        mac_block = MACBlock(prefix='BC:24:11:AA:BB:CC', prefix_length=24)
+        with self.assertRaises(ValidationError):
+            mac_block.full_clean()
+
+    def test_save_invalid_prefix(self):
+        with self.assertRaisesMessage(ValueError, 'Invalid MAC address block'):
+            MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=0)
+
+    def test_size(self):
+        self.assertEqual(MACBlock(prefix='BC:24:11:00:00:00', prefix_length=24).size, 2 ** 24)
+        self.assertEqual(MACBlock(prefix='BC:24:11:50:00:00', prefix_length=28).size, 2 ** 20)
+        self.assertEqual(MACBlock(prefix='BC:24:11:00:00:01', prefix_length=48).size, 1)
+
+    def test_duplicate_prefix(self):
+        MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=24)
+        mac_block = MACBlock(prefix='BC:24:11:00:00:00', prefix_length=24)
+        with self.assertRaises(ValidationError):
+            mac_block.full_clean()
+        # A block of a different length may share the same first address
+        MACBlock(prefix='BC:24:11:00:00:00', prefix_length=28).full_clean()
+
+    def test_get_mac_addresses(self):
+        mac_block = MACBlock.objects.create(prefix='BC:24:11:50:00:00', prefix_length=28)
+        MACAddress.objects.bulk_create((
+            MACAddress(mac_address='BC:24:11:4F:FF:FF'),
+            MACAddress(mac_address='BC:24:11:50:00:00'),
+            MACAddress(mac_address='BC:24:11:5F:FF:FF'),
+            MACAddress(mac_address='BC:24:11:60:00:00'),
+        ))
+        self.assertEqual(
+            sorted(str(mac.mac_address) for mac in mac_block.get_mac_addresses()),
+            ['BC:24:11:50:00:00', 'BC:24:11:5F:FF:FF']
+        )
+
+    def test_get_child_blocks(self):
+        mac_blocks = (
+            MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=24),
+            MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=28),
+            MACBlock.objects.create(prefix='BC:24:11:F0:00:00', prefix_length=28),
+            MACBlock.objects.create(prefix='BC:24:12:00:00:00', prefix_length=28),
+        )
+        self.assertEqual(list(mac_blocks[0].get_child_blocks()), [mac_blocks[1], mac_blocks[2]])
+        self.assertEqual(list(mac_blocks[1].get_child_blocks()), [])
+
+    def test_mac_address_mac_block(self):
+        mac_blocks = (
+            MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=24),
+            MACBlock.objects.create(prefix='BC:24:11:50:00:00', prefix_length=28),
+        )
+        self.assertEqual(MACAddress(mac_address='BC:24:11:51:00:00').mac_block, mac_blocks[1])
+        self.assertEqual(MACAddress(mac_address='BC:24:11:61:00:00').mac_block, mac_blocks[0])
+        self.assertIsNone(MACAddress(mac_address='BC:24:12:00:00:00').mac_block)
+
+    def test_available_mac_addresses(self):
+        mac_block = MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=45)
+        self.assertEqual(str(mac_block.get_first_available_mac_address()), 'BC:24:11:00:00:00')
+
+        MACAddress.objects.bulk_create((
+            MACAddress(mac_address='BC:24:11:00:00:00'),
+            MACAddress(mac_address='BC:24:11:00:00:01'),
+            MACAddress(mac_address='BC:24:11:00:00:01'),  # Duplicate
+            MACAddress(mac_address='BC:24:11:00:00:03'),
+            MACAddress(mac_address='BC:24:11:00:00:07'),
+            MACAddress(mac_address='BC:24:11:00:00:08'),  # Outside the block
+        ))
+        self.assertEqual(str(mac_block.get_first_available_mac_address()), 'BC:24:11:00:00:02')
+        self.assertEqual(
+            [str(mac) for mac in mac_block.iter_available_mac_addresses()],
+            ['BC:24:11:00:00:02', 'BC:24:11:00:00:04', 'BC:24:11:00:00:05', 'BC:24:11:00:00:06']
+        )
+
+        # Fetching occupied addresses in batches finds the same gaps
+        self.assertEqual(
+            list(mac_block._iter_occupied(batch_size=2)),
+            [int(EUI(mac)) for mac in ('BC:24:11:00:00:00', 'BC:24:11:00:00:01', 'BC:24:11:00:00:03',
+                                       'BC:24:11:00:00:07')]
+        )
+
+    def test_no_available_mac_addresses(self):
+        mac_block = MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=47)
+        MACAddress.objects.bulk_create((
+            MACAddress(mac_address='BC:24:11:00:00:00'),
+            MACAddress(mac_address='BC:24:11:00:00:01'),
+        ))
+        self.assertIsNone(mac_block.get_first_available_mac_address())
+        self.assertEqual(mac_block.utilization, 100)
+
+    def test_utilization(self):
+        mac_block = MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=46)
+        MACAddress.objects.bulk_create((
+            MACAddress(mac_address='BC:24:11:00:00:00'),
+            MACAddress(mac_address='BC:24:11:00:00:00'),  # Duplicate
+            MACAddress(mac_address='BC:24:11:00:00:02'),
+        ))
+        self.assertEqual(mac_block.utilization, 50)
+        annotated = MACBlock.objects.annotate_mac_address_count().get(pk=mac_block.pk)
+        self.assertEqual(annotated.mac_address_count, 2)
+        self.assertEqual(annotated.utilization, 50)
+
+    def test_enforce_unique(self):
+        MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=24, enforce_unique=True)
+        MACAddress.objects.create(mac_address='BC:24:11:00:00:01')
+        MACAddress.objects.create(mac_address='BC:24:12:00:00:01')
+
+        # A duplicate within the block is rejected
+        with self.assertRaisesMessage(ValidationError, 'BC:24:11:00:00:00/24'):
+            MACAddress(mac_address='BC:24:11:00:00:01').full_clean()
+
+        # A duplicate Outside the block is permitted
+        MACAddress(mac_address='BC:24:12:00:00:01').full_clean()
+
+        # Saving an existing MAC address does not count it as its own duplicate
+        MACAddress.objects.get(mac_address='BC:24:11:00:00:01').full_clean()
+
+    def test_enforce_unique_with_duplicates(self):
+        MACAddress.objects.bulk_create((
+            MACAddress(mac_address='BC:24:11:00:00:01'),
+            MACAddress(mac_address='BC:24:11:00:00:01'),
+        ))
+        mac_block = MACBlock(prefix='BC:24:11:00:00:00', prefix_length=24, enforce_unique=True)
+        with self.assertRaisesMessage(ValidationError, 'BC:24:11:00:00:01'):
+            mac_block.full_clean()
+
+        # Uniqueness is not enforced by default
+        mac_block.enforce_unique = False
+        mac_block.full_clean()
+
+
 class LocationTestCase(TestCase):
 class LocationTestCase(TestCase):
 
 
     def test_change_location_site(self):
     def test_change_location_site(self):

+ 4 - 0
netbox/dcim/tests/test_tables.py

@@ -334,3 +334,7 @@ class VirtualDeviceContextTableTestCase(TableTestCases.StandardTableTestCase):
 
 
 class MACAddressTableTestCase(TableTestCases.StandardTableTestCase):
 class MACAddressTableTestCase(TableTestCases.StandardTableTestCase):
     table = MACAddressTable
     table = MACAddressTable
+
+
+class MACBlockTableTestCase(TableTestCases.StandardTableTestCase):
+    table = MACBlockTable

+ 81 - 0
netbox/dcim/tests/test_views.py

@@ -6971,3 +6971,84 @@ class MACAddressTestCase(ViewTestCases.PrimaryObjectViewTestCase):
         self.assertHttpStatus(response, 200)
         self.assertHttpStatus(response, 200)
         self.assertIn(b'quick-add-object', response.content)
         self.assertIn(b'quick-add-object', response.content)
         self.assertEqual(initial_count + 1, self._get_queryset().count())
         self.assertEqual(initial_count + 1, self._get_queryset().count())
+
+    def test_mac_blocks_panel(self):
+        """
+        The MAC address page lists the MAC blocks containing it, only if the user can view MAC blocks.
+        """
+        MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=24, name='Block 1')
+        mac_address = MACAddress.objects.create(mac_address='BC:24:11:00:00:01')
+        panel_url = 'contains=BC%3A24%3A11%3A00%3A00%3A01'
+
+        self.add_permissions('dcim.view_macaddress')
+        response = self.client.get(mac_address.get_absolute_url())
+        self.assertHttpStatus(response, 200)
+        self.assertNotContains(response, panel_url)
+
+        self.add_permissions('dcim.view_macblock')
+        response = self.client.get(mac_address.get_absolute_url())
+        self.assertHttpStatus(response, 200)
+        self.assertContains(response, panel_url)
+
+
+class MACBlockTestCase(ViewTestCases.PrimaryObjectViewTestCase):
+    model = MACBlock
+
+    @classmethod
+    def setUpTestData(cls):
+        mac_blocks = (
+            MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=24, name='Block 1'),
+            MACBlock.objects.create(prefix='BC:24:12:00:00:00', prefix_length=24, name='Block 2'),
+            MACBlock.objects.create(prefix='BC:24:13:00:00:00', prefix_length=24, name='Block 3'),
+        )
+
+        tags = create_tags('Alpha', 'Bravo', 'Charlie')
+
+        cls.form_data = {
+            'prefix': EUI('BC:24:14:50:00:00'),
+            'prefix_length': 28,
+            'name': 'Block X',
+            'enforce_unique': True,
+            'description': 'New MAC block',
+            'tags': [t.pk for t in tags],
+        }
+
+        cls.csv_data = (
+            "prefix,prefix_length,name",
+            "BC:24:15:00:00:00,24,Block 4",
+            "BC:24:16:00:00:00,28,Block 5",
+            "BC:24:17:00:00:00,36,Block 6",
+        )
+
+        cls.csv_update_data = (
+            "id,name,enforce_unique",
+            f"{mac_blocks[0].pk},Block 7,true",
+            f"{mac_blocks[1].pk},Block 8,true",
+            f"{mac_blocks[2].pk},Block 9,false",
+        )
+
+        cls.bulk_edit_data = {
+            'name': 'New name',
+            'enforce_unique': True,
+            'description': 'New description',
+        }
+
+    def test_create_duplicate_prefix_with_host_bits(self):
+        self.add_permissions('dcim.add_macblock')
+        response = self.client.post(
+            reverse('dcim:macblock_add'), {'prefix': 'BC:24:11:AA:BB:CC', 'prefix_length': 24}
+        )
+        self.assertHttpStatus(response, 200)
+        self.assertEqual(MACBlock.objects.filter(prefix='BC:24:11:00:00:00', prefix_length=24).count(), 1)
+
+    def test_mac_addresses_panel(self):
+        """
+        The MAC block page offers to add the first available MAC address within the block.
+        """
+        self.add_permissions('dcim.view_macblock', 'dcim.view_macaddress', 'dcim.add_macaddress')
+        mac_block = MACBlock.objects.get(name='Block 1')
+        MACAddress.objects.create(mac_address='BC:24:11:00:00:00')
+
+        response = self.client.get(mac_block.get_absolute_url())
+        self.assertHttpStatus(response, 200)
+        self.assertContains(response, 'mac_address=BC%3A24%3A11%3A00%3A00%3A01')

+ 11 - 0
netbox/dcim/ui/panels.py

@@ -492,6 +492,17 @@ class MACAddressPanel(panels.ObjectAttributesPanel):
     is_primary = attrs.BooleanAttr('is_primary', label=_('Primary for interface'))
     is_primary = attrs.BooleanAttr('is_primary', label=_('Primary for interface'))
 
 
 
 
+class MACBlockPanel(panels.ObjectAttributesPanel):
+    prefix = attrs.TextAttr('prefix', label=_('Prefix'), style='font-monospace', copy_button=True)
+    prefix_length = attrs.NumericAttr('prefix_length', label=_('Prefix length'))
+    name = attrs.TextAttr('name')
+    last_address = attrs.TextAttr('last_address', label=_('Last address'), style='font-monospace')
+    size = attrs.NumericAttr('size')
+    utilization = attrs.UtilizationAttr('utilization')
+    enforce_unique = attrs.BooleanAttr('enforce_unique', label=_('Enforce unique'))
+    description = attrs.TextAttr('description')
+
+
 class ConnectionPanel(panels.ObjectPanel):
 class ConnectionPanel(panels.ObjectPanel):
     """
     """
     A panel which displays connection information for a cabled object.
     A panel which displays connection information for a cabled object.

+ 2 - 0
netbox/dcim/urls.py

@@ -208,5 +208,7 @@ urlpatterns = [
 
 
     path('mac-addresses/', include(get_model_urls('dcim', 'macaddress', detail=False))),
     path('mac-addresses/', include(get_model_urls('dcim', 'macaddress', detail=False))),
     path('mac-addresses/<int:pk>/', include(get_model_urls('dcim', 'macaddress'))),
     path('mac-addresses/<int:pk>/', include(get_model_urls('dcim', 'macaddress'))),
+    path('mac-blocks/', include(get_model_urls('dcim', 'macblock', detail=False))),
+    path('mac-blocks/<int:pk>/', include(get_model_urls('dcim', 'macblock'))),
 
 
 ]
 ]

+ 81 - 0
netbox/dcim/views.py

@@ -5872,6 +5872,11 @@ class MACAddressView(generic.ObjectView):
         ],
         ],
         right_panels=[
         right_panels=[
             CommentsPanel(),
             CommentsPanel(),
+            ObjectsTablePanel(
+                model='dcim.MACBlock',
+                title=_('MAC Address Blocks'),
+                filters={'contains': lambda ctx: str(ctx['object'].mac_address)},
+            ),
         ],
         ],
     )
     )
 
 
@@ -5949,3 +5954,79 @@ class MACAddressBulkDeleteView(generic.BulkDeleteView):
     queryset = MACAddress.objects.all()
     queryset = MACAddress.objects.all()
     filterset = filtersets.MACAddressFilterSet
     filterset = filtersets.MACAddressFilterSet
     table = tables.MACAddressTable
     table = tables.MACAddressTable
+
+
+#
+# MAC address blocks
+#
+
+@register_model_view(MACBlock, 'list', path='', detail=False)
+class MACBlockListView(generic.ObjectListView):
+    queryset = MACBlock.objects.annotate_mac_address_count()
+    filterset = filtersets.MACBlockFilterSet
+    filterset_form = forms.MACBlockFilterForm
+    table = tables.MACBlockTable
+    actions = (AddObject, BulkImport, BulkExport, BulkEdit, BulkDelete)
+
+
+@register_model_view(MACBlock)
+class MACBlockView(generic.ObjectView):
+    queryset = MACBlock.objects.all()
+    template_name = 'generic/object.html'
+    layout = layout.SimpleLayout(
+        left_panels=[
+            panels.MACBlockPanel(),
+            TagsPanel(),
+            CustomFieldsPanel(),
+        ],
+        right_panels=[
+            CommentsPanel(),
+        ],
+        bottom_panels=[
+            ObjectsTablePanel(
+                model='dcim.MACAddress',
+                title=_('MAC Addresses'),
+                filters={'mac_block_id': lambda ctx: ctx['object'].pk},
+                actions=[
+                    actions.AddObject(
+                        'dcim.MACAddress',
+                        label=_('Add Next Available'),
+                        url_params={'mac_address': lambda ctx: ctx['object'].get_first_available_mac_address()},
+                    ),
+                ],
+            ),
+        ],
+    )
+
+
+@register_model_view(MACBlock, 'add', detail=False)
+@register_model_view(MACBlock, 'edit')
+class MACBlockEditView(generic.ObjectEditView):
+    queryset = MACBlock.objects.all()
+    form = forms.MACBlockForm
+
+
+@register_model_view(MACBlock, 'delete')
+class MACBlockDeleteView(generic.ObjectDeleteView):
+    queryset = MACBlock.objects.all()
+
+
+@register_model_view(MACBlock, 'bulk_import', path='import', detail=False)
+class MACBlockBulkImportView(generic.BulkImportView):
+    queryset = MACBlock.objects.all()
+    model_form = forms.MACBlockImportForm
+
+
+@register_model_view(MACBlock, 'bulk_edit', path='edit', detail=False)
+class MACBlockBulkEditView(generic.BulkEditView):
+    queryset = MACBlock.objects.annotate_mac_address_count()
+    filterset = filtersets.MACBlockFilterSet
+    table = tables.MACBlockTable
+    form = forms.MACBlockBulkEditForm
+
+
+@register_model_view(MACBlock, 'bulk_delete', path='delete', detail=False)
+class MACBlockBulkDeleteView(generic.BulkDeleteView):
+    queryset = MACBlock.objects.annotate_mac_address_count()
+    filterset = filtersets.MACBlockFilterSet
+    table = tables.MACBlockTable

+ 4 - 1
netbox/ipam/graphql/filters.py

@@ -27,7 +27,7 @@ if TYPE_CHECKING:
     from core.graphql.filters import ContentTypeFilter
     from core.graphql.filters import ContentTypeFilter
     from dcim.graphql.filters import SiteFilter
     from dcim.graphql.filters import SiteFilter
     from netbox.graphql.filter_lookups import BigIntegerLookup, IntegerLookup, IntegerRangeArrayLookup
     from netbox.graphql.filter_lookups import BigIntegerLookup, IntegerLookup, IntegerRangeArrayLookup
-    from vpn.graphql.filters import L2VPNFilter
+    from vpn.graphql.filters import L2VPNFilter, L2VPNTerminationFilter
 
 
     from .enums import *
     from .enums import *
 
 
@@ -198,6 +198,9 @@ class IPAddressFilter(ContactFilterMixin, TenancyFilterMixin, PrimaryModelFilter
     )
     )
     nat_outside_id: ID | None = strawberry_django.filter_field()
     nat_outside_id: ID | None = strawberry_django.filter_field()
     dns_name: StrFilterLookup | None = strawberry_django.filter_field()
     dns_name: StrFilterLookup | None = strawberry_django.filter_field()
+    l2vpn_terminations: Annotated['L2VPNTerminationFilter', strawberry.lazy('vpn.graphql.filters')] | None = (
+        strawberry_django.filter_field()
+    )
 
 
     @strawberry_django.filter_field()
     @strawberry_django.filter_field()
     def assigned(self, value: bool, prefix) -> Q:
     def assigned(self, value: bool, prefix) -> Q:

+ 2 - 1
netbox/ipam/graphql/types.py

@@ -34,7 +34,7 @@ if TYPE_CHECKING:
     )
     )
     from tenancy.graphql.types import TenantType
     from tenancy.graphql.types import TenantType
     from virtualization.graphql.types import ClusterGroupType, ClusterType, VirtualMachineType, VMInterfaceType
     from virtualization.graphql.types import ClusterGroupType, ClusterType, VirtualMachineType, VMInterfaceType
-    from vpn.graphql.types import L2VPNType, TunnelTerminationType
+    from vpn.graphql.types import L2VPNTerminationType, L2VPNType, TunnelTerminationType
     from wireless.graphql.types import WirelessLANType
     from wireless.graphql.types import WirelessLANType
 
 
 __all__ = (
 __all__ = (
@@ -167,6 +167,7 @@ class IPAddressType(ContactsMixin, PrimaryObjectType):
     nat_inside: Annotated['IPAddressType', strawberry.lazy('ipam.graphql.types')] | None
     nat_inside: Annotated['IPAddressType', strawberry.lazy('ipam.graphql.types')] | None
     nat_outside: list[Annotated['IPAddressType', strawberry.lazy('ipam.graphql.types')]]
     nat_outside: list[Annotated['IPAddressType', strawberry.lazy('ipam.graphql.types')]]
     tunnel_terminations: list[Annotated['TunnelTerminationType', strawberry.lazy('vpn.graphql.types')]]
     tunnel_terminations: list[Annotated['TunnelTerminationType', strawberry.lazy('vpn.graphql.types')]]
+    l2vpn_terminations: list[Annotated['L2VPNTerminationType', strawberry.lazy('vpn.graphql.types')]]
     services: list[Annotated['ServiceType', strawberry.lazy('ipam.graphql.types')]]
     services: list[Annotated['ServiceType', strawberry.lazy('ipam.graphql.types')]]
 
 
     # Note that self is the Django model instance, so self.family resolves to the model's family property
     # Note that self is the Django model instance, so self.family resolves to the model's family property

+ 7 - 1
netbox/ipam/models/ip.py

@@ -1,5 +1,5 @@
 import netaddr
 import netaddr
-from django.contrib.contenttypes.fields import GenericForeignKey
+from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
 from django.contrib.contenttypes.models import ContentType
 from django.contrib.contenttypes.models import ContentType
 from django.contrib.postgres.indexes import GistIndex
 from django.contrib.postgres.indexes import GistIndex
 from django.core.exceptions import ValidationError
 from django.core.exceptions import ValidationError
@@ -1013,6 +1013,12 @@ class IPAddress(ContactsMixin, PrimaryModel):
         verbose_name=_('DNS name'),
         verbose_name=_('DNS name'),
         help_text=_('Hostname or FQDN (not case-sensitive)')
         help_text=_('Hostname or FQDN (not case-sensitive)')
     )
     )
+    l2vpn_terminations = GenericRelation(
+        to='vpn.L2VPNTermination',
+        content_type_field='assigned_object_type',
+        object_id_field='assigned_object_id',
+        related_query_name='ipaddress',
+    )
 
 
     objects = IPAddressManager()
     objects = IPAddressManager()
 
 

+ 6 - 0
netbox/ipam/views.py

@@ -1148,6 +1148,12 @@ class IPAddressView(generic.ObjectView):
                 filters={'ip_address_id': lambda ctx: ctx['object'].pk},
                 filters={'ip_address_id': lambda ctx: ctx['object'].pk},
                 title=_('Application services'),
                 title=_('Application services'),
             ),
             ),
+            ObjectsTablePanel(
+                'vpn.l2vpntermination',
+                filters={'ipaddress_id': lambda ctx: ctx['object'].pk},
+                exclude_columns=['assigned_object_type', 'assigned_object', 'assigned_object_parent'],
+                title=_('L2VPN terminations'),
+            ),
         ],
         ],
     )
     )
 
 

+ 1 - 0
netbox/netbox/constants.py

@@ -28,6 +28,7 @@ ADVISORY_LOCK_KEYS = {
     'available-ips': 100200,
     'available-ips': 100200,
     'available-vlans': 100300,
     'available-vlans': 100300,
     'available-asns': 100400,
     'available-asns': 100400,
+    'available-mac-addresses': 100500,
 
 
     # Jobs
     # Jobs
     'job-schedules': 110100,
     'job-schedules': 110100,

+ 45 - 3
netbox/netbox/forms/bulk_edit.py

@@ -4,8 +4,11 @@ from django.utils.translation import gettext_lazy as _
 from core.models import ObjectType
 from core.models import ObjectType
 from extras.choices import *
 from extras.choices import *
 from extras.models import Tag
 from extras.models import Tag
-from utilities.forms import BulkEditForm
-from utilities.forms.fields import CommentField, DynamicModelMultipleChoiceField
+from netbox.models.features import ContactsMixin
+from tenancy.choices import ContactPriorityChoices
+from tenancy.models import Contact, ContactRole
+from utilities.forms import BulkEditForm, add_blank_choice
+from utilities.forms.fields import CommentField, DynamicModelChoiceField, DynamicModelMultipleChoiceField
 
 
 from .mixins import ChangelogMessageMixin, CustomFieldsMixin, OwnerMixin
 from .mixins import ChangelogMessageMixin, CustomFieldsMixin, OwnerMixin
 
 
@@ -20,7 +23,7 @@ __all__ = (
 class NetBoxModelBulkEditForm(ChangelogMessageMixin, CustomFieldsMixin, BulkEditForm):
 class NetBoxModelBulkEditForm(ChangelogMessageMixin, CustomFieldsMixin, BulkEditForm):
     """
     """
     Base form for modifying multiple NetBox objects (of the same type) in bulk via the UI. Adds support for custom
     Base form for modifying multiple NetBox objects (of the same type) in bulk via the UI. Adds support for custom
-    fields and adding/removing tags.
+    fields, adding/removing tags, and adding/removing contact assignments (for models which support contacts).
 
 
     Attributes:
     Attributes:
         fieldsets: An iterable of two-tuples which define a heading and field set to display per section of
         fieldsets: An iterable of two-tuples which define a heading and field set to display per section of
@@ -42,6 +45,30 @@ class NetBoxModelBulkEditForm(ChangelogMessageMixin, CustomFieldsMixin, BulkEdit
         queryset=Tag.objects.all(),
         queryset=Tag.objects.all(),
         required=False
         required=False
     )
     )
+    add_contacts = DynamicModelMultipleChoiceField(
+        label=_('Add contacts'),
+        queryset=Contact.objects.all(),
+        required=False,
+        help_text=_('Existing assignments with the selected role are updated to the selected priority, if any')
+    )
+    contact_role = DynamicModelChoiceField(
+        label=_('Role'),
+        queryset=ContactRole.objects.all(),
+        required=False,
+        help_text=_('Role to assign to added contacts')
+    )
+    contact_priority = forms.ChoiceField(
+        label=_('Priority'),
+        choices=add_blank_choice(ContactPriorityChoices),
+        required=False,
+        help_text=_('Priority to assign to added contacts')
+    )
+    remove_contacts = DynamicModelMultipleChoiceField(
+        label=_('Remove contacts'),
+        queryset=Contact.objects.all(),
+        required=False,
+        help_text=_('Removes all assignments of these contacts, regardless of role')
+    )
 
 
     def __init__(self, *args, **kwargs):
     def __init__(self, *args, **kwargs):
         super().__init__(*args, **kwargs)
         super().__init__(*args, **kwargs)
@@ -53,8 +80,23 @@ class NetBoxModelBulkEditForm(ChangelogMessageMixin, CustomFieldsMixin, BulkEdit
         self.fields['add_tags'].widget.add_query_param('for_object_type_id', object_type.pk)
         self.fields['add_tags'].widget.add_query_param('for_object_type_id', object_type.pk)
         self.fields['remove_tags'].widget.add_query_param('for_object_type_id', object_type.pk)
         self.fields['remove_tags'].widget.add_query_param('for_object_type_id', object_type.pk)
 
 
+        # Contact fields apply only to models which support contact assignment
+        if not issubclass(self.model, ContactsMixin):
+            for name in ('add_contacts', 'contact_role', 'contact_priority', 'remove_contacts'):
+                del self.fields[name]
+
         self._extend_nullable_fields()
         self._extend_nullable_fields()
 
 
+    def clean(self):
+        super().clean()
+
+        if self.cleaned_data.get('add_contacts') and not self.cleaned_data.get('contact_role'):
+            raise forms.ValidationError({
+                'contact_role': _('A role must be specified when adding contacts.')
+            })
+
+        return self.cleaned_data
+
     def _get_form_field(self, customfield):
     def _get_form_field(self, customfield):
         return customfield.to_form_field(set_initial=False, enforce_required=False)
         return customfield.to_form_field(set_initial=False, enforce_required=False)
 
 

+ 1 - 0
netbox/netbox/navigation/menu.py

@@ -121,6 +121,7 @@ DEVICES_MENU = Menu(
             label=_('Addressing'),
             label=_('Addressing'),
             items=(
             items=(
                 get_model_item('dcim', 'macaddress', _('MAC Addresses')),
                 get_model_item('dcim', 'macaddress', _('MAC Addresses')),
+                get_model_item('dcim', 'macblock', _('MAC Address Blocks')),
             ),
             ),
         ),
         ),
     ),
     ),

+ 79 - 0
netbox/netbox/views/generic/bulk_views.py

@@ -33,6 +33,7 @@ from netbox.exporters import get_exporter
 from netbox.forms.bulk_rename import NetBoxModelBulkRenameForm
 from netbox.forms.bulk_rename import NetBoxModelBulkRenameForm
 from netbox.models.features import ChangeLoggingMixin
 from netbox.models.features import ChangeLoggingMixin
 from netbox.object_actions import AddObject, BulkDelete, BulkEdit, BulkExport, BulkImport, BulkRename
 from netbox.object_actions import AddObject, BulkDelete, BulkEdit, BulkExport, BulkImport, BulkRename
+from tenancy.models import ContactAssignment
 from utilities.error_handlers import handle_protectederror
 from utilities.error_handlers import handle_protectederror
 from utilities.exceptions import AbortRequest, AbortTransaction, PermissionsViolation
 from utilities.exceptions import AbortRequest, AbortTransaction, PermissionsViolation
 from utilities.forms import BulkDeleteForm, BulkRenameForm, restrict_form_fields
 from utilities.forms import BulkDeleteForm, BulkRenameForm, restrict_form_fields
@@ -910,6 +911,78 @@ class BulkEditView(GetReturnURLMixin, BaseMultiObjectView):
         if form.cleaned_data.get('remove_tags', None):
         if form.cleaned_data.get('remove_tags', None):
             obj.tags.remove(*form.cleaned_data['remove_tags'])
             obj.tags.remove(*form.cleaned_data['remove_tags'])
 
 
+        # Remove/add contact assignments
+        if form.cleaned_data.get('remove_contacts') or form.cleaned_data.get('add_contacts'):
+            self._update_contact_assignments(form, obj)
+
+    def _update_contact_assignments(self, form, obj):
+        object_type = ObjectType.objects.get_for_model(obj)
+        assignments = ContactAssignment.objects.filter(object_type=object_type, object_id=obj.pk)
+        changelog_message = form.cleaned_data.get('changelog_message')
+
+        # Removal precedes addition so that a contact's role can be replaced in a single operation
+        if remove_contacts := form.cleaned_data.get('remove_contacts'):
+            for assignment in assignments.filter(contact__in=remove_contacts):
+                assignment.snapshot()
+                assignment._changelog_message = changelog_message
+                assignment.delete()
+
+        if add_contacts := form.cleaned_data.get('add_contacts'):
+            role = form.cleaned_data.get('contact_role')
+            priority = form.cleaned_data.get('contact_priority') or None
+            existing = {
+                a.contact_id: a for a in assignments.filter(role=role, contact__in=add_contacts)
+            }
+            cf_defaults = CustomField.objects.get_defaults_for_model(ContactAssignment)
+            for contact in add_contacts:
+                # Apply a specified priority to an existing assignment rather than duplicating it
+                if assignment := existing.get(contact.pk):
+                    if priority is None or assignment.priority == priority:
+                        continue
+                    assignment.snapshot()
+                    assignment.priority = priority
+                    pk_list = self._contact_assignments['change']
+                else:
+                    assignment = ContactAssignment(
+                        object=obj, contact=contact, role=role, priority=priority,
+                        custom_field_data=dict(cf_defaults),
+                    )
+                    pk_list = self._contact_assignments['add']
+                assignment._changelog_message = changelog_message
+                try:
+                    assignment.full_clean()
+                except ValidationError as e:
+                    raise ValidationError(
+                        _("Unable to assign contact {contact} to {object}: {error}").format(
+                            contact=contact, object=obj, error='; '.join(e.messages)
+                        )
+                    )
+                assignment.save()
+                pk_list.append(assignment.pk)
+
+    def _check_contact_removal_permission(self, form):
+        """
+        Verify that the user may delete every contact assignment targeted for removal.
+        """
+        if remove_contacts := form.cleaned_data.get('remove_contacts'):
+            to_delete = ContactAssignment.objects.filter(
+                object_type=ObjectType.objects.get_for_model(self.queryset.model),
+                object_id__in=self.queryset.filter(pk__in=form.cleaned_data['pk']).values('pk'),
+                contact__in=remove_contacts,
+            )
+            if to_delete.restrict(self.request.user, 'delete').count() != to_delete.count():
+                raise PermissionsViolation
+
+    def _check_contact_assignment_permissions(self):
+        """
+        Verify that the user was permitted to create or modify every affected contact assignment.
+        """
+        for action, pk_list in self._contact_assignments.items():
+            if pk_list:
+                permitted = ContactAssignment.objects.restrict(self.request.user, action).filter(pk__in=pk_list)
+                if permitted.count() != len(pk_list):
+                    raise PermissionsViolation
+
     def _update_objects(self, form, request):
     def _update_objects(self, form, request):
         custom_fields = getattr(form, 'custom_fields', {})
         custom_fields = getattr(form, 'custom_fields', {})
         standard_fields = [
         standard_fields = [
@@ -935,6 +1008,10 @@ class BulkEditView(GetReturnURLMixin, BaseMultiObjectView):
                 # This form field is used to modify a field rather than set its value directly
                 # This form field is used to modify a field rather than set its value directly
                 model_fields[name] = None
                 model_fields[name] = None
 
 
+        # Contact assignment permissions are checked once for all objects rather than per object
+        self._contact_assignments = {'add': [], 'change': []}
+        self._check_contact_removal_permission(form)
+
         for obj in self.queryset.filter(pk__in=form.cleaned_data['pk']):
         for obj in self.queryset.filter(pk__in=form.cleaned_data['pk']):
 
 
             # Take a snapshot of change-logged models
             # Take a snapshot of change-logged models
@@ -996,6 +1073,8 @@ class BulkEditView(GetReturnURLMixin, BaseMultiObjectView):
             if is_background_request(request):
             if is_background_request(request):
                 request.job.logger.info(f"Updated {obj}")
                 request.job.logger.info(f"Updated {obj}")
 
 
+        self._check_contact_assignment_permissions()
+
         # Rebuild the tree for MPTT plugin models (no-op for ltree; its triggers keep
         # Rebuild the tree for MPTT plugin models (no-op for ltree; its triggers keep
         # the tree current). TODO: Remove in v5.0 (see _rebuild_mptt_tree).
         # the tree current). TODO: Remove in v5.0 (see _rebuild_mptt_tree).
         _rebuild_mptt_tree(self.queryset.model)
         _rebuild_mptt_tree(self.queryset.model)

+ 13 - 0
netbox/templates/generic/bulk_edit.html

@@ -82,6 +82,19 @@ Context:
             </div>
             </div>
           {% endif %}
           {% endif %}
 
 
+          {# Render contact add/remove fields #}
+          {% if form.add_contacts and form.remove_contacts %}
+            <div class="field-group mb-5">
+              <div class="row">
+                <h2 class="col-9 offset-3">{% trans "Contacts" %}</h2>
+              </div>
+              {% render_field form.add_contacts %}
+              {% render_field form.contact_role %}
+              {% render_field form.contact_priority %}
+              {% render_field form.remove_contacts %}
+            </div>
+          {% endif %}
+
           {# Render custom fields #}
           {# Render custom fields #}
           {% if form.custom_fields %}
           {% if form.custom_fields %}
             <div class="field-group mb-5">
             <div class="field-group mb-5">

+ 191 - 1
netbox/tenancy/tests/test_views.py

@@ -1,10 +1,14 @@
 from django.contrib.contenttypes.models import ContentType
 from django.contrib.contenttypes.models import ContentType
 from django.urls import reverse
 from django.urls import reverse
 
 
+from core.models import ObjectType
 from dcim.models import Site
 from dcim.models import Site
+from extras.choices import CustomFieldTypeChoices
+from extras.models import CustomField
 from tenancy.choices import ContactPriorityChoices
 from tenancy.choices import ContactPriorityChoices
+from tenancy.forms import ContactBulkEditForm
 from tenancy.models import *
 from tenancy.models import *
-from utilities.testing import ViewTestCases, create_tags
+from utilities.testing import TestCase, ViewTestCases, create_tags
 
 
 
 
 class TenantGroupTestCase(ViewTestCases.OrganizationalObjectViewTestCase):
 class TenantGroupTestCase(ViewTestCases.OrganizationalObjectViewTestCase):
@@ -102,6 +106,192 @@ class TenantTestCase(ViewTestCases.PrimaryObjectViewTestCase):
         }
         }
 
 
 
 
+class TenantBulkEditContactsTestCase(TestCase):
+
+    @classmethod
+    def setUpTestData(cls):
+        cls.tenants = (
+            Tenant(name='Tenant 1', slug='tenant-1'),
+            Tenant(name='Tenant 2', slug='tenant-2'),
+        )
+        Tenant.objects.bulk_create(cls.tenants)
+        cls.contacts = (
+            Contact(name='Contact 1'),
+            Contact(name='Contact 2'),
+        )
+        Contact.objects.bulk_create(cls.contacts)
+        cls.roles = (
+            ContactRole(name='Role 1', slug='role-1'),
+            ContactRole(name='Role 2', slug='role-2'),
+        )
+        ContactRole.objects.bulk_create(cls.roles)
+
+    def _post(self, **data):
+        return self.client.post(reverse('tenancy:tenant_bulk_edit'), {
+            'pk': [t.pk for t in self.tenants],
+            '_apply': True,
+            **data,
+        })
+
+    def test_add_contacts(self):
+        self.add_permissions(
+            'tenancy.view_tenant', 'tenancy.change_tenant', 'tenancy.view_contact', 'tenancy.view_contactrole',
+            'tenancy.add_contactassignment',
+        )
+        # An existing assignment should not be duplicated
+        ContactAssignment.objects.create(
+            object=self.tenants[0], contact=self.contacts[0], role=self.roles[0],
+            priority=ContactPriorityChoices.PRIORITY_PRIMARY,
+        )
+
+        response = self._post(
+            add_contacts=[c.pk for c in self.contacts],
+            contact_role=self.roles[0].pk,
+            contact_priority=ContactPriorityChoices.PRIORITY_PRIMARY,
+        )
+        self.assertHttpStatus(response, 302)
+        for tenant in self.tenants:
+            assignments = ContactAssignment.objects.filter(
+                object_type=ContentType.objects.get_for_model(Tenant), object_id=tenant.pk, role=self.roles[0]
+            )
+            self.assertEqual(
+                set(assignments.values_list('contact', flat=True)), {c.pk for c in self.contacts}
+            )
+        self.assertEqual(ContactAssignment.objects.filter(priority=ContactPriorityChoices.PRIORITY_PRIMARY).count(), 4)
+
+    def test_add_contacts_without_priority(self):
+        self.add_permissions(
+            'tenancy.view_tenant', 'tenancy.change_tenant', 'tenancy.view_contact', 'tenancy.view_contactrole',
+            'tenancy.add_contactassignment',
+        )
+        response = self._post(add_contacts=[self.contacts[0].pk], contact_role=self.roles[0].pk)
+        self.assertHttpStatus(response, 302)
+        self.assertEqual(ContactAssignment.objects.filter(contact=self.contacts[0], priority__isnull=True).count(), 2)
+
+    def test_add_contacts_updates_existing_priority(self):
+        self.add_permissions(
+            'tenancy.view_tenant', 'tenancy.change_tenant', 'tenancy.view_contact', 'tenancy.view_contactrole',
+            'tenancy.add_contactassignment', 'tenancy.change_contactassignment',
+        )
+        assignment = ContactAssignment.objects.create(
+            object=self.tenants[0], contact=self.contacts[0], role=self.roles[0]
+        )
+
+        response = self._post(
+            add_contacts=[self.contacts[0].pk],
+            contact_role=self.roles[0].pk,
+            contact_priority=ContactPriorityChoices.PRIORITY_PRIMARY,
+        )
+        self.assertHttpStatus(response, 302)
+        assignment.refresh_from_db()
+        self.assertEqual(assignment.priority, ContactPriorityChoices.PRIORITY_PRIMARY)
+        self.assertEqual(ContactAssignment.objects.count(), 2)
+
+    def test_add_contacts_updates_existing_priority_without_permission(self):
+        self.add_permissions(
+            'tenancy.view_tenant', 'tenancy.change_tenant', 'tenancy.view_contact', 'tenancy.view_contactrole',
+            'tenancy.add_contactassignment',
+        )
+        assignment = ContactAssignment.objects.create(
+            object=self.tenants[0], contact=self.contacts[0], role=self.roles[0]
+        )
+
+        response = self._post(
+            add_contacts=[self.contacts[0].pk],
+            contact_role=self.roles[0].pk,
+            contact_priority=ContactPriorityChoices.PRIORITY_PRIMARY,
+        )
+        self.assertHttpStatus(response, 200)
+        assignment.refresh_from_db()
+        self.assertIsNone(assignment.priority)
+        self.assertEqual(ContactAssignment.objects.count(), 1)
+
+    def test_add_contacts_required_custom_field(self):
+        self.add_permissions(
+            'tenancy.view_tenant', 'tenancy.change_tenant', 'tenancy.view_contact', 'tenancy.view_contactrole',
+            'tenancy.add_contactassignment',
+        )
+        cf = CustomField.objects.create(name='cf1', type=CustomFieldTypeChoices.TYPE_TEXT, required=True)
+        cf.object_types.set([ObjectType.objects.get_for_model(ContactAssignment)])
+
+        # A required custom field without a default cannot be satisfied
+        response = self._post(add_contacts=[self.contacts[0].pk], contact_role=self.roles[0].pk)
+        self.assertHttpStatus(response, 200)
+        self.assertFalse(ContactAssignment.objects.exists())
+
+        # The default value is applied to new assignments
+        cf.default = 'foo'
+        cf.save()
+        response = self._post(add_contacts=[self.contacts[0].pk], contact_role=self.roles[0].pk)
+        self.assertHttpStatus(response, 302)
+        self.assertEqual(ContactAssignment.objects.filter(custom_field_data__cf1='foo').count(), 2)
+
+    def test_replace_contact_role(self):
+        self.add_permissions(
+            'tenancy.view_tenant', 'tenancy.change_tenant', 'tenancy.view_contact', 'tenancy.view_contactrole',
+            'tenancy.add_contactassignment', 'tenancy.delete_contactassignment',
+        )
+        for tenant in self.tenants:
+            ContactAssignment.objects.create(object=tenant, contact=self.contacts[0], role=self.roles[0])
+
+        # Removing and re-adding a contact in one edit replaces its role
+        response = self._post(
+            add_contacts=[self.contacts[0].pk],
+            contact_role=self.roles[1].pk,
+            remove_contacts=[self.contacts[0].pk],
+        )
+        self.assertHttpStatus(response, 302)
+        self.assertEqual(ContactAssignment.objects.filter(contact=self.contacts[0], role=self.roles[1]).count(), 2)
+        self.assertFalse(ContactAssignment.objects.filter(role=self.roles[0]).exists())
+
+    def test_add_contacts_requires_role(self):
+        self.add_permissions(
+            'tenancy.view_tenant', 'tenancy.change_tenant', 'tenancy.view_contact',
+            'tenancy.add_contactassignment',
+        )
+        response = self._post(add_contacts=[self.contacts[0].pk])
+        self.assertHttpStatus(response, 200)
+        self.assertFalse(ContactAssignment.objects.exists())
+
+    def test_add_contacts_without_permission(self):
+        self.add_permissions(
+            'tenancy.view_tenant', 'tenancy.change_tenant', 'tenancy.view_contact', 'tenancy.view_contactrole',
+        )
+        response = self._post(add_contacts=[self.contacts[0].pk], contact_role=self.roles[0].pk)
+        self.assertHttpStatus(response, 200)
+        self.assertFalse(ContactAssignment.objects.exists())
+
+    def test_remove_contacts(self):
+        self.add_permissions(
+            'tenancy.view_tenant', 'tenancy.change_tenant', 'tenancy.view_contact',
+            'tenancy.delete_contactassignment',
+        )
+        for tenant in self.tenants:
+            for role in self.roles:
+                ContactAssignment.objects.create(object=tenant, contact=self.contacts[0], role=role)
+            ContactAssignment.objects.create(object=tenant, contact=self.contacts[1], role=self.roles[0])
+
+        response = self._post(remove_contacts=[self.contacts[0].pk])
+        self.assertHttpStatus(response, 302)
+        self.assertFalse(ContactAssignment.objects.filter(contact=self.contacts[0]).exists())
+        self.assertEqual(ContactAssignment.objects.filter(contact=self.contacts[1]).count(), 2)
+
+    def test_remove_contacts_without_permission(self):
+        self.add_permissions(
+            'tenancy.view_tenant', 'tenancy.change_tenant', 'tenancy.view_contact',
+        )
+        ContactAssignment.objects.create(object=self.tenants[0], contact=self.contacts[0], role=self.roles[0])
+
+        response = self._post(remove_contacts=[self.contacts[0].pk])
+        self.assertHttpStatus(response, 200)
+        self.assertEqual(ContactAssignment.objects.count(), 1)
+
+    def test_contact_fields_omitted_for_unsupported_models(self):
+        form = ContactBulkEditForm()
+        self.assertNotIn('add_contacts', form.fields)
+        self.assertNotIn('remove_contacts', form.fields)
+
+
 class ContactGroupTestCase(ViewTestCases.OrganizationalObjectViewTestCase):
 class ContactGroupTestCase(ViewTestCases.OrganizationalObjectViewTestCase):
     model = ContactGroup
     model = ContactGroup
 
 

+ 6 - 0
netbox/vpn/constants.py

@@ -2,6 +2,12 @@ from django.db.models import Q
 
 
 L2VPN_ASSIGNMENT_MODELS = Q(
 L2VPN_ASSIGNMENT_MODELS = Q(
     Q(app_label='dcim', model='interface') |
     Q(app_label='dcim', model='interface') |
+    Q(app_label='ipam', model='ipaddress') |
     Q(app_label='ipam', model='vlan') |
     Q(app_label='ipam', model='vlan') |
     Q(app_label='virtualization', model='vminterface')
     Q(app_label='virtualization', model='vminterface')
 )
 )
+
+# Models which may terminate more than one L2VPN (e.g. an IP address which is the far-end PE of several pseudowires)
+L2VPN_MULTI_TERMINATION_MODELS = (
+    'ipam.ipaddress',
+)

+ 51 - 6
netbox/vpn/filtersets.py

@@ -5,6 +5,7 @@ from django.utils.translation import gettext as _
 from core.models import ObjectType
 from core.models import ObjectType
 from dcim.models import Device, Interface
 from dcim.models import Device, Interface
 from ipam.models import VLAN, IPAddress, RouteTarget
 from ipam.models import VLAN, IPAddress, RouteTarget
+from ipam.utils import parse_inet_addresses
 from netbox.filtersets import NetBoxModelFilterSet, OrganizationalModelFilterSet, PrimaryModelFilterSet
 from netbox.filtersets import NetBoxModelFilterSet, OrganizationalModelFilterSet, PrimaryModelFilterSet
 from tenancy.filtersets import ContactModelFilterSet, TenancyFilterSet
 from tenancy.filtersets import ContactModelFilterSet, TenancyFilterSet
 from utilities.filters import (
 from utilities.filters import (
@@ -422,24 +423,28 @@ class L2VPNTerminationFilterSet(NetBoxModelFilterSet):
         label=_('Site (ID)'),
         label=_('Site (ID)'),
     )
     )
     device = NonUniqueModelMultipleChoiceFilter(
     device = NonUniqueModelMultipleChoiceFilter(
-        field_name='interface__device__name',
+        method='filter_device',
+        field_name='name',
         queryset=Device.objects.all(),
         queryset=Device.objects.all(),
         to_field_name='name',
         to_field_name='name',
         label=_('Device (name)'),
         label=_('Device (name)'),
     )
     )
     device_id = django_filters.ModelMultipleChoiceFilter(
     device_id = django_filters.ModelMultipleChoiceFilter(
-        field_name='interface__device',
+        method='filter_device',
+        field_name='pk',
         queryset=Device.objects.all(),
         queryset=Device.objects.all(),
         label=_('Device (ID)'),
         label=_('Device (ID)'),
     )
     )
     virtual_machine = NonUniqueModelMultipleChoiceFilter(
     virtual_machine = NonUniqueModelMultipleChoiceFilter(
-        field_name='vminterface__virtual_machine__name',
+        method='filter_virtual_machine',
+        field_name='name',
         queryset=VirtualMachine.objects.all(),
         queryset=VirtualMachine.objects.all(),
         to_field_name='name',
         to_field_name='name',
         label=_('Virtual machine (name)'),
         label=_('Virtual machine (name)'),
     )
     )
     virtual_machine_id = django_filters.ModelMultipleChoiceFilter(
     virtual_machine_id = django_filters.ModelMultipleChoiceFilter(
-        field_name='vminterface__virtual_machine',
+        method='filter_virtual_machine',
+        field_name='pk',
         queryset=VirtualMachine.objects.all(),
         queryset=VirtualMachine.objects.all(),
         label=_('Virtual machine (ID)'),
         label=_('Virtual machine (ID)'),
     )
     )
@@ -480,6 +485,15 @@ class L2VPNTerminationFilterSet(NetBoxModelFilterSet):
         queryset=VLAN.objects.all(),
         queryset=VLAN.objects.all(),
         label=_('VLAN (ID)'),
         label=_('VLAN (ID)'),
     )
     )
+    ipaddress = MultiValueCharFilter(
+        method='filter_ipaddress',
+        label=_('IP address'),
+    )
+    ipaddress_id = django_filters.ModelMultipleChoiceFilter(
+        field_name='ipaddress',
+        queryset=IPAddress.objects.all(),
+        label=_('IP address (ID)'),
+    )
     assigned_object_type_id = django_filters.ModelMultipleChoiceFilter(
     assigned_object_type_id = django_filters.ModelMultipleChoiceFilter(
         queryset=ObjectType.objects.all(),
         queryset=ObjectType.objects.all(),
         distinct=False,
         distinct=False,
@@ -508,17 +522,48 @@ class L2VPNTerminationFilterSet(NetBoxModelFilterSet):
             Q(
             Q(
                 Q(**{'vlan__site__{}__in'.format(name): value}) |
                 Q(**{'vlan__site__{}__in'.format(name): value}) |
                 Q(**{'interface__device__site__{}__in'.format(name): value}) |
                 Q(**{'interface__device__site__{}__in'.format(name): value}) |
-                Q(**{'vminterface__virtual_machine__site__{}__in'.format(name): value})
+                Q(**{'vminterface__virtual_machine__site__{}__in'.format(name): value}) |
+                Q(**{'ipaddress__interface__device__site__{}__in'.format(name): value}) |
+                Q(**{'ipaddress__vminterface__virtual_machine__site__{}__in'.format(name): value})
             )
             )
         )
         )
         return qs
         return qs
 
 
+    def filter_ipaddress(self, queryset, name, value):
+        # Match an address given without a mask regardless of the IP address's mask. Discard any invalid addresses.
+        value = parse_inet_addresses(value)
+        if not value:
+            return queryset.none()
+        return queryset.filter(ipaddress__address__net_in=value)
+
+    def filter_device(self, queryset, name, value):
+        if not value:
+            return queryset
+        # Match on the name (rather than the object) when filtering by name, as devices may share a name
+        values = [getattr(device, name) for device in value]
+        return queryset.filter(
+            Q(**{f'interface__device__{name}__in': values}) |
+            Q(**{f'ipaddress__interface__device__{name}__in': values})
+        )
+
+    def filter_virtual_machine(self, queryset, name, value):
+        if not value:
+            return queryset
+        # Match on the name (rather than the object) when filtering by name, as virtual machines may share a name
+        values = [getattr(vm, name) for vm in value]
+        return queryset.filter(
+            Q(**{f'vminterface__virtual_machine__{name}__in': values}) |
+            Q(**{f'ipaddress__vminterface__virtual_machine__{name}__in': values})
+        )
+
     def filter_region(self, queryset, name, value):
     def filter_region(self, queryset, name, value):
         qs = queryset.filter(
         qs = queryset.filter(
             Q(
             Q(
                 Q(**{'vlan__site__region__{}__in'.format(name): value}) |
                 Q(**{'vlan__site__region__{}__in'.format(name): value}) |
                 Q(**{'interface__device__site__region__{}__in'.format(name): value}) |
                 Q(**{'interface__device__site__region__{}__in'.format(name): value}) |
-                Q(**{'vminterface__virtual_machine__site__region__{}__in'.format(name): value})
+                Q(**{'vminterface__virtual_machine__site__region__{}__in'.format(name): value}) |
+                Q(**{'ipaddress__interface__device__site__region__{}__in'.format(name): value}) |
+                Q(**{'ipaddress__vminterface__virtual_machine__site__region__{}__in'.format(name): value})
             )
             )
         )
         )
         return qs
         return qs

+ 49 - 13
netbox/vpn/forms/bulk_import.py

@@ -2,7 +2,7 @@ from django.core.exceptions import ValidationError
 from django.utils.translation import gettext_lazy as _
 from django.utils.translation import gettext_lazy as _
 
 
 from dcim.models import Device, Interface
 from dcim.models import Device, Interface
-from ipam.models import VLAN, IPAddress
+from ipam.models import VLAN, VRF, IPAddress
 from netbox.forms import NetBoxModelImportForm, OrganizationalModelImportForm, PrimaryModelImportForm
 from netbox.forms import NetBoxModelImportForm, OrganizationalModelImportForm, PrimaryModelImportForm
 from tenancy.models import Tenant
 from tenancy.models import Tenant
 from utilities.forms.fields import CSVChoiceField, CSVModelChoiceField, CSVModelMultipleChoiceField
 from utilities.forms.fields import CSVChoiceField, CSVModelChoiceField, CSVModelMultipleChoiceField
@@ -289,14 +289,14 @@ class L2VPNTerminationImportForm(NetBoxModelImportForm):
         queryset=Device.objects.all(),
         queryset=Device.objects.all(),
         required=False,
         required=False,
         to_field_name='name',
         to_field_name='name',
-        help_text=_('Parent device (for interface)')
+        help_text=_('Parent device (for interface or IP address)')
     )
     )
     virtual_machine = CSVModelChoiceField(
     virtual_machine = CSVModelChoiceField(
         label=_('Virtual machine'),
         label=_('Virtual machine'),
         queryset=VirtualMachine.objects.all(),
         queryset=VirtualMachine.objects.all(),
         required=False,
         required=False,
         to_field_name='name',
         to_field_name='name',
-        help_text=_('Parent virtual machine (for interface)')
+        help_text=_('Parent virtual machine (for interface or IP address)')
     )
     )
     interface = CSVModelChoiceField(
     interface = CSVModelChoiceField(
         label=_('Interface'),
         label=_('Interface'),
@@ -312,36 +312,72 @@ class L2VPNTerminationImportForm(NetBoxModelImportForm):
         to_field_name='name',
         to_field_name='name',
         help_text=_('Assigned VLAN')
         help_text=_('Assigned VLAN')
     )
     )
+    ipaddress = CSVModelChoiceField(
+        label=_('IP address'),
+        queryset=IPAddress.objects.all(),
+        required=False,
+        to_field_name='address',
+        help_text=_('Assigned IP address, with mask (e.g. the far-end PE of a pseudowire)')
+    )
+    ipaddress_vrf = CSVModelChoiceField(
+        label=_('IP address VRF'),
+        queryset=VRF.objects.all(),
+        required=False,
+        to_field_name='name',
+        help_text=_('VRF of the assigned IP address')
+    )
 
 
     class Meta:
     class Meta:
         model = L2VPNTermination
         model = L2VPNTermination
-        fields = ('l2vpn', 'device', 'virtual_machine', 'interface', 'vlan', 'tags')
+        fields = ('l2vpn', 'device', 'virtual_machine', 'interface', 'vlan', 'ipaddress', 'ipaddress_vrf', 'tags')
 
 
     def __init__(self, data=None, *args, **kwargs):
     def __init__(self, data=None, *args, **kwargs):
         super().__init__(data, *args, **kwargs)
         super().__init__(data, *args, **kwargs)
 
 
         if data:
         if data:
 
 
-            # Limit interface queryset by device or VM
+            # Limit interface and IP address querysets by device or VM
             if data.get('device'):
             if data.get('device'):
                 self.fields['interface'].queryset = Interface.objects.filter(
                 self.fields['interface'].queryset = Interface.objects.filter(
                     **{f"device__{self.fields['device'].to_field_name}": data['device']}
                     **{f"device__{self.fields['device'].to_field_name}": data['device']}
                 )
                 )
+                self.fields['ipaddress'].queryset = IPAddress.objects.filter(
+                    **{f"interface__device__{self.fields['device'].to_field_name}": data['device']}
+                )
             elif data.get('virtual_machine'):
             elif data.get('virtual_machine'):
                 self.fields['interface'].queryset = VMInterface.objects.filter(
                 self.fields['interface'].queryset = VMInterface.objects.filter(
                     **{f"virtual_machine__{self.fields['virtual_machine'].to_field_name}": data['virtual_machine']}
                     **{f"virtual_machine__{self.fields['virtual_machine'].to_field_name}": data['virtual_machine']}
                 )
                 )
+                self.fields['ipaddress'].queryset = IPAddress.objects.filter(
+                    **{
+                        f"vminterface__virtual_machine__{self.fields['virtual_machine'].to_field_name}":
+                            data['virtual_machine']
+                    }
+                )
+
+            # Limit IP address queryset by VRF
+            if data.get('ipaddress_vrf'):
+                self.fields['ipaddress'].queryset = self.fields['ipaddress'].queryset.filter(
+                    **{f"vrf__{self.fields['ipaddress_vrf'].to_field_name}": data['ipaddress_vrf']}
+                )
 
 
     def clean(self):
     def clean(self):
         super().clean()
         super().clean()
 
 
         if self.cleaned_data.get('device') and self.cleaned_data.get('virtual_machine'):
         if self.cleaned_data.get('device') and self.cleaned_data.get('virtual_machine'):
             raise ValidationError(_('Cannot import device and VM interface terminations simultaneously.'))
             raise ValidationError(_('Cannot import device and VM interface terminations simultaneously.'))
-        if not self.instance and not (self.cleaned_data.get('interface') or self.cleaned_data.get('vlan')):
-            raise ValidationError(_('Each termination must specify either an interface or a VLAN.'))
-        if self.cleaned_data.get('interface') and self.cleaned_data.get('vlan'):
-            raise ValidationError(_('Cannot assign both an interface and a VLAN.'))
-
-        # if this is an update we might not have interface or vlan in the form data
-        if self.cleaned_data.get('interface') or self.cleaned_data.get('vlan'):
-            self.instance.assigned_object = self.cleaned_data.get('interface') or self.cleaned_data.get('vlan')
+        assigned_objects = [
+            obj for obj in (
+                self.cleaned_data.get('interface'),
+                self.cleaned_data.get('vlan'),
+                self.cleaned_data.get('ipaddress'),
+            ) if obj
+        ]
+        if not self.instance.pk and not assigned_objects:
+            raise ValidationError(_('Each termination must specify an interface, a VLAN, or an IP address.'))
+        if len(assigned_objects) > 1:
+            raise ValidationError(_('Cannot assign more than one of an interface, a VLAN, and an IP address.'))
+
+        # if this is an update we might not have an assigned object in the form data
+        if assigned_objects:
+            self.instance.assigned_object = assigned_objects[0]

+ 7 - 2
netbox/vpn/forms/filtersets.py

@@ -3,7 +3,7 @@ from django.contrib.contenttypes.models import ContentType
 from django.utils.translation import gettext as _
 from django.utils.translation import gettext as _
 
 
 from dcim.models import Device, Region, Site
 from dcim.models import Device, Region, Site
-from ipam.models import VLAN, RouteTarget
+from ipam.models import VLAN, IPAddress, RouteTarget
 from netbox.forms import NetBoxModelFilterSetForm, OrganizationalModelFilterSetForm, PrimaryModelFilterSetForm
 from netbox.forms import NetBoxModelFilterSetForm, OrganizationalModelFilterSetForm, PrimaryModelFilterSetForm
 from tenancy.forms import ContactModelFilterForm, TenancyFilterForm
 from tenancy.forms import ContactModelFilterForm, TenancyFilterForm
 from utilities.forms.fields import (
 from utilities.forms.fields import (
@@ -259,7 +259,7 @@ class L2VPNTerminationFilterForm(NetBoxModelFilterSetForm):
         FieldSet('filter_id', 'tag', 'l2vpn_id'),
         FieldSet('filter_id', 'tag', 'l2vpn_id'),
         FieldSet(
         FieldSet(
             'assigned_object_type_id', 'region_id', 'site_id', 'device_id', 'virtual_machine_id', 'vlan_id',
             'assigned_object_type_id', 'region_id', 'site_id', 'device_id', 'virtual_machine_id', 'vlan_id',
-            name=_('Assigned Object')
+            'ipaddress_id', name=_('Assigned Object')
         ),
         ),
     )
     )
     l2vpn_id = DynamicModelChoiceField(
     l2vpn_id = DynamicModelChoiceField(
@@ -314,4 +314,9 @@ class L2VPNTerminationFilterForm(NetBoxModelFilterSetForm):
         },
         },
         label=_('Virtual Machine')
         label=_('Virtual Machine')
     )
     )
+    ipaddress_id = DynamicModelMultipleChoiceField(
+        queryset=IPAddress.objects.all(),
+        required=False,
+        label=_('IP Address')
+    )
     tag = TagFilterField(model)
     tag = TagFilterField(model)

+ 18 - 5
netbox/vpn/forms/model_forms.py

@@ -506,6 +506,13 @@ class L2VPNTerminationForm(NetBoxModelForm):
         selector=True,
         selector=True,
         label=_('Interface')
         label=_('Interface')
     )
     )
+    ipaddress = DynamicModelChoiceField(
+        queryset=IPAddress.objects.all(),
+        required=False,
+        selector=True,
+        label=_('IP Address'),
+        help_text=_('For example, the far-end PE of a pseudowire')
+    )
 
 
     fieldsets = (
     fieldsets = (
         FieldSet(
         FieldSet(
@@ -514,6 +521,7 @@ class L2VPNTerminationForm(NetBoxModelForm):
                 FieldSet('vlan', name=_('VLAN')),
                 FieldSet('vlan', name=_('VLAN')),
                 FieldSet('interface', name=_('Device')),
                 FieldSet('interface', name=_('Device')),
                 FieldSet('vminterface', name=_('Virtual Machine')),
                 FieldSet('vminterface', name=_('Virtual Machine')),
+                FieldSet('ipaddress', name=_('IP Address')),
             ),
             ),
             'tags',
             'tags',
         ),
         ),
@@ -534,6 +542,8 @@ class L2VPNTerminationForm(NetBoxModelForm):
                 initial['vlan'] = instance.assigned_object
                 initial['vlan'] = instance.assigned_object
             elif type(instance.assigned_object) is VMInterface:
             elif type(instance.assigned_object) is VMInterface:
                 initial['vminterface'] = instance.assigned_object
                 initial['vminterface'] = instance.assigned_object
+            elif type(instance.assigned_object) is IPAddress:
+                initial['ipaddress'] = instance.assigned_object
             kwargs['initial'] = initial
             kwargs['initial'] = initial
 
 
         super().__init__(*args, **kwargs)
         super().__init__(*args, **kwargs)
@@ -544,10 +554,13 @@ class L2VPNTerminationForm(NetBoxModelForm):
         interface = self.cleaned_data.get('interface')
         interface = self.cleaned_data.get('interface')
         vminterface = self.cleaned_data.get('vminterface')
         vminterface = self.cleaned_data.get('vminterface')
         vlan = self.cleaned_data.get('vlan')
         vlan = self.cleaned_data.get('vlan')
+        ipaddress = self.cleaned_data.get('ipaddress')
 
 
-        if not (interface or vminterface or vlan):
-            raise ValidationError(_('A termination must specify an interface or VLAN.'))
-        if len([x for x in (interface, vminterface, vlan) if x]) > 1:
-            raise ValidationError(_('A termination can only have one terminating object (an interface or VLAN).'))
+        if not (interface or vminterface or vlan or ipaddress):
+            raise ValidationError(_('A termination must specify an interface, VLAN, or IP address.'))
+        if len([x for x in (interface, vminterface, vlan, ipaddress) if x]) > 1:
+            raise ValidationError(
+                _('A termination can only have one terminating object (an interface, VLAN, or IP address).')
+            )
 
 
-        self.instance.assigned_object = interface or vminterface or vlan
+        self.instance.assigned_object = interface or vminterface or vlan or ipaddress

+ 3 - 1
netbox/vpn/graphql/types.py

@@ -5,7 +5,7 @@ import strawberry_django
 
 
 from dcim.models import Interface
 from dcim.models import Interface
 from extras.graphql.mixins import ContactsMixin, CustomFieldsMixin, TagsMixin
 from extras.graphql.mixins import ContactsMixin, CustomFieldsMixin, TagsMixin
-from ipam.models import VLAN
+from ipam.models import VLAN, IPAddress
 from netbox.graphql.optimization import build_gfk_prefetch
 from netbox.graphql.optimization import build_gfk_prefetch
 from netbox.graphql.types import (
 from netbox.graphql.types import (
     NetBoxObjectType,
     NetBoxObjectType,
@@ -162,12 +162,14 @@ class L2VPNTerminationType(NetBoxObjectType):
                 Interface,
                 Interface,
                 VMInterface,
                 VMInterface,
                 VLAN,
                 VLAN,
+                IPAddress,
             ],
             ],
         ),
         ),
         only=['assigned_object_type', 'assigned_object_id'],
         only=['assigned_object_type', 'assigned_object_id'],
     )
     )
     def assigned_object(self) -> Annotated[
     def assigned_object(self) -> Annotated[
         Annotated['InterfaceType', strawberry.lazy('dcim.graphql.types')]
         Annotated['InterfaceType', strawberry.lazy('dcim.graphql.types')]
+        | Annotated['IPAddressType', strawberry.lazy('ipam.graphql.types')]
         | Annotated['VLANType', strawberry.lazy('ipam.graphql.types')]
         | Annotated['VLANType', strawberry.lazy('ipam.graphql.types')]
         | Annotated['VMInterfaceType', strawberry.lazy('virtualization.graphql.types')],
         | Annotated['VMInterfaceType', strawberry.lazy('virtualization.graphql.types')],
         strawberry.union('L2VPNAssignmentType'),
         strawberry.union('L2VPNAssignmentType'),

+ 26 - 0
netbox/vpn/migrations/0014_l2vpntermination_unique_per_l2vpn.py

@@ -0,0 +1,26 @@
+# Generated by Django 6.1.1 on 2026-11-02 19:40
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('contenttypes', '0002_remove_content_type_name'),
+        ('extras', '0145_taggeditem_object_id_bigint'),
+        ('vpn', '0013_consolidate_unique_constraints'),
+    ]
+
+    operations = [
+        migrations.RemoveConstraint(
+            model_name='l2vpntermination',
+            name='vpn_l2vpntermination_assigned_object',
+        ),
+        migrations.AddConstraint(
+            model_name='l2vpntermination',
+            constraint=models.UniqueConstraint(
+                fields=('l2vpn', 'assigned_object_type', 'assigned_object_id'),
+                name='vpn_l2vpntermination_l2vpn_assigned_object',
+            ),
+        ),
+    ]

+ 26 - 13
netbox/vpn/models/l2vpn.py

@@ -5,9 +5,11 @@ from django.utils.functional import cached_property
 from django.utils.translation import gettext_lazy as _
 from django.utils.translation import gettext_lazy as _
 
 
 from core.models import ObjectType
 from core.models import ObjectType
+from ipam.models import VLAN, IPAddress
 from netbox.models import NetBoxModel, PrimaryModel
 from netbox.models import NetBoxModel, PrimaryModel
 from netbox.models.features import ContactsMixin
 from netbox.models.features import ContactsMixin
 from vpn.choices import L2VPNStatusChoices, L2VPNTypeChoices
 from vpn.choices import L2VPNStatusChoices, L2VPNTypeChoices
+from vpn.constants import L2VPN_MULTI_TERMINATION_MODELS
 
 
 __all__ = (
 __all__ = (
     'L2VPN',
     'L2VPN',
@@ -109,8 +111,8 @@ class L2VPNTermination(NetBoxModel):
         ordering = ('l2vpn',)
         ordering = ('l2vpn',)
         constraints = (
         constraints = (
             models.UniqueConstraint(
             models.UniqueConstraint(
-                fields=('assigned_object_type', 'assigned_object_id'),
-                name='vpn_l2vpntermination_assigned_object'
+                fields=('l2vpn', 'assigned_object_type', 'assigned_object_id'),
+                name='vpn_l2vpntermination_l2vpn_assigned_object'
             ),
             ),
         )
         )
         verbose_name = _('L2VPN termination')
         verbose_name = _('L2VPN termination')
@@ -126,8 +128,18 @@ class L2VPNTermination(NetBoxModel):
         if self.assigned_object:
         if self.assigned_object:
             obj_id = self.assigned_object.pk
             obj_id = self.assigned_object.pk
             obj_type = ObjectType.objects.get_for_model(self.assigned_object)
             obj_type = ObjectType.objects.get_for_model(self.assigned_object)
-            terminations = L2VPNTermination.objects.filter(assigned_object_id=obj_id, assigned_object_type=obj_type)
-            if terminations.exclude(pk=self.pk).exists():
+            terminations = L2VPNTermination.objects.filter(
+                assigned_object_id=obj_id, assigned_object_type=obj_type
+            ).exclude(pk=self.pk)
+            # Some objects may terminate many L2VPNs, but each only once. Others may terminate only one L2VPN.
+            if self.assigned_object._meta.label_lower in L2VPN_MULTI_TERMINATION_MODELS:
+                if terminations.filter(l2vpn_id=self.l2vpn_id).exists():
+                    raise ValidationError(
+                        _('{assigned_object} already terminates {l2vpn}').format(
+                            assigned_object=self.assigned_object, l2vpn=self.l2vpn
+                        )
+                    )
+            elif terminations.exists():
                 raise ValidationError(
                 raise ValidationError(
                     _('L2VPN Termination already assigned ({assigned_object})').format(
                     _('L2VPN Termination already assigned ({assigned_object})').format(
                         assigned_object=self.assigned_object
                         assigned_object=self.assigned_object
@@ -147,15 +159,16 @@ class L2VPNTermination(NetBoxModel):
 
 
     @property
     @property
     def assigned_object_parent(self):
     def assigned_object_parent(self):
-        obj_type = ObjectType.objects.get_for_model(self.assigned_object)
-        if obj_type.model == 'vminterface':
-            return self.assigned_object.virtual_machine
-        if obj_type.model == 'interface':
-            return self.assigned_object.device
-        if obj_type.model == 'vminterface':
-            return self.assigned_object.virtual_machine
-        return None
+        obj = self.assigned_object
+        if isinstance(obj, IPAddress):
+            # The interface the IP address is assigned to, if any
+            obj = obj.assigned_object
+        return getattr(obj, 'parent_object', None)
 
 
     @property
     @property
     def assigned_object_site(self):
     def assigned_object_site(self):
-        return self.assigned_object_parent.site
+        if isinstance(self.assigned_object, VLAN):
+            return self.assigned_object.site
+        if parent := self.assigned_object_parent:
+            return parent.site
+        return None

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

@@ -12,7 +12,7 @@
   "l2vpn:api_list_objects": 14,
   "l2vpn:api_list_objects": 14,
   "l2vpn:list_objects_with_permission": 16,
   "l2vpn:list_objects_with_permission": 16,
   "l2vpntermination:api_list_objects": 15,
   "l2vpntermination:api_list_objects": 15,
-  "l2vpntermination:list_objects_with_permission": 21,
+  "l2vpntermination:list_objects_with_permission": 20,
   "tunnel:api_list_objects": 13,
   "tunnel:api_list_objects": 13,
   "tunnel:list_objects_with_permission": 17,
   "tunnel:list_objects_with_permission": 17,
   "tunnelgroup:api_list_objects": 12,
   "tunnelgroup:api_list_objects": 12,

+ 24 - 5
netbox/vpn/tests/test_api.py

@@ -1,9 +1,11 @@
+import json
+
 from django.urls import reverse
 from django.urls import reverse
 from rest_framework import status
 from rest_framework import status
 
 
 from dcim.choices import InterfaceTypeChoices
 from dcim.choices import InterfaceTypeChoices
 from dcim.models import Interface
 from dcim.models import Interface
-from ipam.models import VLAN
+from ipam.models import VLAN, IPAddress
 from utilities.testing import APITestCase, APIViewTestCases, create_test_device
 from utilities.testing import APITestCase, APIViewTestCases, create_test_device
 from vpn.choices import *
 from vpn.choices import *
 from vpn.models import *
 from vpn.models import *
@@ -676,10 +678,12 @@ class L2VPNTerminationTestCase(APIViewTestCases.APIViewTestCase):
         )
         )
         L2VPN.objects.bulk_create(l2vpns)
         L2VPN.objects.bulk_create(l2vpns)
 
 
+        ip_address = IPAddress.objects.create(address='192.0.2.1/32')
+
         l2vpnterminations = (
         l2vpnterminations = (
             L2VPNTermination(l2vpn=l2vpns[0], assigned_object=vlans[0]),
             L2VPNTermination(l2vpn=l2vpns[0], assigned_object=vlans[0]),
             L2VPNTermination(l2vpn=l2vpns[0], assigned_object=vlans[1]),
             L2VPNTermination(l2vpn=l2vpns[0], assigned_object=vlans[1]),
-            L2VPNTermination(l2vpn=l2vpns[0], assigned_object=vlans[2])
+            L2VPNTermination(l2vpn=l2vpns[1], assigned_object=ip_address)
         )
         )
         L2VPNTermination.objects.bulk_create(l2vpnterminations)
         L2VPNTermination.objects.bulk_create(l2vpnterminations)
 
 
@@ -695,9 +699,10 @@ class L2VPNTerminationTestCase(APIViewTestCases.APIViewTestCase):
                 'assigned_object_id': vlans[4].pk,
                 'assigned_object_id': vlans[4].pk,
             },
             },
             {
             {
-                'l2vpn': l2vpns[0].pk,
-                'assigned_object_type': 'ipam.vlan',
-                'assigned_object_id': vlans[5].pk,
+                # The same IP address may terminate another L2VPN
+                'l2vpn': l2vpns[2].pk,
+                'assigned_object_type': 'ipam.ipaddress',
+                'assigned_object_id': ip_address.pk,
             },
             },
         ]
         ]
 
 
@@ -708,3 +713,17 @@ class L2VPNTerminationTestCase(APIViewTestCases.APIViewTestCase):
         cls.bulk_update_invalid_data = {
         cls.bulk_update_invalid_data = {
             'l2vpn': 99999,
             'l2vpn': 99999,
         }
         }
+
+    def test_graphql_ip_address_l2vpn_terminations_filter(self):
+        """IP addresses can be filtered over GraphQL by the L2VPNs they terminate."""
+        self.add_permissions('ipam.view_ipaddress')
+        IPAddress.objects.create(address='192.0.2.2/32')
+        l2vpn = L2VPN.objects.get(name='L2VPN 2')
+        query = (
+            f'{{ ip_address_list(filters: {{l2vpn_terminations: {{l2vpn_id: "{l2vpn.pk}"}}}}) {{ address }} }}'
+        )
+        response = self.client.post(reverse('graphql'), data={'query': query}, format='json', **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        data = json.loads(response.content)
+        self.assertNotIn('errors', data)
+        self.assertEqual([ip['address'] for ip in data['data']['ip_address_list']], ['192.0.2.1/32'])

+ 26 - 6
netbox/vpn/tests/test_filtersets.py

@@ -900,6 +900,13 @@ class L2VPNTerminationTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
         )
         )
         L2VPN.objects.bulk_create(l2vpns)
         L2VPN.objects.bulk_create(l2vpns)
 
 
+        ip_addresses = (
+            IPAddress(address='192.0.2.1/32', assigned_object=interfaces[0]),
+            IPAddress(address='192.0.2.2/32', assigned_object=vminterfaces[0]),
+            IPAddress(address='192.0.2.3/32'),
+        )
+        IPAddress.objects.bulk_create(ip_addresses)
+
         l2vpnterminations = (
         l2vpnterminations = (
             L2VPNTermination(l2vpn=l2vpns[0], assigned_object=vlans[0]),
             L2VPNTermination(l2vpn=l2vpns[0], assigned_object=vlans[0]),
             L2VPNTermination(l2vpn=l2vpns[1], assigned_object=vlans[1]),
             L2VPNTermination(l2vpn=l2vpns[1], assigned_object=vlans[1]),
@@ -910,6 +917,8 @@ class L2VPNTerminationTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
             L2VPNTermination(l2vpn=l2vpns[0], assigned_object=vminterfaces[0]),
             L2VPNTermination(l2vpn=l2vpns[0], assigned_object=vminterfaces[0]),
             L2VPNTermination(l2vpn=l2vpns[1], assigned_object=vminterfaces[1]),
             L2VPNTermination(l2vpn=l2vpns[1], assigned_object=vminterfaces[1]),
             L2VPNTermination(l2vpn=l2vpns[2], assigned_object=vminterfaces[2]),
             L2VPNTermination(l2vpn=l2vpns[2], assigned_object=vminterfaces[2]),
+            L2VPNTermination(l2vpn=l2vpns[2], assigned_object=ip_addresses[0]),
+            L2VPNTermination(l2vpn=l2vpns[2], assigned_object=ip_addresses[1]),
         )
         )
         L2VPNTermination.objects.bulk_create(l2vpnterminations)
         L2VPNTermination.objects.bulk_create(l2vpnterminations)
 
 
@@ -954,6 +963,17 @@ class L2VPNTerminationTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
         params = {'vlan': ['VLAN 1', 'VLAN 2']}
         params = {'vlan': ['VLAN 1', 'VLAN 2']}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
 
 
+    def test_ipaddress(self):
+        ip_addresses = IPAddress.objects.all()[:2]
+        params = {'ipaddress_id': [ip_addresses[0].pk, ip_addresses[1].pk]}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+        params = {'ipaddress': ['192.0.2.1/32', '192.0.2.2/32']}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+        params = {'ipaddress': ['192.0.2.1', '192.0.2.2']}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+        params = {'ipaddress': ['invalid']}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 0)
+
     def test_vlan_shared_name(self):
     def test_vlan_shared_name(self):
         # A VLAN name shared by several groups should resolve to a single filter value
         # A VLAN name shared by several groups should resolve to a single filter value
         vlan = VLAN.objects.first()
         vlan = VLAN.objects.first()
@@ -965,16 +985,16 @@ class L2VPNTerminationTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
     def test_site(self):
     def test_site(self):
         site = Site.objects.all().first()
         site = Site.objects.all().first()
         params = {'site_id': [site.pk]}
         params = {'site_id': [site.pk]}
-        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 3)
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 4)
         params = {'site': ['site-1']}
         params = {'site': ['site-1']}
-        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 3)
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 4)
 
 
     def test_device(self):
     def test_device(self):
         device = Device.objects.all().first()
         device = Device.objects.all().first()
         params = {'device_id': [device.pk]}
         params = {'device_id': [device.pk]}
-        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 3)
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 4)
         params = {'device': ['Device 1']}
         params = {'device': ['Device 1']}
-        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 3)
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 4)
 
 
     def test_device_shared_name(self):
     def test_device_shared_name(self):
         # A device name shared by several sites should resolve to a single filter value
         # A device name shared by several sites should resolve to a single filter value
@@ -988,9 +1008,9 @@ class L2VPNTerminationTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
     def test_virtual_machine(self):
     def test_virtual_machine(self):
         virtual_machine = VirtualMachine.objects.all().first()
         virtual_machine = VirtualMachine.objects.all().first()
         params = {'virtual_machine_id': [virtual_machine.pk]}
         params = {'virtual_machine_id': [virtual_machine.pk]}
-        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 3)
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 4)
         params = {'virtual_machine': ['Virtual Machine 1']}
         params = {'virtual_machine': ['Virtual Machine 1']}
-        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 3)
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 4)
 
 
     def test_virtual_machine_shared_name(self):
     def test_virtual_machine_shared_name(self):
         # A virtual machine name shared by several clusters should resolve to a single filter value
         # A virtual machine name shared by several clusters should resolve to a single filter value

+ 82 - 0
netbox/vpn/tests/test_forms.py

@@ -0,0 +1,82 @@
+from django.test import TestCase
+
+from dcim.models import Interface
+from ipam.models import VRF, IPAddress
+from utilities.testing import create_test_device
+from vpn.choices import L2VPNTypeChoices
+from vpn.forms import L2VPNTerminationForm, L2VPNTerminationImportForm
+from vpn.models import L2VPN, L2VPNTermination
+
+
+class L2VPNTerminationFormTestCase(TestCase):
+
+    @classmethod
+    def setUpTestData(cls):
+        cls.ip_address = IPAddress.objects.create(address='192.0.2.1/32')
+        cls.l2vpns = (
+            L2VPN.objects.create(name='L2VPN 1', slug='l2vpn-1', type=L2VPNTypeChoices.TYPE_VPLS),
+            L2VPN.objects.create(name='L2VPN 2', slug='l2vpn-2', type=L2VPNTypeChoices.TYPE_VPLS),
+        )
+        L2VPNTermination.objects.create(l2vpn=cls.l2vpns[0], assigned_object=cls.ip_address)
+
+    def test_ipaddress_terminates_another_l2vpn(self):
+        form = L2VPNTerminationForm(data={'l2vpn': self.l2vpns[1].pk, 'ipaddress': self.ip_address.pk})
+        self.assertTrue(form.is_valid(), form.errors)
+
+    def test_duplicate_ipaddress_termination(self):
+        form = L2VPNTerminationForm(data={'l2vpn': self.l2vpns[0].pk, 'ipaddress': self.ip_address.pk})
+        self.assertFalse(form.is_valid())
+        self.assertIn('already terminates', str(form.errors))
+
+
+class L2VPNTerminationImportFormTestCase(TestCase):
+
+    @classmethod
+    def setUpTestData(cls):
+        L2VPN.objects.create(name='L2VPN 1', slug='l2vpn-1', type=L2VPNTypeChoices.TYPE_VPLS)
+
+        # The same address exists globally, in a VRF, and on a device's interface in another VRF
+        cls.vrfs = (
+            VRF.objects.create(name='VRF 1'),
+            VRF.objects.create(name='VRF 2'),
+        )
+        cls.device = create_test_device('Device 1')
+        interface = Interface.objects.create(device=cls.device, name='Interface 1', type='1000baset')
+        cls.ip_addresses = (
+            IPAddress.objects.create(address='192.0.2.1/32'),
+            IPAddress.objects.create(address='192.0.2.1/32', vrf=cls.vrfs[0]),
+            IPAddress.objects.create(address='192.0.2.1/32', vrf=cls.vrfs[1], assigned_object=interface),
+        )
+
+    def test_missing_assigned_object(self):
+        form = L2VPNTerminationImportForm(data={'l2vpn': 'L2VPN 1'}, instance=L2VPNTermination())
+        self.assertFalse(form.is_valid())
+        self.assertIn('must specify an interface, a VLAN, or an IP address', str(form.errors))
+
+    def get_assigned_object(self, data):
+        form = L2VPNTerminationImportForm(data={'l2vpn': 'L2VPN 1', **data}, instance=L2VPNTermination())
+        self.assertTrue(form.is_valid(), form.errors)
+        return form.instance.assigned_object
+
+    def test_ipaddress_ambiguous(self):
+        form = L2VPNTerminationImportForm(
+            data={'l2vpn': 'L2VPN 1', 'ipaddress': '192.0.2.1/32'}, instance=L2VPNTermination()
+        )
+        self.assertFalse(form.is_valid())
+        self.assertIn('ipaddress', form.errors)
+
+    def test_ipaddress_vrf(self):
+        assigned_object = self.get_assigned_object({'ipaddress': '192.0.2.1/32', 'ipaddress_vrf': 'VRF 1'})
+        self.assertEqual(assigned_object, self.ip_addresses[1])
+
+    def test_ipaddress_device(self):
+        assigned_object = self.get_assigned_object({'ipaddress': '192.0.2.1/32', 'device': 'Device 1'})
+        self.assertEqual(assigned_object, self.ip_addresses[2])
+
+    def test_ipaddress_not_on_device(self):
+        form = L2VPNTerminationImportForm(
+            data={'l2vpn': 'L2VPN 1', 'ipaddress': '192.0.2.1/32', 'ipaddress_vrf': 'VRF 1', 'device': 'Device 1'},
+            instance=L2VPNTermination()
+        )
+        self.assertFalse(form.is_valid())
+        self.assertIn('ipaddress', form.errors)

+ 48 - 1
netbox/vpn/tests/test_models.py

@@ -2,7 +2,7 @@ from django.core.exceptions import ValidationError
 from django.test import TestCase
 from django.test import TestCase
 
 
 from dcim.models import Device, DeviceRole, DeviceType, Interface, Manufacturer, Site
 from dcim.models import Device, DeviceRole, DeviceType, Interface, Manufacturer, Site
-from ipam.models import VLAN
+from ipam.models import VLAN, IPAddress
 from vpn.models import *
 from vpn.models import *
 
 
 
 
@@ -77,3 +77,50 @@ class L2VPNTerminationTestCase(TestCase):
         L2VPNTermination.objects.create(l2vpn=l2vpn, assigned_object=vlan)
         L2VPNTermination.objects.create(l2vpn=l2vpn, assigned_object=vlan)
         duplicate = L2VPNTermination(l2vpn=l2vpn, assigned_object=vlan)
         duplicate = L2VPNTermination(l2vpn=l2vpn, assigned_object=vlan)
         self.assertRaises(ValidationError, duplicate.clean)
         self.assertRaises(ValidationError, duplicate.clean)
+
+    def test_ipaddress_terminates_multiple_l2vpns(self):
+        ip_address = IPAddress.objects.create(address='192.0.2.1/32')
+        l2vpns = L2VPN.objects.all()[:2]
+
+        L2VPNTermination.objects.create(l2vpn=l2vpns[0], assigned_object=ip_address)
+        termination = L2VPNTermination(l2vpn=l2vpns[1], assigned_object=ip_address)
+        termination.full_clean()
+        termination.save()
+
+        self.assertEqual(ip_address.l2vpn_terminations.count(), 2)
+
+    def test_duplicate_ipaddress_terminations(self):
+        ip_address = IPAddress.objects.create(address='192.0.2.1/32')
+        l2vpn = L2VPN.objects.first()
+
+        L2VPNTermination.objects.create(l2vpn=l2vpn, assigned_object=ip_address)
+        duplicate = L2VPNTermination(l2vpn=l2vpn, assigned_object=ip_address)
+        self.assertRaises(ValidationError, duplicate.clean)
+
+    def test_ipaddress_termination_parent(self):
+        interface = Interface.objects.first()
+        assigned_ip = IPAddress.objects.create(address='192.0.2.1/32', assigned_object=interface)
+        unassigned_ip = IPAddress.objects.create(address='192.0.2.2/32')
+        l2vpn = L2VPN.objects.first()
+
+        termination = L2VPNTermination.objects.create(l2vpn=l2vpn, assigned_object=assigned_ip)
+        self.assertEqual(termination.assigned_object_parent, interface.device)
+        self.assertEqual(termination.assigned_object_site, interface.device.site)
+
+        termination = L2VPNTermination.objects.create(l2vpn=l2vpn, assigned_object=unassigned_ip)
+        self.assertIsNone(termination.assigned_object_parent)
+        self.assertIsNone(termination.assigned_object_site)
+
+    def test_vlan_termination_site(self):
+        site = Site.objects.first()
+        vlan = VLAN.objects.create(name='VLAN 8', vid=658, site=site)
+        termination = L2VPNTermination.objects.create(l2vpn=L2VPN.objects.first(), assigned_object=vlan)
+        self.assertIsNone(termination.assigned_object_parent)
+        self.assertEqual(termination.assigned_object_site, site)
+
+    def test_delete_ipaddress_deletes_terminations(self):
+        ip_address = IPAddress.objects.create(address='192.0.2.1/32')
+        termination = L2VPNTermination.objects.create(l2vpn=L2VPN.objects.first(), assigned_object=ip_address)
+
+        ip_address.delete()
+        self.assertFalse(L2VPNTermination.objects.filter(pk=termination.pk).exists())

+ 50 - 6
netbox/vpn/tests/test_views.py

@@ -1,7 +1,12 @@
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
+from django.urls import reverse
+
 from dcim.choices import InterfaceTypeChoices
 from dcim.choices import InterfaceTypeChoices
 from dcim.models import Interface
 from dcim.models import Interface
-from ipam.models import VLAN, RouteTarget
-from utilities.testing import ViewTestCases, create_tags, create_test_device
+from ipam.models import VLAN, IPAddress, RouteTarget
+from utilities.testing import ViewTestCases, create_tags, create_test_device, create_test_virtualmachine
+from virtualization.models import VMInterface
 from vpn.choices import *
 from vpn.choices import *
 from vpn.models import *
 from vpn.models import *
 
 
@@ -664,11 +669,13 @@ class L2VPNTerminationTestCase(
             'interface': interface.pk,
             'interface': interface.pk,
         }
         }
 
 
+        IPAddress.objects.create(address='192.0.2.1/32')
+
         cls.csv_data = (
         cls.csv_data = (
-            "l2vpn,vlan",
-            "L2VPN 1,Vlan 4",
-            "L2VPN 1,Vlan 5",
-            "L2VPN 1,Vlan 6",
+            "l2vpn,vlan,ipaddress",
+            "L2VPN 1,Vlan 4,",
+            "L2VPN 1,Vlan 5,",
+            "L2VPN 1,,192.0.2.1/32",
         )
         )
 
 
         cls.csv_update_data = (
         cls.csv_update_data = (
@@ -684,6 +691,43 @@ class L2VPNTerminationTestCase(
     def test_bulk_update_objects_with_permission(self):
     def test_bulk_update_objects_with_permission(self):
         pass
         pass
 
 
+    def test_list_objects_query_count(self):
+        """
+        Listing terminations should not need extra queries for each row to display its parent and site.
+        """
+        self.add_permissions('vpn.view_l2vpntermination')
+        self.user.config.set(
+            'tables.L2VPNTerminationTable.columns',
+            ['l2vpn', 'assigned_object_type', 'assigned_object', 'assigned_object_parent', 'assigned_object_site'],
+            commit=True
+        )
+        device = create_test_device('Device 2')
+        virtual_machine = create_test_virtualmachine('Virtual Machine 1')
+
+        def get_queries(count):
+            l2vpn = L2VPN.objects.create(
+                name=f'L2VPN {count}x', slug=f'l2vpn-{count}x', type=L2VPNTypeChoices.TYPE_VPLS
+            )
+            for i in range(count):
+                interface = Interface.objects.create(device=device, name=f'{count}x {i}', type='1000baset')
+                vminterface = VMInterface.objects.create(virtual_machine=virtual_machine, name=f'{count}x {i}')
+                vlan = VLAN.objects.create(name=f'VLAN {count}x {i}', vid=100 * count + i, site=device.site)
+                for obj in (
+                    interface,
+                    vminterface,
+                    vlan,
+                    IPAddress.objects.create(address=f'198.51.{count}.{i}/32', assigned_object=interface),
+                    IPAddress.objects.create(address=f'203.0.{count}.{i}/32', assigned_object=vminterface),
+                ):
+                    L2VPNTermination.objects.create(l2vpn=l2vpn, assigned_object=obj)
+            with CaptureQueriesContext(connection) as queries:
+                response = self.client.get(f"{reverse('vpn:l2vpntermination_list')}?l2vpn_id={l2vpn.pk}")
+            self.assertHttpStatus(response, 200)
+            self.assertContains(response, device.site.name)
+            return len(queries)
+
+        self.assertEqual(get_queries(1), get_queries(3))
+
     #
     #
     # Custom assertions
     # Custom assertions
     #
     #

+ 18 - 1
netbox/vpn/views.py

@@ -1,6 +1,9 @@
+from django.contrib.contenttypes.prefetch import GenericPrefetch
 from django.utils.translation import gettext_lazy as _
 from django.utils.translation import gettext_lazy as _
 
 
+from dcim.models import Interface
 from extras.ui.panels import CustomFieldsPanel, TagsPanel
 from extras.ui.panels import CustomFieldsPanel, TagsPanel
+from ipam.models import VLAN, IPAddress
 from ipam.tables import RouteTargetTable
 from ipam.tables import RouteTargetTable
 from netbox.object_actions import AddObject, BulkDelete, BulkEdit, BulkExport, BulkImport
 from netbox.object_actions import AddObject, BulkDelete, BulkEdit, BulkExport, BulkImport
 from netbox.ui import actions, layout
 from netbox.ui import actions, layout
@@ -14,6 +17,7 @@ from netbox.ui.panels import (
 from netbox.views import generic
 from netbox.views import generic
 from utilities.query import count_related
 from utilities.query import count_related
 from utilities.views import GetRelatedModelsMixin, register_model_view
 from utilities.views import GetRelatedModelsMixin, register_model_view
+from virtualization.models import VMInterface
 
 
 from . import filtersets, forms, tables
 from . import filtersets, forms, tables
 from .models import *
 from .models import *
@@ -761,7 +765,20 @@ class L2VPNBulkDeleteView(generic.BulkDeleteView):
 
 
 @register_model_view(L2VPNTermination, 'list', path='', detail=False)
 @register_model_view(L2VPNTermination, 'list', path='', detail=False)
 class L2VPNTerminationListView(generic.ObjectListView):
 class L2VPNTerminationListView(generic.ObjectListView):
-    queryset = L2VPNTermination.objects.all()
+    # Fetch each terminating object's parent and site, which the table may display
+    queryset = L2VPNTermination.objects.prefetch_related(
+        GenericPrefetch('assigned_object', [
+            Interface.objects.select_related('device__site'),
+            VMInterface.objects.select_related('virtual_machine__site'),
+            VLAN.objects.select_related('site'),
+            IPAddress.objects.prefetch_related(
+                GenericPrefetch('assigned_object', [
+                    Interface.objects.select_related('device__site'),
+                    VMInterface.objects.select_related('virtual_machine__site'),
+                ])
+            ),
+        ])
+    )
     table = tables.L2VPNTerminationTable
     table = tables.L2VPNTerminationTable
     filterset = filtersets.L2VPNTerminationFilterSet
     filterset = filtersets.L2VPNTerminationFilterSet
     filterset_form = forms.L2VPNTerminationFilterForm
     filterset_form = forms.L2VPNTerminationFilterForm