diff options
author | Reuben Pereira <rpereira@gitlab.com> | 2019-07-23 19:47:17 +0000 |
---|---|---|
committer | Mayra Cabrera <mcabrera@gitlab.com> | 2019-07-23 19:47:17 +0000 |
commit | 42ecbcad108aa44beb279421c300024d17a360cd (patch) | |
tree | 1e913053608ef43ee9aa949441f6a9943beff914 /app/validators | |
parent | ab97168e4f03994967cc6c8a38aa910f24cf1d7f (diff) | |
download | gitlab-ce-42ecbcad108aa44beb279421c300024d17a360cd.tar.gz |
Add validator for qualidied domain array
- Validate that the entries contain no unicode, html tags and are not
larger than 255 characters.
Diffstat (limited to 'app/validators')
-rw-r--r-- | app/validators/qualified_domain_array_validator.rb | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/app/validators/qualified_domain_array_validator.rb b/app/validators/qualified_domain_array_validator.rb new file mode 100644 index 00000000000..986c146a9db --- /dev/null +++ b/app/validators/qualified_domain_array_validator.rb @@ -0,0 +1,49 @@ +# 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 |