class Castle::IPs::Extract

used for extraction of ip from the request

Constants

DEFAULT

ordered list of ip headers for ip extraction

list of header which are used with proxy depth setting

Public Class Methods

new(headers, config = nil) click to toggle source

@param headers [Hash] @param config [Castle::Configuration, Castle::SingletonConfiguration, nil]

# File lib/castle/ips/extract.rb, line 18
def initialize(headers, config = nil)
  config ||= Castle.config
  @headers = headers
  @ip_headers = config.ip_headers.empty? ? DEFAULT : config.ip_headers
  @proxies = config.trusted_proxies + Castle::Configuration::TRUSTED_PROXIES
  @trust_proxy_chain = config.trust_proxy_chain
  @trusted_proxy_depth = config.trusted_proxy_depth
end

Public Instance Methods

call() click to toggle source

Order of headers:

.... list of headers defined by ip_headers
X-Forwarded-For
Remote-Addr

@return [String]

# File lib/castle/ips/extract.rb, line 32
def call
  all_ips = []

  @ip_headers.each do |ip_header|
    ips = ips_from(ip_header)
    ip_value = remove_proxies(ips)

    return ip_value if ip_value

    all_ips.push(*ips)
  end

  # fallback to first listed ip
  all_ips.first
end

Private Instance Methods

ips_from(header) click to toggle source

@param header [String] @return [Array<String>]

# File lib/castle/ips/extract.rb, line 66
def ips_from(header)
  value = @headers[header]

  return [] unless value

  ips = value.strip.split(/[,\s]+/)

  limit_proxy_depth(ips, header)
end
limit_proxy_depth(ips, ip_header) click to toggle source

@param ips [Array<String>] @param ip_header [String] @return [Array<String>]

# File lib/castle/ips/extract.rb, line 79
def limit_proxy_depth(ips, ip_header)
  ips.pop(@trusted_proxy_depth) if DEPTH_RELATED.include?(ip_header)

  ips
end
proxy?(ip) click to toggle source

@param ip [String] @return [Boolean]

# File lib/castle/ips/extract.rb, line 60
def proxy?(ip)
  @proxies.any? { |proxy| proxy.match(ip) }
end
remove_proxies(ips) click to toggle source

@param ips [Array<String>] @return [Array<String>]

# File lib/castle/ips/extract.rb, line 52
def remove_proxies(ips)
  return ips.first if @trust_proxy_chain

  ips.reject { |ip| proxy?(ip) }.last
end