gitlab-org--gitlab-foss/app/validators/qualified_domain_array_validator.rb
Reuben Pereira 42ecbcad10 Add validator for qualidied domain array
- Validate that the entries contain no unicode, html tags and are not
larger than 255 characters.
2019-07-23 19:47:17 +00:00

49 lines
1.5 KiB
Ruby

# frozen_string_literal: true
# QualifiedDomainArrayValidator
#
# Custom validator for URL hosts/'qualified domains' (FQDNs, ex: gitlab.com, sub.example.com).
# This does not check if the domain actually exists. It only checks if it is a
# valid domain string.
#
# Example:
#
# class ApplicationSetting < ApplicationRecord
# validates :outbound_local_requests_whitelist, qualified_domain_array: true
# end
#
class QualifiedDomainArrayValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
validate_value_present(record, attribute, value)
validate_host_length(record, attribute, value)
validate_idna_encoding(record, attribute, value)
validate_sanitization(record, attribute, value)
end
private
def validate_value_present(record, attribute, value)
return unless value.blank?
record.errors.add(attribute, _('entries cannot be blank'))
end
def validate_host_length(record, attribute, value)
return unless value&.any? { |entry| entry.size > 255 }
record.errors.add(attribute, _('entries cannot be larger than 255 characters'))
end
def validate_idna_encoding(record, attribute, value)
return if value&.all?(&:ascii_only?)
record.errors.add(attribute, _('unicode domains should use IDNA encoding'))
end
def validate_sanitization(record, attribute, value)
sanitizer = Rails::Html::FullSanitizer.new
return unless value&.any? { |str| sanitizer.sanitize(str) != str }
record.errors.add(attribute, _('entries cannot contain HTML tags'))
end
end