about summary refs log tree commit diff
path: root/app/validators/email_mx_validator.rb
blob: 237ca4c7bc8613ae2a2a277d7c8acd0931903e33 (plain) (blame)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# frozen_string_literal: true

require 'resolv'

class EmailMxValidator < ActiveModel::Validator
  def validate(user)
    return if user.email.blank?

    domain = get_domain(user.email)

    if domain.blank?
      user.errors.add(:email, :invalid)
    elsif !on_allowlist?(domain)
      resolved_ips, resolved_domains = resolve_mx(domain)

      if resolved_ips.empty?
        user.errors.add(:email, :unreachable)
      elsif on_blacklist?(resolved_domains, resolved_ips, user.sign_up_ip)
        user.errors.add(:email, :blocked)
      end
    end
  end

  private

  def get_domain(value)
    _, domain = value.split('@', 2)

    return nil if domain.nil?

    TagManager.instance.normalize_domain(domain)
  rescue Addressable::URI::InvalidURIError
    nil
  end

  def on_allowlist?(domain)
    return false if Rails.configuration.x.email_domains_whitelist.blank?

    Rails.configuration.x.email_domains_whitelist.include?(domain)
  end

  def resolve_mx(domain)
    records = []
    ips     = []

    Resolv::DNS.open do |dns|
      dns.timeouts = 5

      records = dns.getresources(domain, Resolv::DNS::Resource::IN::MX).to_a.map { |e| e.exchange.to_s }

      ([domain] + records).uniq.each do |hostname|
        ips.concat(dns.getresources(hostname, Resolv::DNS::Resource::IN::A).to_a.map { |e| e.address.to_s })
        ips.concat(dns.getresources(hostname, Resolv::DNS::Resource::IN::AAAA).to_a.map { |e| e.address.to_s })
      end
    end

    [ips, records]
  end

  def on_blacklist?(domains, resolved_ips, attempt_ip)
    EmailDomainBlock.block?(domains, ips: resolved_ips, attempt_ip: attempt_ip)
  end
end