From af2aefbd7455e3b5840e51d81a2b7992acea1617 Mon Sep 17 00:00:00 2001 From: Sofer Athlan-Guyot Date: Thu, 7 Jan 2016 20:03:57 +0100 Subject: [PATCH] Utility to handle IPv6 address brackets. This add the function normalize_ip_for_uri to the parser. It encloses into brackets any valid IPv6 address thrown at it. Change-Id: I093dd5a4e6294e20761cb3d33373652eeadeac36 Closes-bug: 1531960 --- .../parser/functions/normalize_ip_for_uri.rb | 31 +++++++++++++++++++ spec/functions/normalize_ip_for_uri_spec.rb | 13 ++++++++ 2 files changed, 44 insertions(+) create mode 100644 lib/puppet/parser/functions/normalize_ip_for_uri.rb create mode 100644 spec/functions/normalize_ip_for_uri_spec.rb diff --git a/lib/puppet/parser/functions/normalize_ip_for_uri.rb b/lib/puppet/parser/functions/normalize_ip_for_uri.rb new file mode 100644 index 00000000..c54c26fb --- /dev/null +++ b/lib/puppet/parser/functions/normalize_ip_for_uri.rb @@ -0,0 +1,31 @@ +require 'ipaddr' + +module Puppet::Parser::Functions + newfunction(:normalize_ip_for_uri, + :type => :rvalue, + :arity => 1, + :doc => <<-EOD + Add brackets if the argument is an IPv6 address. + Returns the argument untouched otherwise. + CAUTION: this code "fails" when the user is passing + an IPv6 address with the port in it without the + brackets: 2001::1:8080, to specify address 2001::1 + and port 8080. This code will change it to + [2001::1:8080] as it's a valid ip address. This + shouldn't be an issue in most cases. + EOD + ) do |args| + ip = args[0] + begin + if IPAddr.new(ip).ipv6? + unless ip.match(/\[.+\]/) + Puppet.debug("IP #{ip} is changed to [#{ip}]") + ip = "[#{ip}]" + end + end + rescue ArgumentError => e + # ignore it + end + return ip + end +end diff --git a/spec/functions/normalize_ip_for_uri_spec.rb b/spec/functions/normalize_ip_for_uri_spec.rb new file mode 100644 index 00000000..1b0dc503 --- /dev/null +++ b/spec/functions/normalize_ip_for_uri_spec.rb @@ -0,0 +1,13 @@ +require 'spec_helper' + +describe 'normalize_ip_for_uri' do + it { should run.with_params(false).and_return(false)} + it { should run.with_params('not_an_ip').and_return('not_an_ip')} + it { should run.with_params('127.0.0.1').and_return('127.0.0.1')} + it { should run.with_params('::1').and_return('[::1]')} + it { should run.with_params('[2001::01]').and_return('[2001::01]')} + it do + is_expected.to run.with_params('one', 'two') + .and_raise_error(ArgumentError, /Wrong number of arguments/) + end +end