services.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. from django.contrib.contenttypes.models import ContentType
  2. from django.core.exceptions import ValidationError as DjangoValidationError
  3. from django.utils.translation import gettext_lazy as _
  4. from rest_framework import serializers
  5. from ipam.choices import *
  6. from ipam.constants import SERVICE_ASSIGNMENT_MODELS, SERVICE_PORT_MAX, SERVICE_PORT_MIN
  7. from ipam.models import IPAddress, Service, ServiceTemplate
  8. from ipam.utils import legacy_protocol_and_ports
  9. from ipam.validators import validate_port_mappings
  10. from netbox.api.fields import ChoiceField, ContentTypeField, SerializedPKRelatedField
  11. from netbox.api.gfk_fields import GFKSerializerField
  12. from netbox.api.serializers import PrimaryModelSerializer
  13. from .ip import IPAddressSerializer
  14. __all__ = (
  15. 'ServiceSerializer',
  16. 'ServiceTemplateSerializer',
  17. )
  18. class PortMappingsField(serializers.ListField):
  19. """
  20. A service's port mappings as a flat list of ``protocol/port`` strings (e.g. ``["tcp/80", "udp/53"]``),
  21. matching how they are stored. Each entry is validated (and normalized) on write.
  22. """
  23. child = serializers.CharField()
  24. def to_internal_value(self, data):
  25. mappings = super().to_internal_value(data)
  26. try:
  27. return validate_port_mappings(mappings)
  28. except DjangoValidationError as exc:
  29. raise serializers.ValidationError(exc.messages)
  30. class PortMappingsSerializerMixin(serializers.Serializer):
  31. """
  32. Shared port-mapping handling for the Service and ServiceTemplate serializers, including backward
  33. compatibility for the legacy single-protocol ``protocol``/``ports`` representation.
  34. Read: alongside the ``port_mappings`` list, a service that uses a single protocol also reports the
  35. legacy ``protocol`` and ``ports`` fields; a multi-protocol service reports ``null`` for both (it
  36. cannot be expressed in the old single-protocol format).
  37. Write: either format is accepted. When the legacy ``protocol``/``ports`` pair is supplied (and
  38. ``port_mappings`` is not), it is translated into ``port_mappings``. Supplying both together is
  39. accepted only when the legacy fields agree with what ``port_mappings`` implies (e.g. a full-object
  40. round-trip that echoes back the read representation); a genuine conflict is rejected as ambiguous.
  41. Subclassing ``serializers.Serializer`` (rather than a plain mixin) lets DRF's metaclass collect the
  42. fields declared here into the inheriting serializers.
  43. """
  44. port_mappings = PortMappingsField(required=False)
  45. # Legacy single-protocol fields, retained for backward compatibility. They are read straight off the
  46. # model's protocol/ports properties (which share these field names), so DRF sources them directly —
  47. # matching the {"value", "label"} shape every other choice field uses. default=None applies only on
  48. # write, where validate() consumes them.
  49. # TODO: Remove protocol/ports in v5.0 along with the legacy handling in validate().
  50. protocol = ChoiceField(
  51. choices=ServiceProtocolChoices,
  52. required=False,
  53. allow_null=True,
  54. default=None,
  55. help_text=_("Deprecated; use port_mappings. Reported only for single-protocol services."),
  56. )
  57. ports = serializers.ListField(
  58. child=serializers.IntegerField(min_value=SERVICE_PORT_MIN, max_value=SERVICE_PORT_MAX),
  59. required=False,
  60. allow_null=True,
  61. default=None,
  62. help_text=_("Deprecated; use port_mappings. Reported only for single-protocol services."),
  63. )
  64. def validate(self, data):
  65. # Consume the legacy fields and translate them into port_mappings *before* calling super(),
  66. # which instantiates the model (via full_clean()) and would choke on these now-nonexistent kwargs.
  67. legacy_protocol = data.pop('protocol', None)
  68. legacy_ports = data.pop('ports', None)
  69. # protocol/ports carry default=None, so an omitted field arrives as None; an explicitly-supplied
  70. # value (including a falsy ports=[]) is a legacy write and must be handled — checking `is not None`
  71. # rather than truthiness so an intentional empty list isn't silently dropped.
  72. if legacy_protocol is not None or legacy_ports is not None:
  73. # `port_mappings` and `protocol`/`ports` are mutually exclusive as *representations*, but a
  74. # full-object round-trip (GET then PUT/PATCH) legitimately resubmits port_mappings alongside
  75. # the legacy protocol/ports the read emitted. Only reject a genuine *conflict*: when the legacy
  76. # fields agree with what port_mappings already implies they're merely redundant, so accept the
  77. # request and let port_mappings win.
  78. if 'port_mappings' in data:
  79. expected_protocol, expected_ports = legacy_protocol_and_ports(data['port_mappings'])
  80. protocol_agrees = legacy_protocol is None or legacy_protocol == expected_protocol
  81. ports_agree = legacy_ports is None or sorted(legacy_ports) == (expected_ports or [])
  82. if not (protocol_agrees and ports_agree):
  83. raise serializers.ValidationError(_(
  84. "Specify either 'port_mappings' or the deprecated 'protocol'/'ports' fields, not both."
  85. ))
  86. return super().validate(data)
  87. # The old API accepted an empty ports list (the ArrayField had no minimum length); the new
  88. # model requires at least one mapping. Report that directly — both fields may have been
  89. # supplied, so the "both are required" message below would be misleading.
  90. if legacy_ports == []:
  91. raise serializers.ValidationError(
  92. {'ports': _("At least one port mapping is required.")}
  93. )
  94. # The legacy API let either field be updated on its own (e.g. a PATCH that adjusts only the
  95. # port list). Preserve that by backfilling the omitted field from the instance's current
  96. # single-protocol representation.
  97. if not (legacy_protocol and legacy_ports):
  98. legacy_protocol = legacy_protocol or (self.instance.protocol if self.instance else None)
  99. if legacy_ports is None:
  100. legacy_ports = self.instance.ports if self.instance else None
  101. # If the pair still can't be resolved — a create, or an existing multi-protocol service that
  102. # has no single-protocol form — the request can't be expressed in the legacy format.
  103. if not (legacy_protocol and legacy_ports):
  104. raise serializers.ValidationError(_(
  105. "Both 'protocol' and 'ports' are required when writing via the deprecated legacy "
  106. "format; use port_mappings instead."
  107. ))
  108. try:
  109. data['port_mappings'] = validate_port_mappings(
  110. [f'{legacy_protocol}/{port}' for port in legacy_ports]
  111. )
  112. except DjangoValidationError as exc:
  113. raise serializers.ValidationError({'ports': exc.messages})
  114. return super().validate(data)
  115. class ServiceTemplateSerializer(PortMappingsSerializerMixin, PrimaryModelSerializer):
  116. class Meta:
  117. model = ServiceTemplate
  118. fields = [
  119. 'id', 'url', 'display_url', 'display', 'name', 'port_mappings', 'protocol', 'ports', 'description',
  120. 'owner', 'comments', 'tags', 'custom_fields', 'created', 'last_updated',
  121. ]
  122. brief_fields = ('id', 'url', 'display', 'name', 'port_mappings', 'description')
  123. class ServiceSerializer(PortMappingsSerializerMixin, PrimaryModelSerializer):
  124. ipaddresses = SerializedPKRelatedField(
  125. queryset=IPAddress.objects.all(),
  126. serializer=IPAddressSerializer,
  127. nested=True,
  128. required=False,
  129. many=True
  130. )
  131. parent_object_type = ContentTypeField(
  132. queryset=ContentType.objects.filter(SERVICE_ASSIGNMENT_MODELS)
  133. )
  134. parent = GFKSerializerField(read_only=True)
  135. class Meta:
  136. model = Service
  137. fields = [
  138. 'id', 'url', 'display_url', 'display', 'parent_object_type', 'parent_object_id', 'parent', 'name',
  139. 'port_mappings', 'protocol', 'ports', 'ipaddresses', 'description', 'owner', 'comments', 'tags',
  140. 'custom_fields', 'created', 'last_updated',
  141. ]
  142. brief_fields = ('id', 'url', 'display', 'name', 'port_mappings', 'description')