validators.py 4.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from django.core.exceptions import ValidationError
  2. from django.core.validators import BaseValidator, RegexValidator
  3. from django.utils.translation import gettext_lazy as _
  4. def validate_port_mappings(mappings):
  5. """
  6. Validate a list of service port mappings, i.e. ``protocol/port`` strings such as ``'tcp/80'``.
  7. Ensures each entry is well-formed, uses a known protocol, falls within the permitted port range,
  8. and is not duplicated. Raises a ``ValidationError`` describing the first problem found.
  9. Returns the list in a canonical, normalized form (integer ports, so ``'tcp/080'`` becomes
  10. ``'tcp/80'``, and the protocol lowercased, so ``'TCP/80'`` becomes ``'tcp/80'``); callers should
  11. persist the returned value so every entry path stores identical strings and remains matchable by the
  12. port filters. Protocol matching is case-insensitive, so all paths (REST, CSV import, model form)
  13. accept any case without each having to fold it first. Shared by the model (``ServiceBase.clean()``),
  14. the model form field (``PortMappingField``), the CSV import form, and the REST API serializers so all
  15. paths enforce identical rules.
  16. """
  17. # Imported lazily to avoid a circular import during settings load (this module is imported by
  18. # ipam.models, and ipam.constants pulls in ipam.choices, which reads settings.FIELD_CHOICES).
  19. from ipam.choices import ServiceProtocolChoices
  20. from ipam.constants import SERVICE_PORT_MAX, SERVICE_PORT_MIN
  21. from ipam.utils import split_port_mapping
  22. # A set, since this is consulted once per mapping and a service may define thousands
  23. valid_protocols = set(ServiceProtocolChoices.values())
  24. seen = set()
  25. normalized_mappings = []
  26. for mapping in mappings:
  27. protocol, port = split_port_mapping(mapping)
  28. if not port:
  29. raise ValidationError(
  30. _("Invalid port mapping '{mapping}'. Expected format protocol/port (e.g. tcp/80).").format(
  31. mapping=mapping
  32. )
  33. )
  34. # The error reports the protocol as supplied rather than the folded form.
  35. if (canonical_protocol := protocol.lower()) not in valid_protocols:
  36. raise ValidationError(_("Invalid protocol: {protocol}").format(protocol=protocol))
  37. try:
  38. port_number = int(port)
  39. except ValueError:
  40. raise ValidationError(_("Invalid port number: {port}").format(port=port))
  41. if not SERVICE_PORT_MIN <= port_number <= SERVICE_PORT_MAX:
  42. raise ValidationError(
  43. _("Port {port} is not within the permitted range ({min}-{max}).").format(
  44. port=port_number, min=SERVICE_PORT_MIN, max=SERVICE_PORT_MAX
  45. )
  46. )
  47. # Normalize the port to an integer so e.g. tcp/80 and tcp/080 count as duplicates and are
  48. # stored identically (leaving the raw string would make tcp/080 invisible to the port filter).
  49. normalized = f'{canonical_protocol}/{port_number}'
  50. if normalized in seen:
  51. raise ValidationError(_("Duplicate port mapping: {mapping}").format(mapping=mapping))
  52. seen.add(normalized)
  53. normalized_mappings.append(normalized)
  54. return normalized_mappings
  55. def prefix_validator(prefix):
  56. if prefix.ip != prefix.cidr.ip:
  57. raise ValidationError(
  58. _("{prefix} is not a valid prefix. Did you mean {suggested}?").format(
  59. prefix=prefix, suggested=prefix.cidr
  60. )
  61. )
  62. class MaxPrefixLengthValidator(BaseValidator):
  63. message = _('The prefix length must be less than or equal to %(limit_value)s.')
  64. code = 'max_prefix_length'
  65. def compare(self, a, b):
  66. return a.prefixlen > b
  67. class MinPrefixLengthValidator(BaseValidator):
  68. message = _('The prefix length must be greater than or equal to %(limit_value)s.')
  69. code = 'min_prefix_length'
  70. def compare(self, a, b):
  71. return a.prefixlen < b
  72. DNSValidator = RegexValidator(
  73. regex=r'^([0-9A-Za-z_-]+|\*)(\.[0-9A-Za-z_-]+)*\.?$',
  74. message=_('Only alphanumeric characters, asterisks, hyphens, periods, and underscores are allowed in DNS names'),
  75. code='invalid'
  76. )