diff options
author | Jay Mundrawala <jdmundrawala@gmail.com> | 2015-03-09 21:50:59 -0700 |
---|---|---|
committer | Jay Mundrawala <jdmundrawala@gmail.com> | 2015-03-20 14:38:04 -0700 |
commit | ef351de3c33cb1bf03667cd50bcc9ea680708584 (patch) | |
tree | 348b6a17c8a0e2c62229ad796ce7015670e4fb4f | |
parent | c290d11a22b3f90f0e21bccc9e919f4057db42f9 (diff) | |
download | chef-ef351de3c33cb1bf03667cd50bcc9ea680708584.tar.gz |
Escape strings when they contain a special character
-rw-r--r-- | lib/chef/mixin/powershell_type_coercions.rb | 31 | ||||
-rw-r--r-- | spec/unit/mixin/powershell_type_coercions_spec.rb | 11 |
2 files changed, 32 insertions, 10 deletions
diff --git a/lib/chef/mixin/powershell_type_coercions.rb b/lib/chef/mixin/powershell_type_coercions.rb index 1f216176c1..e7e3dede63 100644 --- a/lib/chef/mixin/powershell_type_coercions.rb +++ b/lib/chef/mixin/powershell_type_coercions.rb @@ -45,23 +45,34 @@ class Chef "@(#{translated.join(',')})" end + def unsafe?(s) + ["'", '#', '`', '"'].any? do |x| + s.include? x + end + end + + def safe_string(s) + # do we need to worry about binary data? + if unsafe?(s) + encoded_str = Base64.strict_encode64(s.encode("UTF-8")) + "([System.Text.Encoding]::UTF8.GetString("\ + "[System.Convert]::FromBase64String('#{encoded_str}')"\ + "))" + else + "'#{s}'" + end + end + def translate_type(value) translation = type_coercions[value.class] - translated_value = nil if translation - should_quote = translation[:single_quoted] - translated_value = translation[:type].call(value) + translation[:type].call(value) elsif value.respond_to? :to_psobject - should_quote = false - translated_value = "(#{value.to_psobject})" + "(#{value.to_psobject})" else - should_quote = true - translated_value = value.to_s + safe_string(value.to_s) end - - translated_value = "'#{translated_value}'" if should_quote - translated_value end end diff --git a/spec/unit/mixin/powershell_type_coercions_spec.rb b/spec/unit/mixin/powershell_type_coercions_spec.rb index 0019c9b74e..988c3926c1 100644 --- a/spec/unit/mixin/powershell_type_coercions_spec.rb +++ b/spec/unit/mixin/powershell_type_coercions_spec.rb @@ -18,6 +18,7 @@ require 'spec_helper' require 'chef/mixin/powershell_type_coercions' +require 'base64' class Chef::PSTypeTester include Chef::Mixin::PowershellTypeCoercions @@ -27,6 +28,16 @@ describe Chef::Mixin::PowershellTypeCoercions do let (:test_class) { Chef::PSTypeTester.new } describe '#translate_type' do + it 'should single quote a string' do + expect(test_class.translate_type('foo')).to eq("'foo'") + end + + ["'", '"', '#', '`'].each do |c| + it "should base64 encode a string that contains #{c}" do + expect(test_class.translate_type("#{c}")).to match(Base64.strict_encode64(c)) + end + end + it 'should not quote an integer' do expect(test_class.translate_type(123)).to eq('123') end |