File: qualified_domain_array_validator.rb

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (49 lines) | stat: -rw-r--r-- 1,551 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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.nil?

    record.errors.add(attribute, _('entries cannot be nil'))
  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