From 52e6632175621463d168f15039abd96e67ff77c7 Mon Sep 17 00:00:00 2001 From: simon lehericey Date: Wed, 3 Apr 2019 14:24:05 +0200 Subject: [PATCH] Add IPService --- app/services/ip_service.rb | 36 +++++++++++++++++++++++ spec/services/ip_service_spec.rb | 49 ++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 app/services/ip_service.rb create mode 100644 spec/services/ip_service_spec.rb diff --git a/app/services/ip_service.rb b/app/services/ip_service.rb new file mode 100644 index 000000000..6ca7fdc5e --- /dev/null +++ b/app/services/ip_service.rb @@ -0,0 +1,36 @@ +class IPService + class << self + def ip_trusted?(ip) + ip_address = parse_address(ip) + + if ip_address.nil? + false + elsif trusted_networks.present? + trusted_networks.any? { |network| network.include?(ip_address) } + else + false + end + end + + private + + def trusted_networks + if ENV['TRUSTED_NETWORKS'].present? + ENV['TRUSTED_NETWORKS'] + .split + .map { |string| parse_address(string) } + .compact + else + [] + end + end + + def parse_address(address) + begin + IPAddr.new(address) + rescue + nil + end + end + end +end diff --git a/spec/services/ip_service_spec.rb b/spec/services/ip_service_spec.rb new file mode 100644 index 000000000..c9c1d1641 --- /dev/null +++ b/spec/services/ip_service_spec.rb @@ -0,0 +1,49 @@ +require 'spec_helper' + +describe IPService do + describe '.ip_trusted?' do + subject { IPService.ip_trusted?(ip) } + + context 'when the ip is nil' do + let(:ip) { nil } + + it { is_expected.to be(false) } + end + + context 'when the ip is defined' do + let(:ip) { '192.168.1.10' } + + context 'when it belongs to a trusted network' do + before do + ENV['TRUSTED_NETWORKS'] = '10.0.0.0/8 192.168.0.0/16 bad_network' + end + + it { is_expected.to be(true) } + end + + context 'when it does not belong to a trusted network' do + before do + ENV['TRUSTED_NETWORKS'] = '10.0.0.0/8' + end + + it { is_expected.to be(false) } + end + end + + context 'when a trusted network is defined' do + before { ENV['TRUSTED_NETWORKS'] = '10.0.0.0/8' } + + context 'when the ip is nil' do + let(:ip) { nil } + + it { is_expected.to be(false) } + end + + context 'when the ip is badly formatted' do + let(:ip) { 'yop' } + + it { is_expected.to be(false) } + end + end + end +end