chef-config-16.12.3/0000755000175100017510000000000014034030210013045 5ustar pravipravichef-config-16.12.3/Rakefile0000644000175100017510000000053514034030210014515 0ustar pravipravirequire "bundler/gem_tasks" task default: :spec begin require "rspec/core/rake_task" desc "Run standard specs" RSpec::Core::RakeTask.new(:spec) do |t| t.verbose = false t.pattern = FileList["spec/**/*_spec.rb"] end rescue LoadError STDERR.puts "\n*** RSpec not available. (sudo) gem install rspec to run unit tests. ***\n\n" end chef-config-16.12.3/spec/0000755000175100017510000000000014034030210013777 5ustar pravipravichef-config-16.12.3/spec/unit/0000755000175100017510000000000014034030210014756 5ustar pravipravichef-config-16.12.3/spec/unit/path_helper_spec.rb0000644000175100017510000003362314034030210020617 0ustar pravipravi# # Author:: Bryan McLellan # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "chef-config/path_helper" require "spec_helper" RSpec.describe ChefConfig::PathHelper do let(:path_helper) { described_class } context "common functionality" do context "join" do it "joins starting with '' resolve to absolute paths" do expect(path_helper.join("", "a", "b")).to eq("#{path_helper.path_separator}a#{path_helper.path_separator}b") end it "joins ending with '' add a / to the end" do expect(path_helper.join("a", "b", "")).to eq("a#{path_helper.path_separator}b#{path_helper.path_separator}") end end context "dirname" do it "dirname('abc') is '.'" do expect(path_helper.dirname("abc")).to eq(".") end it "dirname('/') is '/'" do expect(path_helper.dirname(path_helper.path_separator)).to eq(path_helper.path_separator) end it "dirname('a/b/c') is 'a/b'" do expect(path_helper.dirname(path_helper.join("a", "b", "c"))).to eq(path_helper.join("a", "b")) end it "dirname('a/b/c/') is 'a/b'" do expect(path_helper.dirname(path_helper.join("a", "b", "c", ""))).to eq(path_helper.join("a", "b")) end it "dirname('/a/b/c') is '/a/b'" do expect(path_helper.dirname(path_helper.join("", "a", "b", "c"))).to eq(path_helper.join("", "a", "b")) end end end context "forcing windows/non-windows" do context "forcing windows" do it "path_separator is \\" do expect(path_helper.path_separator(windows: true)).to eq('\\') end context "platform-specific #join behavior" do it "joins components on Windows when some end with unix separators" do expected = "C:\\foo\\bar\\baz" expect(path_helper.join('C:\\foo/', "bar", "baz", windows: true)).to eq(expected) end it "joins components when some end with separators" do expected = "C:\\foo\\bar\\baz" expect(path_helper.join('C:\\foo\\', "bar", "baz", windows: true)).to eq(expected) end it "joins components when some end and start with separators" do expected = "C:\\foo\\bar\\baz" expect(path_helper.join('C:\\foo\\', "bar/", "/baz", windows: true)).to eq(expected) end it "joins components that don't end in separators" do expected = "C:\\foo\\bar\\baz" expect(path_helper.join('C:\\foo', "bar", "baz", windows: true)).to eq(expected) end end it "cleanpath changes slashes into backslashes and leaves backslashes alone" do expect(path_helper.cleanpath('/a/b\\c/d/', windows: true)).to eq('\\a\\b\\c\\d') end it "cleanpath does not remove leading double backslash" do expect(path_helper.cleanpath('\\\\a/b\\c/d/', windows: true)).to eq('\\\\a\\b\\c\\d') end end context "forcing unix" do it "path_separator is /" do expect(path_helper.path_separator(windows: false)).to eq("/") end it "cleanpath removes extra slashes alone" do expect(path_helper.cleanpath("/a///b/c/d/", windows: false)).to eq("/a/b/c/d") end context "platform-specific #join behavior" do it "joins components when some end with separators" do expected = "/foo/bar/baz" expect(path_helper.join("/foo/", "bar", "baz", windows: false)).to eq(expected) end it "joins components when some end and start with separators" do expected = "/foo/bar/baz" expect(path_helper.join("/foo/", "bar/", "/baz", windows: false)).to eq(expected) end it "joins components that don't end in separators" do expected = "/foo/bar/baz" expect(path_helper.join("/foo", "bar", "baz", windows: false)).to eq(expected) end end it "cleanpath changes backslashes into slashes and leaves slashes alone" do expect(path_helper.cleanpath('/a/b\\c/d/', windows: false)).to eq("/a/b/c/d") end it "cleanpath does not remove leading double backslash" do expect(path_helper.cleanpath('\\\\a/b\\c/d/', windows: false)).to eq("//a/b/c/d") end end end context "on windows", :windows_only do before(:each) do allow(ChefUtils).to receive(:windows?).and_return(true) end it "path_separator is \\" do expect(path_helper.path_separator).to eq('\\') end context "platform-specific #join behavior" do it "joins components on Windows when some end with unix separators" do expected = "C:\\foo\\bar\\baz" expect(path_helper.join('C:\\foo/', "bar", "baz")).to eq(expected) end it "joins components when some end with separators" do expected = "C:\\foo\\bar\\baz" expect(path_helper.join('C:\\foo\\', "bar", "baz")).to eq(expected) end it "joins components when some end and start with separators" do expected = "C:\\foo\\bar\\baz" expect(path_helper.join('C:\\foo\\', "bar/", "/baz")).to eq(expected) end it "joins components that don't end in separators" do expected = "C:\\foo\\bar\\baz" expect(path_helper.join('C:\\foo', "bar", "baz")).to eq(expected) end end it "cleanpath changes slashes into backslashes and leaves backslashes alone" do expect(path_helper.cleanpath('/a/b\\c/d/')).to eq('\\a\\b\\c\\d') end it "cleanpath does not remove leading double backslash" do expect(path_helper.cleanpath('\\\\a/b\\c/d/')).to eq('\\\\a\\b\\c\\d') end end context "on unix", :unix_only do before(:each) do allow(ChefUtils).to receive(:windows?).and_return(false) end it "path_separator is /" do expect(path_helper.path_separator).to eq("/") end it "cleanpath removes extra slashes alone" do expect(path_helper.cleanpath("/a///b/c/d/")).to eq("/a/b/c/d") end context "platform-specific #join behavior" do it "joins components when some end with separators" do expected = path_helper.cleanpath("/foo/bar/baz") expect(path_helper.join("/foo/", "bar", "baz")).to eq(expected) end it "joins components when some end and start with separators" do expected = path_helper.cleanpath("/foo/bar/baz") expect(path_helper.join("/foo/", "bar/", "/baz")).to eq(expected) end it "joins components that don't end in separators" do expected = path_helper.cleanpath("/foo/bar/baz") expect(path_helper.join("/foo", "bar", "baz")).to eq(expected) end end it "cleanpath changes backslashes into slashes and leaves slashes alone" do expect(path_helper.cleanpath('/a/b\\c/d/', windows: false)).to eq("/a/b/c/d") end # NOTE: this seems a bit weird to me, but this is just the way Pathname#cleanpath works it "cleanpath does not remove leading double backslash" do expect(path_helper.cleanpath('\\\\a/b\\c/d/')).to eq("//a/b/c/d") end end context "validate_path" do context "on windows" do before(:each) do # pass by default allow(ChefUtils).to receive(:windows?).and_return(true) allow(path_helper).to receive(:printable?).and_return(true) allow(path_helper).to receive(:windows_max_length_exceeded?).and_return(false) end it "returns the path if the path passes the tests" do expect(path_helper.validate_path("C:\\ThisIsRigged")).to eql("C:\\ThisIsRigged") end it "does not raise an error if everything looks great" do expect { path_helper.validate_path("C:\\cool path\\dude.exe") }.not_to raise_error end it "raises an error if the path has invalid characters" do allow(path_helper).to receive(:printable?).and_return(false) expect { path_helper.validate_path("Newline!\n") }.to raise_error(ChefConfig::InvalidPath) end it "Adds the \\\\?\\ prefix if the path exceeds MAX_LENGTH and does not have it" do long_path = "C:\\" + "a" * 250 + "\\" + "b" * 250 prefixed_long_path = "\\\\?\\" + long_path allow(path_helper).to receive(:windows_max_length_exceeded?).and_return(true) expect(path_helper.validate_path(long_path)).to eql(prefixed_long_path) end end end context "windows_max_length_exceeded?" do it "returns true if the path is too long (259 + NUL) for the API" do expect(path_helper.windows_max_length_exceeded?("C:\\" + "a" * 250 + "\\" + "b" * 6)).to be_truthy end it "returns false if the path is not too long (259 + NUL) for the standard API" do expect(path_helper.windows_max_length_exceeded?("C:\\" + "a" * 250 + "\\" + "b" * 5)).to be_falsey end it "returns false if the path is over 259 characters but uses the \\\\?\\ prefix" do expect(path_helper.windows_max_length_exceeded?("\\\\?\\C:\\" + "a" * 250 + "\\" + "b" * 250)).to be_falsey end end context "printable?" do it "returns true if the string contains no non-printable characters" do expect(path_helper.printable?("C:\\Program Files (x86)\\Microsoft Office\\Files.lst")).to be_truthy end it "returns true when given 'abc' in unicode" do expect(path_helper.printable?("\u0061\u0062\u0063")).to be_truthy end it "returns true when given japanese unicode" do expect(path_helper.printable?("\uff86\uff87\uff88")).to be_truthy end it "returns false if the string contains a non-printable character" do expect(path_helper.printable?("\my files\work\notes.txt")).to be_falsey end # This isn't necessarily a requirement, but here to be explicit about functionality. it "returns false if the string contains a newline or tab" do expect(path_helper.printable?("\tThere's no way,\n\t *no* way,\n\t that you came from my loins.\n")).to be_falsey end end context "canonical_path" do context "on windows", :windows_only do it "returns an absolute path with backslashes instead of slashes" do expect(path_helper.canonical_path("\\\\?\\C:/windows/win.ini")).to eq("\\\\?\\c:\\windows\\win.ini") end it "adds the \\\\?\\ prefix if it is missing" do expect(path_helper.canonical_path("C:/windows/win.ini")).to eq("\\\\?\\c:\\windows\\win.ini") end it "returns a lowercase path" do expect(path_helper.canonical_path("\\\\?\\C:\\CASE\\INSENSITIVE")).to eq("\\\\?\\c:\\case\\insensitive") end end context "not on windows", :unix_only do it "returns a canonical path" do expect(path_helper.canonical_path("/etc//apache.d/sites-enabled/../sites-available/default")).to eq("/etc/apache.d/sites-available/default") end end end context "paths_eql?" do it "returns true if the paths are the same" do allow(path_helper).to receive(:canonical_path).with("bandit", windows: ChefUtils.windows?).and_return("c:/bandit/bandit") allow(path_helper).to receive(:canonical_path).with("../bandit/bandit", windows: ChefUtils.windows?).and_return("c:/bandit/bandit") expect(path_helper.paths_eql?("bandit", "../bandit/bandit")).to be_truthy end it "returns false if the paths are different" do allow(path_helper).to receive(:canonical_path).with("bandit", windows: ChefUtils.windows?).and_return("c:/Bo/Bandit") allow(path_helper).to receive(:canonical_path).with("../bandit/bandit", windows: ChefUtils.windows?).and_return("c:/bandit/bandit") expect(path_helper.paths_eql?("bandit", "../bandit/bandit")).to be_falsey end end context "escape_glob" do it "escapes characters reserved by glob" do path = "C:\\this\\*path\\[needs]\\escaping?" escaped_path = "C:\\\\this\\\\\\*path\\\\\\[needs\\]\\\\escaping\\?" expect(path_helper.escape_glob(path, windows: true)).to eq(escaped_path) end context "when given more than one argument" do it "joins, cleanpaths, and escapes characters reserved by glob" do args = ["this/*path", "[needs]", "escaping?"] escaped_path = if ChefUtils.windows? "this\\\\\\*path\\\\\\[needs\\]\\\\escaping\\?" else "this/\\*path/\\[needs\\]/escaping\\?" end expect(path_helper.escape_glob(*args)).to eq(escaped_path) end end end context "escape_glob_dir" do it "escapes characters reserved by glob without using backslashes for path separators" do path = "C:/this/*path/[needs]/escaping?" escaped_path = "C:/this/\\*path/\\[needs\\]/escaping\\?" expect(path_helper.escape_glob_dir(path)).to eq(escaped_path) end context "when given more than one argument" do it "joins, cleanpaths, and escapes characters reserved by glob" do args = ["this/*path", "[needs]", "escaping?"] escaped_path = "this/\\*path/\\[needs\\]/escaping\\?" expect(path_helper).to receive(:join).with(*args).and_call_original expect(path_helper.escape_glob_dir(*args)).to eq(escaped_path) end end end context "all_homes" do before do stub_const("ENV", env) allow(ChefUtils).to receive(:windows?).and_return(is_windows) end context "on windows" do let (:is_windows) { true } end context "on unix" do let (:is_windows) { false } context "when HOME is not set" do let (:env) { {} } it "returns an empty array" do expect(path_helper.all_homes).to eq([]) end end end end end chef-config-16.12.3/spec/unit/config_spec.rb0000644000175100017510000014122114034030210017563 0ustar pravipravi# # Author:: Adam Jacob () # Author:: Kyle Goodwin () # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "spec_helper" require "chef-config/config" RSpec.describe ChefConfig::Config do before(:each) do ChefConfig::Config.reset # By default, treat deprecation warnings as errors in tests. ChefConfig::Config.treat_deprecation_warnings_as_errors(true) # Set environment variable so the setting persists in child processes ENV["CHEF_TREAT_DEPRECATION_WARNINGS_AS_ERRORS"] = "1" end describe "config attribute writer: chef_server_url" do before do ChefConfig::Config.chef_server_url = "https://junglist.gen.nz" end it "sets the server url" do expect(ChefConfig::Config.chef_server_url).to eq("https://junglist.gen.nz") end context "when the url has a leading space" do before do ChefConfig::Config.chef_server_url = " https://junglist.gen.nz" end it "strips the space from the url when setting" do expect(ChefConfig::Config.chef_server_url).to eq("https://junglist.gen.nz") end end context "when the url is a frozen string" do before do ChefConfig::Config.chef_server_url = " https://junglist.gen.nz".freeze end it "strips the space from the url when setting without raising an error" do expect(ChefConfig::Config.chef_server_url).to eq("https://junglist.gen.nz") end end context "when the url is invalid" do it "raises an exception" do expect { ChefConfig::Config.chef_server_url = "127.0.0.1" }.to raise_error(ChefConfig::ConfigurationError) end end end describe "parsing arbitrary config from the CLI" do def apply_config described_class.apply_extra_config_options(extra_config_options) end context "when no arbitrary config is given" do let(:extra_config_options) { nil } it "succeeds" do expect { apply_config }.to_not raise_error end end context "when given a simple string option" do let(:extra_config_options) { [ "node_name=bobotclown" ] } it "applies the string option" do apply_config expect(described_class[:node_name]).to eq("bobotclown") end end context "when given a blank value" do let(:extra_config_options) { [ "http_retries=" ] } it "sets the value to nil" do # ensure the value is actually changed in the test described_class[:http_retries] = 55 apply_config expect(described_class[:http_retries]).to eq(nil) end end context "when given spaces between `key = value`" do let(:extra_config_options) { [ "node_name = bobo" ] } it "handles the extra spaces and applies the config option" do apply_config expect(described_class[:node_name]).to eq("bobo") end end context "when given an integer value" do let(:extra_config_options) { [ "http_retries=9000" ] } it "converts to a numeric type and applies the config option" do apply_config expect(described_class[:http_retries]).to eq(9000) end end context "when given a boolean" do let(:extra_config_options) { [ "boolean_thing=true" ] } it "converts to a boolean type and applies the config option" do apply_config expect(described_class[:boolean_thing]).to eq(true) end end context "when given input that is not in key=value form" do let(:extra_config_options) { [ "http_retries:9000" ] } it "raises UnparsableConfigOption" do message = 'Unparsable config option "http_retries:9000"' expect { apply_config }.to raise_error(ChefConfig::UnparsableConfigOption, message) end end describe "expand relative paths" do let(:current_directory) { Dir.pwd } context "when given cookbook_path" do let(:extra_config_options) { [ "cookbook_path=cookbooks/" ] } it "expanded cookbook_path" do apply_config expect(described_class[:cookbook_path]).to eq("#{current_directory}/cookbooks") end end context "when passes multiple config options" do let(:extra_config_options) { ["data_bag_path=data_bags/", "cookbook_path=cookbooks", "chef_repo_path=."] } it "expanded paths" do apply_config expect(described_class[:data_bag_path]).to eq("#{current_directory}/data_bags") expect(described_class[:cookbook_path]).to eq("#{current_directory}/cookbooks") expect(described_class[:chef_repo_path]).to eq(current_directory) end end context "when passes multiple cookbook_paths in config options" do let(:extra_config_options) { ["cookbook_path=[first_cookbook, second_cookbooks]"] } it "expanded paths" do apply_config expect(described_class[:cookbook_path]).to eq(["#{current_directory}/first_cookbook", "#{current_directory}/second_cookbooks"]) end end end end describe "when configuring formatters" do # if TTY and not(force-logger) # formatter = configured formatter or default formatter # formatter goes to STDOUT/ERR # if log file is writeable # log level is configured level or info # log location is file # else # log level is warn # log location is STDERR # end # elsif not(TTY) and force formatter # formatter = configured formatter or default formatter # if log_location specified # formatter goes to log_location # else # formatter goes to STDOUT/ERR # end # else # formatter = "null" # log_location = configured-value or default # log_level = info or default # end # it "has an empty list of formatters by default" do expect(ChefConfig::Config.formatters).to eq([]) end it "configures a formatter with a short name" do ChefConfig::Config.add_formatter(:doc) expect(ChefConfig::Config.formatters).to eq([[:doc, nil]]) end it "configures a formatter with a file output" do ChefConfig::Config.add_formatter(:doc, "/var/log/formatter.log") expect(ChefConfig::Config.formatters).to eq([[:doc, "/var/log/formatter.log"]]) end end describe "#var_chef_path" do let (:dirname) { ChefUtils::Dist::Infra::DIR_SUFFIX } context "on unix", :unix_only do it "var_chef_dir is /var/chef" do expect(ChefConfig::Config.var_chef_dir).to eql("/var/#{dirname}") end it "var_root_dir is /var" do expect(ChefConfig::Config.var_root_dir).to eql("/var") end it "etc_chef_dir is /etc/chef" do expect(ChefConfig::Config.etc_chef_dir).to eql("/etc/#{dirname}") end end context "on windows", :windows_only do it "var_chef_dir is C:\\chef" do expect(ChefConfig::Config.var_chef_dir).to eql("C:\\#{dirname}") end it "var_root_dir is C:\\" do expect(ChefConfig::Config.var_root_dir).to eql("C:\\") end it "etc_chef_dir is C:\\chef" do expect(ChefConfig::Config.etc_chef_dir).to eql("C:\\#{dirname}") end end context "when forced to unix" do it "var_chef_dir is /var/chef" do expect(ChefConfig::Config.var_chef_dir(windows: false)).to eql("/var/#{dirname}") end it "var_root_dir is /var" do expect(ChefConfig::Config.var_root_dir(windows: false)).to eql("/var") end it "etc_chef_dir is /etc/chef" do expect(ChefConfig::Config.etc_chef_dir(windows: false)).to eql("/etc/#{dirname}") end end context "when forced to windows" do it "var_chef_dir is C:\\chef" do expect(ChefConfig::Config.var_chef_dir(windows: true)).to eql("C:\\#{dirname}") end it "var_root_dir is C:\\" do expect(ChefConfig::Config.var_root_dir(windows: true)).to eql("C:\\") end it "etc_chef_dir is C:\\chef" do expect(ChefConfig::Config.etc_chef_dir(windows: true)).to eql("C:\\#{dirname}") end end end [ false, true ].each do |is_windows| context "On #{is_windows ? "Windows" : "Unix"}" do before :each do allow(ChefUtils).to receive(:windows?).and_return(is_windows) end describe "class method: windows_installation_drive" do before do allow(File).to receive(:expand_path).and_return("D:/Path/To/Executable") end if is_windows it "should return D: on a windows system" do expect(ChefConfig::Config.windows_installation_drive).to eq("D:") end else it "should return nil on a non-windows system" do expect(ChefConfig::Config.windows_installation_drive).to eq(nil) end end end describe "class method: platform_specific_path" do before do allow(ChefConfig::Config).to receive(:env).and_return({ "SYSTEMDRIVE" => "C:" }) end if is_windows path = "/etc/chef/cookbooks" context "a windows system with chef installed on C: drive" do before do allow(ChefConfig::Config).to receive(:windows_installation_drive).and_return("C:") end it "should return a windows path rooted in C:" do expect(ChefConfig::Config.platform_specific_path(path)).to eq("C:\\chef\\cookbooks") end end context "a windows system with chef installed on D: drive" do before do allow(ChefConfig::Config).to receive(:windows_installation_drive).and_return("D:") end it "should return a windows path rooted in D:" do expect(ChefConfig::Config.platform_specific_path(path)).to eq("D:\\chef\\cookbooks") end end else it "should return given path on non-windows systems" do path = "/etc/chef/cookbooks" expect(ChefConfig::Config.platform_specific_path(path)).to eq("/etc/chef/cookbooks") end end end describe "default values" do let(:system_drive) { ChefConfig::Config.env["SYSTEMDRIVE"] } if is_windows let :primary_cache_path do if is_windows "#{system_drive}\\chef" else "/var/chef" end end let :secondary_cache_path do if is_windows "#{ChefConfig::Config[:user_home]}\\.chef" else "#{ChefConfig::Config[:user_home]}/.chef" end end before do if is_windows allow(ChefConfig::Config).to receive(:env).and_return({ "SYSTEMDRIVE" => "C:" }) ChefConfig::Config[:user_home] = 'C:\Users\charlie' else ChefConfig::Config[:user_home] = "/Users/charlie" end allow(ChefConfig::Config).to receive(:path_accessible?).and_return(false) end describe "ChefConfig::Config[:client_key]" do let(:path_to_client_key) { ChefConfig::Config.etc_chef_dir + ChefConfig::PathHelper.path_separator } it "sets the default path to the client key" do expect(ChefConfig::Config.client_key).to eq(path_to_client_key + "client.pem") end context "when target mode is enabled" do let(:target_mode_host) { "fluffy.kittens.org" } before do ChefConfig::Config.target_mode.enabled = true ChefConfig::Config.target_mode.host = target_mode_host end it "sets the default path to the client key with the target host name" do expect(ChefConfig::Config.client_key).to eq(path_to_client_key + target_mode_host + ChefConfig::PathHelper.path_separator + "client.pem") end end context "when local mode is enabled" do before { ChefConfig::Config[:local_mode] = true } it "returns nil" do expect(ChefConfig::Config.client_key).to be_nil end end end describe "ChefConfig::Config[:fips]" do let(:fips_enabled) { false } before(:all) do @original_env = ENV.to_hash end after(:all) do ENV.clear ENV.update(@original_env) end before(:each) do ENV["CHEF_FIPS"] = nil allow(ChefConfig).to receive(:fips?).and_return(fips_enabled) end it "returns false when no environment is set and not enabled on system" do expect(ChefConfig::Config[:fips]).to eq(false) end context "when ENV['CHEF_FIPS'] is empty" do before do ENV["CHEF_FIPS"] = "" end it "returns false" do expect(ChefConfig::Config[:fips]).to eq(false) end end context "when ENV['CHEF_FIPS'] is set" do before do ENV["CHEF_FIPS"] = "1" end it "returns true" do expect(ChefConfig::Config[:fips]).to eq(true) end end context "when fips is enabled on system" do let(:fips_enabled) { true } it "returns true" do expect(ChefConfig::Config[:fips]).to eq(true) end end end describe "ChefConfig::Config[:chef_server_root]" do context "when chef_server_url isn't set manually" do it "returns the default of 'https://localhost:443'" do expect(ChefConfig::Config[:chef_server_root]).to eq("https://localhost:443") end end context "when chef_server_url matches '../organizations/*' without a trailing slash" do before do ChefConfig::Config[:chef_server_url] = "https://example.com/organizations/myorg" end it "returns the full URL without /organizations/*" do expect(ChefConfig::Config[:chef_server_root]).to eq("https://example.com") end end context "when chef_server_url matches '../organizations/*' with a trailing slash" do before do ChefConfig::Config[:chef_server_url] = "https://example.com/organizations/myorg/" end it "returns the full URL without /organizations/*" do expect(ChefConfig::Config[:chef_server_root]).to eq("https://example.com") end end context "when chef_server_url matches '..organizations..' but not '../organizations/*'" do before do ChefConfig::Config[:chef_server_url] = "https://organizations.com/organizations" end it "returns the full URL without any modifications" do expect(ChefConfig::Config[:chef_server_root]).to eq(ChefConfig::Config[:chef_server_url]) end end context "when chef_server_url is a standard URL without the string organization(s)" do before do ChefConfig::Config[:chef_server_url] = "https://example.com/some_other_string" end it "returns the full URL without any modifications" do expect(ChefConfig::Config[:chef_server_root]).to eq(ChefConfig::Config[:chef_server_url]) end end end describe "ChefConfig::Config[:cache_path]" do let(:target_mode_host) { "fluffy.kittens.org" } let(:target_mode_primary_cache_path) { ChefUtils.windows? ? "#{primary_cache_path}\\#{target_mode_host}" : "#{primary_cache_path}/#{target_mode_host}" } let(:target_mode_secondary_cache_path) { ChefUtils.windows? ? "#{secondary_cache_path}\\#{target_mode_host}" : "#{secondary_cache_path}/#{target_mode_host}" } before do if is_windows allow(File).to receive(:expand_path).and_return("#{system_drive}/Path/To/Executable") end end context "when /var/chef exists and is accessible" do before do allow(ChefConfig::Config).to receive(:path_accessible?).with(ChefConfig::Config.var_chef_dir).and_return(true) end it "defaults to /var/chef" do expect(ChefConfig::Config[:cache_path]).to eq(primary_cache_path) end context "and target mode is enabled" do it "cache path includes the target host name" do ChefConfig::Config.target_mode.enabled = true ChefConfig::Config.target_mode.host = target_mode_host expect(ChefConfig::Config[:cache_path]).to eq(target_mode_primary_cache_path) end end end context "when /var/chef does not exist and /var is accessible" do it "defaults to /var/chef" do allow(File).to receive(:exists?).with(ChefConfig::Config.var_chef_dir).and_return(false) allow(ChefConfig::Config).to receive(:path_accessible?).with(ChefConfig::Config.var_root_dir).and_return(true) expect(ChefConfig::Config[:cache_path]).to eq(primary_cache_path) end end context "when /var/chef does not exist and /var is not accessible" do it "defaults to $HOME/.chef" do allow(File).to receive(:exists?).with(ChefConfig::Config.var_chef_dir).and_return(false) allow(ChefConfig::Config).to receive(:path_accessible?).with(ChefConfig::Config.var_root_dir).and_return(false) expect(ChefConfig::Config[:cache_path]).to eq(secondary_cache_path) end end context "when /var/chef exists and is not accessible" do before do allow(File).to receive(:exists?).with(ChefConfig::Config.var_chef_dir).and_return(true) allow(File).to receive(:readable?).with(ChefConfig::Config.var_chef_dir).and_return(true) allow(File).to receive(:writable?).with(ChefConfig::Config.var_chef_dir).and_return(false) end it "defaults to $HOME/.chef" do expect(ChefConfig::Config[:cache_path]).to eq(secondary_cache_path) end context "and target mode is enabled" do it "cache path defaults to $HOME/.chef with the target host name" do ChefConfig::Config.target_mode.enabled = true ChefConfig::Config.target_mode.host = target_mode_host expect(ChefConfig::Config[:cache_path]).to eq(target_mode_secondary_cache_path) end end end context "when chef is running in local mode" do before do ChefConfig::Config.local_mode = true end context "and config_dir is /a/b/c" do before do ChefConfig::Config.config_dir ChefConfig::PathHelper.cleanpath("/a/b/c") end it "cache_path is /a/b/c/local-mode-cache" do expect(ChefConfig::Config.cache_path).to eq(ChefConfig::PathHelper.cleanpath("/a/b/c/local-mode-cache")) end end context "and config_dir is /a/b/c/" do before do ChefConfig::Config.config_dir ChefConfig::PathHelper.cleanpath("/a/b/c/") end it "cache_path is /a/b/c/local-mode-cache" do expect(ChefConfig::Config.cache_path).to eq(ChefConfig::PathHelper.cleanpath("/a/b/c/local-mode-cache")) end end end end it "ChefConfig::Config[:stream_execute_output] defaults to false" do expect(ChefConfig::Config[:stream_execute_output]).to eq(false) end it "ChefConfig::Config[:show_download_progress] defaults to false" do expect(ChefConfig::Config[:show_download_progress]).to eq(false) end it "ChefConfig::Config[:download_progress_interval] defaults to every 10%" do expect(ChefConfig::Config[:download_progress_interval]).to eq(10) end it "ChefConfig::Config[:file_backup_path] defaults to /var/chef/backup" do allow(ChefConfig::Config).to receive(:cache_path).and_return(primary_cache_path) backup_path = is_windows ? "#{primary_cache_path}\\backup" : "#{primary_cache_path}/backup" expect(ChefConfig::Config[:file_backup_path]).to eq(backup_path) end it "ChefConfig::Config[:ssl_verify_mode] defaults to :verify_peer" do expect(ChefConfig::Config[:ssl_verify_mode]).to eq(:verify_peer) end it "ChefConfig::Config[:ssl_ca_path] defaults to nil" do expect(ChefConfig::Config[:ssl_ca_path]).to be_nil end describe "ChefConfig::Config[:repo_mode]" do context "when local mode is enabled" do before { ChefConfig::Config[:local_mode] = true } it "defaults to 'hosted_everything'" do expect(ChefConfig::Config[:repo_mode]).to eq("hosted_everything") end context "and osc_compat is enabled" do before { ChefConfig::Config.chef_zero.osc_compat = true } it "defaults to 'everything'" do expect(ChefConfig::Config[:repo_mode]).to eq("everything") end end end context "when local mode is not enabled" do context "and the chef_server_url is multi-tenant" do before { ChefConfig::Config[:chef_server_url] = "https://chef.example/organizations/example" } it "defaults to 'hosted_everything'" do expect(ChefConfig::Config[:repo_mode]).to eq("hosted_everything") end end context "and the chef_server_url is not multi-tenant" do before { ChefConfig::Config[:chef_server_url] = "https://chef.example/" } it "defaults to 'everything'" do expect(ChefConfig::Config[:repo_mode]).to eq("everything") end end end end describe "ChefConfig::Config[:chef_repo_path]" do context "when cookbook_path is set to a single path" do before { ChefConfig::Config[:cookbook_path] = "/home/anne/repo/cookbooks" } it "is set to a path one directory up from the cookbook_path" do expected = File.expand_path("/home/anne/repo") expect(ChefConfig::Config[:chef_repo_path]).to eq(expected) end end context "when cookbook_path is set to multiple paths" do before do ChefConfig::Config[:cookbook_path] = [ "/home/anne/repo/cookbooks", "/home/anne/other_repo/cookbooks", ] end it "is set to an Array of paths one directory up from the cookbook_paths" do expected = [ "/home/anne/repo", "/home/anne/other_repo"].map { |p| File.expand_path(p) } expect(ChefConfig::Config[:chef_repo_path]).to eq(expected) end end context "when cookbook_path is not set but cookbook_artifact_path is set" do before do ChefConfig::Config[:cookbook_path] = nil ChefConfig::Config[:cookbook_artifact_path] = "/home/roxie/repo/cookbook_artifacts" end it "is set to a path one directory up from the cookbook_artifact_path" do expected = File.expand_path("/home/roxie/repo") expect(ChefConfig::Config[:chef_repo_path]).to eq(expected) end end context "when cookbook_path is not set" do before { ChefConfig::Config[:cookbook_path] = nil } it "is set to the cache_path" do expect(ChefConfig::Config[:chef_repo_path]).to eq(ChefConfig::Config[:cache_path]) end end end # On Windows, we'll detect an omnibus build and set this to the # cacert.pem included in the package, but it's nil if you're on Windows # w/o omnibus (e.g., doing development on Windows, custom build, etc.) unless is_windows it "ChefConfig::Config[:ssl_ca_file] defaults to nil" do expect(ChefConfig::Config[:ssl_ca_file]).to be_nil end end it "ChefConfig::Config[:data_bag_path] defaults to /var/chef/data_bags" do allow(ChefConfig::Config).to receive(:cache_path).and_return(primary_cache_path) data_bag_path = is_windows ? "#{primary_cache_path}\\data_bags" : "#{primary_cache_path}/data_bags" expect(ChefConfig::Config[:data_bag_path]).to eq(data_bag_path) end it "ChefConfig::Config[:environment_path] defaults to /var/chef/environments" do allow(ChefConfig::Config).to receive(:cache_path).and_return(primary_cache_path) environment_path = is_windows ? "#{primary_cache_path}\\environments" : "#{primary_cache_path}/environments" expect(ChefConfig::Config[:environment_path]).to eq(environment_path) end it "ChefConfig::Config[:cookbook_artifact_path] defaults to /var/chef/cookbook_artifacts" do allow(ChefConfig::Config).to receive(:cache_path).and_return(primary_cache_path) environment_path = is_windows ? "#{primary_cache_path}\\cookbook_artifacts" : "#{primary_cache_path}/cookbook_artifacts" expect(ChefConfig::Config[:cookbook_artifact_path]).to eq(environment_path) end describe "setting the config dir" do context "when the config file is given with a relative path" do before do ChefConfig::Config.config_file = "client.rb" end it "expands the path when determining config_dir" do # config_dir goes through ChefConfig::PathHelper.canonical_path, which # downcases on windows because the FS is case insensitive, so we # have to downcase expected and actual to make the tests work. expect(ChefConfig::Config.config_dir.downcase).to eq(ChefConfig::PathHelper.cleanpath(Dir.pwd).downcase) end it "does not set derived paths at FS root" do ChefConfig::Config.local_mode = true expect(ChefConfig::Config.cache_path.downcase).to eq(ChefConfig::PathHelper.cleanpath(File.join(Dir.pwd, "local-mode-cache")).downcase) end end context "when the config file is /etc/chef/client.rb" do before do config_location = ChefConfig::PathHelper.cleanpath(ChefConfig::PathHelper.join(ChefConfig::Config.etc_chef_dir, "client.rb")).downcase allow(File).to receive(:absolute_path).with(config_location).and_return(config_location) ChefConfig::Config.config_file = config_location end it "config_dir is /etc/chef" do expect(ChefConfig::Config.config_dir).to eq(ChefConfig::Config.etc_chef_dir.downcase) end context "and chef is running in local mode" do before do ChefConfig::Config.local_mode = true end it "config_dir is /etc/chef" do expect(ChefConfig::Config.config_dir).to eq(ChefConfig::Config.etc_chef_dir.downcase) end end context "when config_dir is set to /other/config/dir/" do before do ChefConfig::Config.config_dir = ChefConfig::PathHelper.cleanpath("/other/config/dir/") end it "yields the explicit value" do expect(ChefConfig::Config.config_dir).to eq(ChefConfig::PathHelper.cleanpath("/other/config/dir/")) end end end context "when the user's home dir is /home/charlie/" do before do ChefConfig::Config.user_home = "/home/charlie/" end it "config_dir is /home/charlie/.chef/" do expect(ChefConfig::Config.config_dir).to eq(ChefConfig::PathHelper.join(ChefConfig::PathHelper.cleanpath("/home/charlie/"), ".chef", "")) end context "and chef is running in local mode" do before do ChefConfig::Config.local_mode = true end it "config_dir is /home/charlie/.chef/" do expect(ChefConfig::Config.config_dir).to eq(ChefConfig::PathHelper.join(ChefConfig::PathHelper.cleanpath("/home/charlie/"), ".chef", "")) end end end if is_windows context "when the user's home dir is windows specific" do before do ChefConfig::Config.user_home = ChefConfig::PathHelper.cleanpath("/home/charlie/") end it "config_dir is with backslashes" do expect(ChefConfig::Config.config_dir).to eq(ChefConfig::PathHelper.join(ChefConfig::PathHelper.cleanpath("/home/charlie/"), ".chef", "")) end context "and chef is running in local mode" do before do ChefConfig::Config.local_mode = true end it "config_dir is with backslashes" do expect(ChefConfig::Config.config_dir).to eq(ChefConfig::PathHelper.join(ChefConfig::PathHelper.cleanpath("/home/charlie/"), ".chef", "")) end end end end end if is_windows describe "finding the windows embedded dir" do let(:default_config_location) { "c:/opscode/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/config.rb" } let(:alternate_install_location) { "c:/my/alternate/install/place/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/config.rb" } let(:non_omnibus_location) { "c:/my/dev/stuff/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/config.rb" } let(:default_ca_file) { "c:/opscode/chef/embedded/ssl/certs/cacert.pem" } it "finds the embedded dir in the default location" do allow(ChefConfig::Config).to receive(:_this_file).and_return(default_config_location) expect(ChefConfig::Config.embedded_dir).to eq("c:/opscode/chef/embedded") end it "finds the embedded dir in a custom install location" do allow(ChefConfig::Config).to receive(:_this_file).and_return(alternate_install_location) expect(ChefConfig::Config.embedded_dir).to eq("c:/my/alternate/install/place/chef/embedded") end it "doesn't error when not in an omnibus install" do allow(ChefConfig::Config).to receive(:_this_file).and_return(non_omnibus_location) expect(ChefConfig::Config.embedded_dir).to be_nil end it "sets the ssl_ca_cert path if the cert file is available" do allow(ChefConfig::Config).to receive(:_this_file).and_return(default_config_location) allow(File).to receive(:exist?).with(default_ca_file).and_return(true) expect(ChefConfig::Config.ssl_ca_file).to eq(default_ca_file) end end end end describe "ChefConfig::Config[:user_home]" do it "should set when HOME is provided" do expected = ChefConfig::PathHelper.cleanpath("/home/kitten") allow(ChefConfig::PathHelper).to receive(:home).and_return(expected) expect(ChefConfig::Config[:user_home]).to eq(expected) end it "falls back to the current working directory when HOME and USERPROFILE is not set" do allow(ChefConfig::PathHelper).to receive(:home).and_return(nil) expect(ChefConfig::Config[:user_home]).to eq(Dir.pwd) end end describe "ChefConfig::Config[:encrypted_data_bag_secret]" do let(:db_secret_default_path) { ChefConfig::PathHelper.cleanpath("#{ChefConfig::Config.etc_chef_dir}/encrypted_data_bag_secret") } before do allow(File).to receive(:exist?).with(db_secret_default_path).and_return(secret_exists) end context "/etc/chef/encrypted_data_bag_secret exists" do let(:secret_exists) { true } it "sets the value to /etc/chef/encrypted_data_bag_secret" do expect(ChefConfig::Config[:encrypted_data_bag_secret]).to eq db_secret_default_path end end context "/etc/chef/encrypted_data_bag_secret does not exist" do let(:secret_exists) { false } it "sets the value to nil" do expect(ChefConfig::Config[:encrypted_data_bag_secret]).to be_nil end end end describe "ChefConfig::Config[:event_handlers]" do it "sets a event_handlers to an empty array by default" do expect(ChefConfig::Config[:event_handlers]).to eq([]) end it "should be able to add custom handlers" do o = Object.new ChefConfig::Config[:event_handlers] << o expect(ChefConfig::Config[:event_handlers]).to be_include(o) end end describe "ChefConfig::Config[:user_valid_regex]" do context "on a platform that is not Windows" do it "allows one letter usernames" do any_match = ChefConfig::Config[:user_valid_regex].any? { |regex| regex.match("a") } expect(any_match).to be_truthy end end end describe "ChefConfig::Config[:internal_locale]" do let(:shell_out) do cmd = instance_double("Mixlib::ShellOut", exitstatus: 0, stdout: locales, error!: nil) allow(cmd).to receive(:run_command).and_return(cmd) cmd end let(:locales) { locale_array.join("\n") } before do allow(Mixlib::ShellOut).to receive(:new).with("locale -a").and_return(shell_out) end shared_examples_for "a suitable locale" do it "returns an English UTF-8 locale" do expect(ChefConfig.logger).to_not receive(:warn).with(/Please install an English UTF-8 locale for Chef Infra Client to use/) expect(ChefConfig.logger).to_not receive(:trace).with(/Defaulting to locale en_US.UTF-8 on Windows/) expect(ChefConfig.logger).to_not receive(:trace).with(/No usable locale -a command found/) expect(ChefConfig::Config.guess_internal_locale).to eq expected_locale end end context "when the result includes 'C.UTF-8'" do include_examples "a suitable locale" do let(:locale_array) { [expected_locale, "en_US.UTF-8"] } let(:expected_locale) { "C.UTF-8" } end end context "when the result includes 'en_US.UTF-8'" do include_examples "a suitable locale" do let(:locale_array) { ["en_CA.UTF-8", expected_locale, "en_NZ.UTF-8"] } let(:expected_locale) { "en_US.UTF-8" } end end context "when the result includes 'en_US.utf8'" do include_examples "a suitable locale" do let(:locale_array) { ["en_CA.utf8", "en_US.utf8", "en_NZ.utf8"] } let(:expected_locale) { "en_US.UTF-8" } end end context "when the result includes 'en.UTF-8'" do include_examples "a suitable locale" do let(:locale_array) { ["en.ISO8859-1", expected_locale] } let(:expected_locale) { "en.UTF-8" } end end context "when the result includes 'en_*.UTF-8'" do include_examples "a suitable locale" do let(:locale_array) { [expected_locale, "en_CA.UTF-8", "en_GB.UTF-8"] } let(:expected_locale) { "en_AU.UTF-8" } end end context "when the result includes 'en_*.utf8'" do include_examples "a suitable locale" do let(:locale_array) { ["en_AU.utf8", "en_CA.utf8", "en_GB.utf8"] } let(:expected_locale) { "en_AU.UTF-8" } end end context "when the result does not include 'en_*.UTF-8'" do let(:locale_array) { ["af_ZA", "af_ZA.ISO8859-1", "af_ZA.ISO8859-15", "af_ZA.UTF-8"] } it "should fall back to C locale" do expect(ChefConfig.logger).to receive(:warn).with("Please install an English UTF-8 locale for Chef Infra Client to use, falling back to C locale and disabling UTF-8 support.") expect(ChefConfig::Config.guess_internal_locale).to eq "C" end end context "on error" do let(:locale_array) { [] } let(:shell_out_cmd) { instance_double("Mixlib::ShellOut") } before do allow(Mixlib::ShellOut).to receive(:new).and_return(shell_out_cmd) allow(shell_out_cmd).to receive(:run_command) allow(shell_out_cmd).to receive(:error!).and_raise(Mixlib::ShellOut::ShellCommandFailed, "this is an error") end it "should default to 'en_US.UTF-8'" do if is_windows expect(ChefConfig.logger).to receive(:trace).with("Defaulting to locale en_US.UTF-8 on Windows, until it matters that we do something else.") else expect(ChefConfig.logger).to receive(:trace).with("No usable locale -a command found, assuming you have en_US.UTF-8 installed.") end expect(ChefConfig::Config.guess_internal_locale).to eq "en_US.UTF-8" end end end end end describe "export_proxies" do before(:all) do @original_env = ENV.to_hash ENV["http_proxy"] = nil ENV["HTTP_PROXY"] = nil ENV["https_proxy"] = nil ENV["HTTPS_PROXY"] = nil ENV["ftp_proxy"] = nil ENV["FTP_PROXY"] = nil ENV["no_proxy"] = nil ENV["NO_PROXY"] = nil end after(:all) do ENV.clear ENV.update(@original_env) end let(:http_proxy) { "http://localhost:7979" } let(:https_proxy) { "https://localhost:7979" } let(:ftp_proxy) { "ftp://localhost:7979" } let(:proxy_user) { "http_user" } let(:proxy_pass) { "http_pass" } context "when http_proxy, proxy_pass and proxy_user are set" do before do ChefConfig::Config.http_proxy = http_proxy ChefConfig::Config.http_proxy_user = proxy_user ChefConfig::Config.http_proxy_pass = proxy_pass end it "exports ENV['http_proxy']" do expect(ENV).to receive(:[]=).with("http_proxy", "http://http_user:http_pass@localhost:7979") expect(ENV).to receive(:[]=).with("HTTP_PROXY", "http://http_user:http_pass@localhost:7979") ChefConfig::Config.export_proxies end end context "when https_proxy, proxy_pass and proxy_user are set" do before do ChefConfig::Config.https_proxy = https_proxy ChefConfig::Config.https_proxy_user = proxy_user ChefConfig::Config.https_proxy_pass = proxy_pass end it "exports ENV['https_proxy']" do expect(ENV).to receive(:[]=).with("https_proxy", "https://http_user:http_pass@localhost:7979") expect(ENV).to receive(:[]=).with("HTTPS_PROXY", "https://http_user:http_pass@localhost:7979") ChefConfig::Config.export_proxies end end context "when ftp_proxy, proxy_pass and proxy_user are set" do before do ChefConfig::Config.ftp_proxy = ftp_proxy ChefConfig::Config.ftp_proxy_user = proxy_user ChefConfig::Config.ftp_proxy_pass = proxy_pass end it "exports ENV['ftp_proxy']" do expect(ENV).to receive(:[]=).with("ftp_proxy", "ftp://http_user:http_pass@localhost:7979") expect(ENV).to receive(:[]=).with("FTP_PROXY", "ftp://http_user:http_pass@localhost:7979") ChefConfig::Config.export_proxies end end shared_examples "no user pass" do it "does not populate the user or password" do expect(ENV).to receive(:[]=).with("http_proxy", "http://localhost:7979") expect(ENV).to receive(:[]=).with("HTTP_PROXY", "http://localhost:7979") ChefConfig::Config.export_proxies end end context "when proxy_pass and proxy_user are passed as empty strings" do before do ChefConfig::Config.http_proxy = http_proxy ChefConfig::Config.http_proxy_user = "" ChefConfig::Config.http_proxy_pass = proxy_pass end include_examples "no user pass" end context "when proxy_pass and proxy_user are not provided" do before do ChefConfig::Config.http_proxy = http_proxy end include_examples "no user pass" end context "when the proxy is provided without a scheme" do before do ChefConfig::Config.http_proxy = "localhost:1111" end it "automatically adds the scheme to the proxy url" do expect(ENV).to receive(:[]=).with("http_proxy", "http://localhost:1111") expect(ENV).to receive(:[]=).with("HTTP_PROXY", "http://localhost:1111") ChefConfig::Config.export_proxies end end shared_examples "no export" do it "does not export any proxy settings" do ChefConfig::Config.export_proxies expect(ENV["http_proxy"]).to eq(nil) expect(ENV["https_proxy"]).to eq(nil) expect(ENV["ftp_proxy"]).to eq(nil) expect(ENV["no_proxy"]).to eq(nil) end end context "when nothing is set" do include_examples "no export" end context "when all the users and passwords are set but no proxies are set" do before do ChefConfig::Config.http_proxy_user = proxy_user ChefConfig::Config.http_proxy_pass = proxy_pass ChefConfig::Config.https_proxy_user = proxy_user ChefConfig::Config.https_proxy_pass = proxy_pass ChefConfig::Config.ftp_proxy_user = proxy_user ChefConfig::Config.ftp_proxy_pass = proxy_pass end include_examples "no export" end context "no_proxy is set" do before do ChefConfig::Config.no_proxy = "localhost" end it "exports ENV['no_proxy']" do expect(ENV).to receive(:[]=).with("no_proxy", "localhost") expect(ENV).to receive(:[]=).with("NO_PROXY", "localhost") ChefConfig::Config.export_proxies end end end describe "proxy_uri" do subject(:proxy_uri) { described_class.proxy_uri(scheme, host, port) } let(:env) { {} } let(:scheme) { "http" } let(:host) { "test.example.com" } let(:port) { 8080 } let(:proxy) { "#{proxy_prefix}#{proxy_host}:#{proxy_port}" } let(:proxy_prefix) { "http://" } let(:proxy_host) { "proxy.mycorp.com" } let(:proxy_port) { 8080 } before do stub_const("ENV", env) end shared_examples_for "a proxy uri" do it "contains the host" do expect(proxy_uri.host).to eq(proxy_host) end it "contains the port" do expect(proxy_uri.port).to eq(proxy_port) end end context "when the config setting is normalized (does not contain the scheme)" do include_examples "a proxy uri" do let(:proxy_prefix) { "" } let(:env) do { "#{scheme}_proxy" => proxy, "no_proxy" => nil, } end end end context "when the proxy is set by the environment" do include_examples "a proxy uri" do let(:scheme) { "https" } let(:env) do { "https_proxy" => "https://jane_username:opensesame@proxy.mycorp.com:8080", } end end end context "when an empty proxy is set by the environment" do let(:env) do { "https_proxy" => "", } end it "does not fail with URI parse exception" do expect { proxy_uri }.to_not raise_error end end context "when no_proxy is set" do context "when no_proxy is the exact host" do let(:env) do { "http_proxy" => proxy, "no_proxy" => host, } end it { is_expected.to eq nil } end context "when no_proxy includes the same domain with a wildcard" do let(:env) do { "http_proxy" => proxy, "no_proxy" => "*.example.com", } end it { is_expected.to eq nil } end context "when no_proxy is included on a list" do let(:env) do { "http_proxy" => proxy, "no_proxy" => "chef.io,getchef.com,opscode.com,test.example.com", } end it { is_expected.to eq nil } end context "when no_proxy is included on a list with wildcards" do let(:env) do { "http_proxy" => proxy, "no_proxy" => "10.*,*.example.com", } end it { is_expected.to eq nil } end context "when no_proxy is a domain with a dot prefix" do let(:env) do { "http_proxy" => proxy, "no_proxy" => ".example.com", } end it { is_expected.to eq nil } end context "when no_proxy is a domain with no wildcard" do let(:env) do { "http_proxy" => proxy, "no_proxy" => "example.com", } end it { is_expected.to eq nil } end end end describe "allowing chefdk configuration outside of chefdk" do it "allows arbitrary settings in the chefdk config context" do expect { ChefConfig::Config.chefdk.generator_cookbook("/path") }.to_not raise_error end end describe "Treating deprecation warnings as errors" do context "when using our default RSpec configuration" do it "defaults to treating deprecation warnings as errors" do expect(ChefConfig::Config[:treat_deprecation_warnings_as_errors]).to be(true) end it "sets CHEF_TREAT_DEPRECATION_WARNINGS_AS_ERRORS environment variable" do expect(ENV["CHEF_TREAT_DEPRECATION_WARNINGS_AS_ERRORS"]).to eq("1") end it "treats deprecation warnings as errors in child processes when testing" do # Doing a full integration test where we launch a child process is slow # and liable to break for weird reasons (bundler env stuff, etc.), so # we're just checking that the presence of the environment variable # causes treat_deprecation_warnings_as_errors to be set to true after a # config reset. ChefConfig::Config.reset expect(ChefConfig::Config[:treat_deprecation_warnings_as_errors]).to be(true) end end context "outside of our test environment" do before do ENV.delete("CHEF_TREAT_DEPRECATION_WARNINGS_AS_ERRORS") ChefConfig::Config.reset end it "defaults to NOT treating deprecation warnings as errors" do expect(ChefConfig::Config[:treat_deprecation_warnings_as_errors]).to be(false) end end end describe "data collector URL" do context "when using default settings" do context "for Chef Client" do it "configures the data collector URL as a relative path to the Chef Server URL" do ChefConfig::Config[:chef_server_url] = "https://chef.example/organizations/myorg" expect(ChefConfig::Config[:data_collector][:server_url]).to eq("https://chef.example/organizations/myorg/data-collector") end end context "for Chef Solo legacy mode" do before do ChefConfig::Config[:solo_legacy_mode] = true end it "sets the data collector server URL to nil" do ChefConfig::Config[:chef_server_url] = "https://chef.example/organizations/myorg" expect(ChefConfig::Config[:data_collector][:server_url]).to be_nil end end context "for local mode" do before do ChefConfig::Config[:local_mode] = true end it "sets the data collector server URL to nil" do ChefConfig::Config[:chef_server_url] = "https://chef.example/organizations/myorg" expect(ChefConfig::Config[:data_collector][:server_url]).to be_nil end end end end describe "validation_client_name" do context "with a normal server URL" do before { ChefConfig::Config[:chef_server_url] = "https://chef.example/organizations/myorg" } it "sets the validation client to myorg-validator" do expect(ChefConfig::Config[:validation_client_name]).to eq "myorg-validator" end end context "with an unusual server URL" do before { ChefConfig::Config[:chef_server_url] = "https://chef.example/myorg" } it "sets the validation client to chef-validator" do expect(ChefConfig::Config[:validation_client_name]).to eq "chef-validator" end end end end chef-config-16.12.3/spec/unit/fips_spec.rb0000644000175100017510000000670114034030210017262 0ustar pravipravi# # Author:: Matt Wrock () # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "chef-config/fips" require "spec_helper" begin require "win32/registry" unless defined?(Win32::Registry) rescue LoadError # not on unix end RSpec.describe "ChefConfig.fips?" do let(:enabled) { "0" } context "on *nix" do let(:fips_path) { "/proc/sys/crypto/fips_enabled" } before(:each) do allow(ChefUtils).to receive(:windows?).and_return(false) allow(::File).to receive(:exist?).with(fips_path).and_return(true) allow(::File).to receive(:read).with(fips_path).and_return(enabled) end context "fips file is present and contains 1" do let(:enabled) { "1" } it "returns true" do expect(ChefConfig.fips?).to be(true) end end context "fips file does not contain 1" do let(:enabled) { "0" } it "returns false" do expect(ChefConfig.fips?).to be(false) end end context "fips file is not present" do before do allow(::File).to receive(:exist?).with(fips_path).and_return(false) end it "returns false" do expect(ChefConfig.fips?).to be(false) end end end context "on windows", :windows_only do let(:fips_key) { 'System\CurrentControlSet\Control\Lsa\FIPSAlgorithmPolicy' } let(:win_reg_entry) { { "Enabled" => enabled } } before(:each) do allow(ChefUtils).to receive(:windows?).and_return(true) allow(Win32::Registry::HKEY_LOCAL_MACHINE).to receive(:open).with(fips_key, arch).and_yield(win_reg_entry) end shared_examples "fips_detection" do context "fips enabled key is set to 1" do let(:enabled) { 1 } it "returns true" do expect(ChefConfig.fips?).to be(true) end end context "fips enabled key is set to 0" do let(:enabled) { 0 } it "returns false" do expect(ChefConfig.fips?).to be(false) end end context "fips key does not exist" do before do allow(Win32::Registry::HKEY_LOCAL_MACHINE).to receive(:open).and_raise(Win32::Registry::Error, 50) end it "returns false" do expect(ChefConfig.fips?).to be(false) end end end context "on 32 bit ruby" do let(:arch) { Win32::Registry::KEY_READ | 0x100 } before { stub_const("::RbConfig::CONFIG", { "target_cpu" => "i386" } ) } it_behaves_like "fips_detection" end context "on 64 bit ruby" do let(:arch) { Win32::Registry::KEY_READ | 0x200 } before { stub_const("::RbConfig::CONFIG", { "target_cpu" => "x86_64" } ) } it_behaves_like "fips_detection" end context "on unknown ruby" do let(:arch) { Win32::Registry::KEY_READ } before { stub_const("::RbConfig::CONFIG", { "target_cpu" => nil } ) } it_behaves_like "fips_detection" end end end chef-config-16.12.3/spec/unit/workstation_config_loader_spec.rb0000644000175100017510000005341314034030210023562 0ustar pravipravi# # Author:: Daniel DeLeo () # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "spec_helper" require "tempfile" unless defined?(Tempfile) require "chef-config/exceptions" require "chef-utils" require "chef-config/workstation_config_loader" RSpec.describe ChefConfig::WorkstationConfigLoader do let(:explicit_config_location) { nil } let(:env) { {} } let(:config_loader) do described_class.new(explicit_config_location).tap do |c| allow(c).to receive(:env).and_return(env) end end before do # We set this to nil so that a dev workstation will # not interfere with the tests. ChefConfig::Config.reset ChefConfig::Config[:config_d_dir] = nil end # Test methods that do I/O or reference external state which are stubbed out # elsewhere. describe "external dependencies" do let(:config_loader) { described_class.new(nil) } it "delegates to ENV for env" do expect(config_loader.env).to equal(ENV) end it "tests a path's existence" do expect(config_loader.path_exists?("/nope/nope/nope/nope/slab/jab/nab")).to be(false) expect(config_loader.path_exists?(__FILE__)).to be(true) end end describe "locating the config file" do context "without an explicit config" do before do allow(config_loader).to receive(:path_exists?).with(an_instance_of(String)).and_return(false) end it "has no config if HOME is not set" do expect(config_loader.config_location).to be(nil) expect(config_loader.no_config_found?).to be(true) end context "when HOME is set and contains a knife.rb" do let(:home) { "/Users/example.user" } before do allow(ChefConfig::PathHelper).to receive(:home).with(".chef").and_yield(File.join(home, ".chef")) allow(config_loader).to receive(:path_exists?).with("#{home}/.chef/knife.rb").and_return(true) end it "uses the config in HOME/.chef/knife.rb" do expect(config_loader.config_location).to eq("#{home}/.chef/knife.rb") end context "and has a config.rb" do before do allow(config_loader).to receive(:path_exists?).with("#{home}/.chef/config.rb").and_return(true) end it "uses the config in HOME/.chef/config.rb" do expect(config_loader.config_location).to eq("#{home}/.chef/config.rb") end context "and/or a parent dir contains a .chef dir" do let(:env_pwd) { "/path/to/cwd" } before do if ChefUtils.windows? env["CD"] = env_pwd else env["PWD"] = env_pwd end allow(config_loader).to receive(:path_exists?).with("#{env_pwd}/.chef/knife.rb").and_return(true) allow(File).to receive(:exist?).with("#{env_pwd}/.chef").and_return(true) allow(File).to receive(:directory?).with("#{env_pwd}/.chef").and_return(true) end it "prefers the config from parent_dir/.chef" do expect(config_loader.config_location).to eq("#{env_pwd}/.chef/knife.rb") end context "and the parent dir's .chef dir has a config.rb" do before do allow(config_loader).to receive(:path_exists?).with("#{env_pwd}/.chef/config.rb").and_return(true) end it "prefers the config from parent_dir/.chef" do expect(config_loader.config_location).to eq("#{env_pwd}/.chef/config.rb") end context "and/or the current working directory contains a .chef dir" do let(:cwd) { Dir.pwd } before do allow(config_loader).to receive(:path_exists?).with("#{cwd}/knife.rb").and_return(true) end it "prefers a knife.rb located in the cwd" do expect(config_loader.config_location).to eq("#{cwd}/knife.rb") end context "and the CWD's .chef dir has a config.rb" do before do allow(config_loader).to receive(:path_exists?).with("#{cwd}/config.rb").and_return(true) end it "prefers a config located in the cwd" do expect(config_loader.config_location).to eq("#{cwd}/config.rb") end context "and/or KNIFE_HOME is set" do let(:knife_home) { "/path/to/knife/home" } before do env["KNIFE_HOME"] = knife_home allow(config_loader).to receive(:path_exists?).with("#{knife_home}/knife.rb").and_return(true) end it "prefers a knife located in KNIFE_HOME" do expect(config_loader.config_location).to eq("/path/to/knife/home/knife.rb") end context "and KNIFE_HOME contains a config.rb" do before do env["KNIFE_HOME"] = knife_home allow(config_loader).to receive(:path_exists?).with("#{knife_home}/config.rb").and_return(true) end it "prefers a config.rb located in KNIFE_HOME" do expect(config_loader.config_location).to eq("/path/to/knife/home/config.rb") end end end end end end end end end context "when the current working dir is inside a symlinked directory" do before do # pwd according to your shell is /home/someuser/prod/chef-repo, but # chef-repo is a symlink to /home/someuser/codes/chef-repo env["CD"] = "/home/someuser/prod/chef-repo" # windows env["PWD"] = "/home/someuser/prod/chef-repo" # unix allow(Dir).to receive(:pwd).and_return("/home/someuser/codes/chef-repo") end it "loads the config from the non-dereferenced directory path" do expect(File).to receive(:exist?).with("/home/someuser/prod/chef-repo/.chef").and_return(false) expect(File).to receive(:exist?).with("/home/someuser/prod/.chef").and_return(true) expect(File).to receive(:directory?).with("/home/someuser/prod/.chef").and_return(true) expect(config_loader).to receive(:path_exists?).with("/home/someuser/prod/.chef/knife.rb").and_return(true) expect(config_loader.config_location).to eq("/home/someuser/prod/.chef/knife.rb") end end end context "when given an explicit config to load" do let(:explicit_config_location) { "/path/to/explicit/config.rb" } it "prefers the explicit config" do expect(config_loader.config_location).to eq(explicit_config_location) end end end describe "loading the config file" do context "when no explicit config is specified and no implicit config is found" do before do allow(config_loader).to receive(:path_exists?).with(an_instance_of(String)).and_return(false) end it "skips loading" do expect(config_loader.config_location).to be(nil) expect(config_loader).not_to receive(:apply_config) config_loader.load end end context "when an explicit config is given but it doesn't exist" do let(:explicit_config_location) { "/nope/nope/nope/slab/jab/nab" } it "raises a configuration error" do expect { config_loader.load }.to raise_error(ChefConfig::ConfigurationError) end end context "when the config file exists" do let(:config_content) { "" } # We need to keep a reference to the tempfile because while #close does # not unlink the file, the object being GC'd will. let(:tempfile) do Tempfile.new("Chef-WorkstationConfigLoader-rspec-test").tap do |t| t.print(config_content) t.close end end let(:explicit_config_location) do tempfile.path end after { File.unlink(explicit_config_location) if File.exist?(explicit_config_location) } context "and is valid" do let(:config_content) { "config_file_evaluated(true)" } it "loads the config" do expect(config_loader).to receive(:apply_config).and_call_original config_loader.load expect(ChefConfig::Config.config_file_evaluated).to be(true) end it "sets ChefConfig::Config.config_file" do config_loader.load expect(ChefConfig::Config.config_file).to eq(explicit_config_location) end it "loads a default value for node_name" do allow(Etc).to receive(:getlogin).and_return("notauser") config_loader.load expect(ChefConfig::Config.node_name).to eq("notauser") end context "with a user.pem" do before do allow(Etc).to receive(:getlogin).and_return("notauser") allow(FileTest).to receive(:exist?).and_call_original allow(FileTest).to receive(:exist?).with(File.expand_path("../notauser.pem", explicit_config_location)).and_return(false) allow(FileTest).to receive(:exist?).with(File.expand_path("../user.pem", explicit_config_location)).and_return(true) end it "loads a default value for client_key" do config_loader.load expect(ChefConfig::Config.client_key).to eq(File.expand_path("../user.pem", explicit_config_location)) end end context "with a notauser.pem" do before do allow(Etc).to receive(:getlogin).and_return("notauser") allow(FileTest).to receive(:exist?).and_call_original allow(FileTest).to receive(:exist?).with(File.expand_path("../notauser.pem", explicit_config_location)).and_return(true) allow(FileTest).to receive(:exist?).with(File.expand_path("../user.pem", explicit_config_location)).and_return(false) end it "loads a default value for client_key" do config_loader.load expect(ChefConfig::Config.client_key).to eq(File.expand_path("../notauser.pem", explicit_config_location)) end end context "with a valclient.pem" do before do ChefConfig::Config.validation_client_name = "valclient" allow(FileTest).to receive(:exist?).and_call_original allow(FileTest).to receive(:exist?).with(File.expand_path("../valclient.pem", explicit_config_location)).and_return(true) allow(FileTest).to receive(:exist?).with(File.expand_path("../validator.pem", explicit_config_location)).and_return(false) allow(FileTest).to receive(:exist?).with(File.expand_path("../validation.pem", explicit_config_location)).and_return(false) end it "loads a default value for validation_key" do config_loader.load expect(ChefConfig::Config.validation_key).to eq(File.expand_path("../valclient.pem", explicit_config_location)) end end context "with a validator.pem" do before do ChefConfig::Config.validation_client_name = "valclient" allow(FileTest).to receive(:exist?).and_call_original allow(FileTest).to receive(:exist?).with(File.expand_path("../valclient.pem", explicit_config_location)).and_return(false) allow(FileTest).to receive(:exist?).with(File.expand_path("../validator.pem", explicit_config_location)).and_return(true) allow(FileTest).to receive(:exist?).with(File.expand_path("../validation.pem", explicit_config_location)).and_return(false) end it "loads a default value for validation_key" do config_loader.load expect(ChefConfig::Config.validation_key).to eq(File.expand_path("../validator.pem", explicit_config_location)) end end end context "and has a syntax error" do let(:config_content) { "{{{{{:{{" } it "raises a ConfigurationError" do expect { config_loader.load }.to raise_error(ChefConfig::ConfigurationError) end end context "and raises a ruby exception during evaluation" do let(:config_content) { ":foo\n:bar\nraise 'oops'\n:baz\n" } it "raises a ConfigurationError" do expect { config_loader.load }.to raise_error(ChefConfig::ConfigurationError) end end end end describe "when loading config.d" do context "when the conf.d directory exists" do let(:config_content) { "" } let(:tempdir) { Dir.mktmpdir("chef-workstation-test") } let!(:confd_file) do Tempfile.new(["Chef-WorkstationConfigLoader-rspec-test", ".rb"], tempdir).tap do |t| t.print(config_content) t.close end end before do ChefConfig::Config[:config_d_dir] = tempdir allow(config_loader).to receive(:path_exists?).with( an_instance_of(String) ).and_return(false) end after do FileUtils.remove_entry_secure tempdir end context "and is valid" do let(:config_content) { "config_d_file_evaluated(true)" } it "loads the config" do expect(config_loader).to receive(:apply_config).and_call_original config_loader.load expect(ChefConfig::Config.config_d_file_evaluated).to be(true) end end context "and has a syntax error" do let(:config_content) { "{{{{{:{{" } it "raises a ConfigurationError" do expect { config_loader.load }.to raise_error(ChefConfig::ConfigurationError) end end context "has a non rb file" do let(:syntax_error_content) { "{{{{{:{{" } let(:config_content) { "config_d_file_evaluated(true)" } let!(:not_confd_file) do Tempfile.new(["Chef-WorkstationConfigLoader-rspec-test", ".foorb"], tempdir).tap do |t| t.print(syntax_error_content) t.close end end it "does not load the non rb file" do expect { config_loader.load }.not_to raise_error expect(ChefConfig::Config.config_d_file_evaluated).to be(true) end end end context "when the conf.d directory does not exist" do before do ChefConfig::Config[:config_d_dir] = "/nope/nope/nope/nope/notdoingit" end it "does not load anything" do expect(config_loader).not_to receive(:apply_config) end end end describe "when loading a credentials file" do if ChefUtils.windows? let(:home) { "C:/Users/example.user" } else let(:home) { "/Users/example.user" } end let(:credentials_file) { "#{home}/.chef/credentials" } let(:context_file) { "#{home}/.chef/context" } before do allow(ChefConfig::PathHelper).to receive(:home).with(".chef").and_return(File.join(home, ".chef")) allow(ChefConfig::PathHelper).to receive(:home).with(".chef", "credentials").and_return(credentials_file) allow(ChefConfig::PathHelper).to receive(:home).with(".chef", "context").and_return(context_file) allow(File).to receive(:file?).with(context_file).and_return false end context "when the file exists" do before do expect(File).to receive(:read).with(credentials_file, { encoding: "utf-8" }).and_return(content) allow(File).to receive(:file?).with(credentials_file).and_return true end context "and has a default profile" do let(:content) do content = <<~EOH [default] node_name = 'barney' client_key = "barney_rubble.pem" chef_server_url = "https://api.chef.io/organizations/bedrock" invalid_config_option1234 = "foobar" EOH content end it "applies the expected config" do expect { config_loader.load_credentials }.not_to raise_error expect(ChefConfig::Config.chef_server_url).to eq("https://api.chef.io/organizations/bedrock") expect(ChefConfig::Config.client_key.to_s).to eq("#{home}/.chef/barney_rubble.pem") expect(ChefConfig::Config.profile.to_s).to eq("default") expect(ChefConfig::Config[:invalid_config_option1234]).to eq("foobar") end end context "and has a default profile with knife settings" do let(:content) do content = <<~EOH [default] node_name = 'barney' client_key = "barney_rubble.pem" chef_server_url = "https://api.chef.io/organizations/bedrock" knife = { secret_file = "/home/barney/.chef/encrypted_data_bag_secret.pem" } [default.knife] ssh_user = "knife_ssh_user" EOH content end it "applies the expected knife config" do expect { config_loader.load_credentials }.not_to raise_error expect(ChefConfig::Config.chef_server_url).to eq("https://api.chef.io/organizations/bedrock") expect(ChefConfig::Config.client_key.to_s).to eq("#{home}/.chef/barney_rubble.pem") expect(ChefConfig::Config.knife[:ssh_user].to_s).to eq("knife_ssh_user") expect(ChefConfig::Config.knife[:secret_file].to_s).to eq("/home/barney/.chef/encrypted_data_bag_secret.pem") expect(ChefConfig::Config.profile.to_s).to eq("default") end end context "and has a profile containing a full key" do let(:content) do content = <<~EOH [default] client_key = """ -----BEGIN RSA PRIVATE KEY----- foo """ EOH content end it "applies the expected config" do expect { config_loader.load_credentials }.not_to raise_error expect(ChefConfig::Config.client_key_contents).to eq(<<~EOH -----BEGIN RSA PRIVATE KEY----- foo EOH ) end end context "and has several profiles" do let(:content) do content = <<~EOH [default] client_name = "default" [environment] client_name = "environment" [explicit] client_name = "explicit" [context] client_name = "context" EOH content end let(:env) { {} } before do stub_const("ENV", env) end it "selects the correct profile explicitly" do expect { config_loader.load_credentials("explicit") }.not_to raise_error expect(ChefConfig::Config.node_name).to eq("explicit") end context "with an environment variable" do let(:env) { { "CHEF_PROFILE" => "environment" } } it "selects the correct profile" do expect { config_loader.load_credentials }.not_to raise_error expect(ChefConfig::Config.node_name).to eq("environment") end end it "selects the correct profile with a context file" do allow(File).to receive(:file?).with(context_file).and_return true expect(File).to receive(:read).with(context_file).and_return "context" expect { config_loader.load_credentials }.not_to raise_error expect(ChefConfig::Config.node_name).to eq("context") end it "falls back to the default" do expect { config_loader.load_credentials }.not_to raise_error expect(ChefConfig::Config.node_name).to eq("default") end end context "and contains both node_name and client_name" do let(:content) do content = <<~EOH [default] node_name = 'barney' client_name = 'barney' EOH content end it "raises a ConfigurationError" do expect { config_loader.load_credentials }.to raise_error(ChefConfig::ConfigurationError) end end context "and ssl_verify_mode is a symbol string" do let(:content) do content = <<~EOH [default] ssl_verify_mode = ":verify_none" EOH content end it "raises a ConfigurationError" do expect { config_loader.load_credentials }.not_to raise_error expect(ChefConfig::Config.ssl_verify_mode).to eq(:verify_none) end end context "and ssl_verify_mode is a string" do let(:content) do content = <<~EOH [default] ssl_verify_mode = "verify_none" EOH content end it "raises a ConfigurationError" do expect { config_loader.load_credentials }.not_to raise_error expect(ChefConfig::Config.ssl_verify_mode).to eq(:verify_none) end end context "and has a syntax error" do let(:content) { "<<<<<" } it "raises a ConfigurationError" do expect { config_loader.load_credentials }.to raise_error(ChefConfig::ConfigurationError) end end end context "when the file does not exist" do it "does not load anything" do allow(File).to receive(:file?).with(credentials_file).and_return false expect(Tomlrb).not_to receive(:load_file) config_loader.load_credentials end end end end chef-config-16.12.3/spec/spec_helper.rb0000644000175100017510000000642714034030210016626 0ustar pravipravirequire "chef-utils" # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with # `:focus` metadata. When nothing is tagged with `:focus`, all examples # get run. config.filter_run :focus config.run_all_when_everything_filtered = true config.filter_run_excluding windows_only: true unless ChefUtils.windows? config.filter_run_excluding unix_only: true if ChefUtils.windows? # Limits the available syntax to the non-monkey patched syntax that is # recommended. For more details, see: # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching config.disable_monkey_patching! # This setting enables warnings. It's recommended, but in some cases may # be too noisy due to issues in dependencies. config.warnings = true # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = "doc" end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. # config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed end chef-config-16.12.3/lib/0000755000175100017510000000000014034030210013613 5ustar pravipravichef-config-16.12.3/lib/chef-config.rb0000644000175100017510000000122514034030210016310 0ustar pravipravi# # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module ChefConfig end chef-config-16.12.3/lib/chef-config/0000755000175100017510000000000014034030210015763 5ustar pravipravichef-config-16.12.3/lib/chef-config/workstation_config_loader.rb0000644000175100017510000002304314034030210023551 0ustar pravipravi# # Author:: Daniel DeLeo () # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "chef-utils" unless defined?(ChefUtils::CANARY) require_relative "config" require_relative "exceptions" require_relative "logger" require_relative "path_helper" require_relative "windows" require_relative "mixin/dot_d" require_relative "mixin/credentials" module ChefConfig class WorkstationConfigLoader include ChefConfig::Mixin::DotD include ChefConfig::Mixin::Credentials # Path to a config file requested by user, (e.g., via command line option). Can be nil attr_accessor :explicit_config_file # The name of a credentials profile. Can be nil attr_accessor :profile attr_reader :credentials_found # TODO: initialize this with a logger for Chef and Knife def initialize(explicit_config_file, logger = nil, profile: nil) @explicit_config_file = explicit_config_file @chef_config_dir = nil @config_location = nil @profile = profile @logger = logger || NullLogger.new @credentials_found = false end def no_config_found? config_location.nil? && !credentials_found end def config_location @config_location ||= (explicit_config_file || locate_local_config) end def chef_config_dir if @chef_config_dir.nil? @chef_config_dir = false full_path = working_directory.split(File::SEPARATOR) (full_path.length - 1).downto(0) do |i| candidate_directory = File.join(full_path[0..i] + [ChefUtils::Dist::Infra::USER_CONF_DIR]) if File.exist?(candidate_directory) && File.directory?(candidate_directory) @chef_config_dir = candidate_directory break end end end @chef_config_dir end def load load_credentials(profile) # Ignore it if there's no explicit_config_file and can't find one at a # default path. unless config_location.nil? if explicit_config_file && !path_exists?(config_location) raise ChefConfig::ConfigurationError, "Specified config file #{config_location} does not exist" end # Have to set Config.config_file b/c other config is derived from it. Config.config_file = config_location apply_config(IO.read(config_location), config_location) end load_dot_d(Config[:config_d_dir]) if Config[:config_d_dir] apply_defaults end # (Private API, public for test purposes) def env ENV end # (Private API, public for test purposes) def path_exists?(path) Pathname.new(path).expand_path.exist? end private def have_config?(path) if path_exists?(path) logger.info("Using config at #{path}") true else logger.debug("Config not found at #{path}, trying next option") false end end def locate_local_config candidate_configs = [] # Look for $KNIFE_HOME/knife.rb (allow multiple knives config on same machine) if env["KNIFE_HOME"] candidate_configs << File.join(env["KNIFE_HOME"], "config.rb") candidate_configs << File.join(env["KNIFE_HOME"], "knife.rb") end # Look for $PWD/knife.rb if Dir.pwd candidate_configs << File.join(Dir.pwd, "config.rb") candidate_configs << File.join(Dir.pwd, "knife.rb") end # Look for $UPWARD/.chef/knife.rb if chef_config_dir candidate_configs << File.join(chef_config_dir, "config.rb") candidate_configs << File.join(chef_config_dir, "knife.rb") end # Look for $HOME/.chef/knife.rb PathHelper.home(ChefUtils::Dist::Infra::USER_CONF_DIR) do |dot_chef_dir| candidate_configs << File.join(dot_chef_dir, "config.rb") candidate_configs << File.join(dot_chef_dir, "knife.rb") end candidate_configs.find do |candidate_config| have_config?(candidate_config) end end def working_directory if ChefUtils.windows? env["CD"] else env["PWD"] end || Dir.pwd end def apply_credentials(creds, profile) # Store the profile used in case other things want it. Config.profile ||= profile # Validate the credentials data. if creds.key?("node_name") && creds.key?("client_name") raise ChefConfig::ConfigurationError, "Do not specify both node_name and client_name. You should prefer client_name." end # Load credentials data into the Chef configuration. creds.each do |key, value| case key.to_s when "client_name" # Special case because it's weird to set your username via `node_name`. Config.node_name = value when "validation_key", "validator_key" extract_key(value, :validation_key, :validation_key_contents) when "client_key" extract_key(value, :client_key, :client_key_contents) when "knife" Config.knife.merge!(value.transform_keys(&:to_sym)) else Config[key.to_sym] = value end end @credentials_found = true end def extract_key(key_value, config_path, config_contents) if key_value.start_with?("-----BEGIN RSA PRIVATE KEY-----") Config.send(config_contents, key_value) else abs_path = Pathname.new(key_value).expand_path(home_chef_dir) Config.send(config_path, abs_path) end end def home_chef_dir @home_chef_dir ||= PathHelper.home(ChefUtils::Dist::Infra::USER_CONF_DIR) end def apply_config(config_content, config_file_path) Config.from_string(config_content, config_file_path) rescue SignalException raise rescue SyntaxError => e message = "" message << "You have invalid ruby syntax in your config file #{config_file_path}\n\n" message << "#{e.class.name}: #{e.message}\n" if file_line = e.message[/#{Regexp.escape(config_file_path)}:\d+/] line = file_line[/:(\d+)$/, 1].to_i message << highlight_config_error(config_file_path, line) end raise ChefConfig::ConfigurationError, message rescue Exception => e message = "You have an error in your config file #{config_file_path}\n\n" message << "#{e.class.name}: #{e.message}\n" filtered_trace = e.backtrace.grep(/#{Regexp.escape(config_file_path)}/) filtered_trace.each { |bt_line| message << " " << bt_line << "\n" } unless filtered_trace.empty? line_nr = filtered_trace.first[/#{Regexp.escape(config_file_path)}:(\d+)/, 1] message << highlight_config_error(config_file_path, line_nr.to_i) end raise ChefConfig::ConfigurationError, message end # Apply default configuration values for workstation-style tools. # # Global defaults should go in {ChefConfig::Config} instead, this is only # for things like `knife` and `chef`. # # @api private # @since 14.3 # @return [void] def apply_defaults # If we don't have a better guess use the username. Config[:node_name] ||= Etc.getlogin # If we don't have a key (path or inline) check user.pem and $node_name.pem. unless Config.key?(:client_key) || Config.key?(:client_key_contents) key_path = find_default_key(["#{Config[:node_name]}.pem", "user.pem"]) Config[:client_key] = key_path if key_path end # Similarly look for a validation key file, though this should be less # common these days. unless Config.key?(:validation_key) || Config.key?(:validation_key_contents) key_path = find_default_key(["#{Config[:validation_client_name]}.pem", "validator.pem", "validation.pem"]) Config[:validation_key] = key_path if key_path end end # Look for a default key file. # # This searches for any of a list of possible default keys, checking both # the local `.chef/` folder and the home directory `~/.chef/`. Returns `nil` # if no matching file is found. # # @api private # @since 14.3 # @param key_names [Array] A list of possible filenames to check for. # The first one found will be returned. # @return [String, nil] def find_default_key(key_names) key_names.each do |filename| path = Pathname.new(filename) # If we have a config location (like ./.chef/), look there first. if config_location local_path = path.expand_path(File.dirname(config_location)) return local_path.to_s if local_path.exist? end # Then check ~/.chef. home_path = path.expand_path(home_chef_dir) return home_path.to_s if home_path.exist? end nil end def highlight_config_error(file, line) config_file_lines = [] IO.readlines(file).each_with_index { |l, i| config_file_lines << "#{(i + 1).to_s.rjust(3)}: #{l.chomp}" } if line == 1 lines = config_file_lines[0..3] else lines = config_file_lines[Range.new(line - 2, line)] end "Relevant file content:\n" + lines.join("\n") + "\n" end def logger @logger end end end chef-config-16.12.3/lib/chef-config/path_helper.rb0000644000175100017510000003370014034030210020606 0ustar pravipravi# # Author:: Bryan McLellan # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "chef-utils" unless defined?(ChefUtils::CANARY) require_relative "windows" require_relative "logger" require_relative "exceptions" module ChefConfig class PathHelper # Maximum characters in a standard Windows path (260 including drive letter and NUL) WIN_MAX_PATH = 259 def self.dirname(path, windows: ChefUtils.windows?) if windows # Find the first slash, not counting trailing slashes end_slash = path.size loop do slash = path.rindex(/[#{Regexp.escape(File::SEPARATOR)}#{Regexp.escape(path_separator(windows: windows))}]/, end_slash - 1) if !slash return end_slash == path.size ? "." : path_separator(windows: windows) elsif slash == end_slash - 1 end_slash = slash else return path[0..slash - 1] end end else ::File.dirname(path) end end BACKSLASH = '\\'.freeze def self.path_separator(windows: ChefUtils.windows?) if windows BACKSLASH else File::SEPARATOR end end def self.join(*args, windows: ChefUtils.windows?) path_separator_regex = Regexp.escape(windows ? "#{File::SEPARATOR}#{BACKSLASH}" : File::SEPARATOR) trailing_slashes_regex = /[#{path_separator_regex}]+$/.freeze leading_slashes_regex = /^[#{path_separator_regex}]+/.freeze args.flatten.inject do |joined_path, component| joined_path = joined_path.sub(trailing_slashes_regex, "") component = component.sub(leading_slashes_regex, "") joined_path + "#{path_separator(windows: windows)}#{component}" end end def self.validate_path(path, windows: ChefUtils.windows?) if windows unless printable?(path) msg = "Path '#{path}' contains non-printable characters. Check that backslashes are escaped with another backslash (e.g. C:\\\\Windows) in double-quoted strings." ChefConfig.logger.error(msg) raise ChefConfig::InvalidPath, msg end if windows_max_length_exceeded?(path) ChefConfig.logger.trace("Path '#{path}' is longer than #{WIN_MAX_PATH}, prefixing with'\\\\?\\'") path.insert(0, "\\\\?\\") end end path end def self.windows_max_length_exceeded?(path) # Check to see if paths without the \\?\ prefix are over the maximum allowed length for the Windows API # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx unless /^\\\\?\\/.match?(path) if path.length > WIN_MAX_PATH return true end end false end def self.printable?(string) # returns true if string is free of non-printable characters (escape sequences) # this returns false for whitespace escape sequences as well, e.g. \n\t if /[^[:print:]]/.match?(string) false else true end end # Produces a comparable path. def self.canonical_path(path, add_prefix = true, windows: ChefUtils.windows?) # First remove extra separators and resolve any relative paths abs_path = File.absolute_path(path) if windows # Add the \\?\ API prefix on Windows unless add_prefix is false # Downcase on Windows where paths are still case-insensitive abs_path.gsub!(::File::SEPARATOR, path_separator(windows: windows)) if add_prefix && abs_path !~ /^\\\\?\\/ abs_path.insert(0, "\\\\?\\") end abs_path.downcase! end abs_path end # The built in ruby Pathname#cleanpath method does not clean up forward slashes and # backslashes. This is a wrapper around that which does. In general this is NOT # recommended for internal use within ruby/chef since ruby does not care about forward slashes # vs. backslashes, even on Windows. Where this generally matters is when being rendered # to the user, or being rendered into things like the windows PATH or to commands that # are being executed. In some cases it may be easier on windows to render paths to # unix-style for being eventually eval'd by ruby in the future (templates being rendered # with code to be consumed by ruby) where forcing unix-style forward slashes avoids the # issue of needing to escape the backslashes in rendered strings. This has a boolean # operator to force windows-style or non-windows style operation, where the default is # determined by the underlying node['platform'] value. # # In general if you don't know if you need this routine, do not use it, best practice # within chef/ruby itself is not to care. Only use it to force windows or unix style # when it really matters. # # @param path [String] the path to clean # @param windows [Boolean] optional flag to force to windows or unix-style # @return [String] cleaned path # def self.cleanpath(path, windows: ChefUtils.windows?) path = Pathname.new(path).cleanpath.to_s if windows # ensure all forward slashes are backslashes path.gsub(File::SEPARATOR, path_separator(windows: windows)) else # ensure all backslashes are forward slashes path.gsub(BACKSLASH, File::SEPARATOR) end end # This is not just escaping for something like use in Regexps, or in globs. For the former # just use Regexp.escape. For the latter, use escape_glob_dir below. # # This is escaping where the path to be rendered is being put into a ruby file which will # later be read back by ruby (or something similar) so we need quadruple backslashes. # # In order to print: # # file_cache_path "C:\\chef" # # We need to convert "C:\chef" to "C:\\\\chef" to interpolate into a string which is rendered # into the output file with that line in it. # # @param path [String] the path to escape # @return [String] the escaped path # def self.escapepath(path) path.gsub(BACKSLASH, BACKSLASH * 4) end def self.paths_eql?(path1, path2, windows: ChefUtils.windows?) canonical_path(path1, windows: windows) == canonical_path(path2, windows: windows) end # @deprecated this method is deprecated. Please use escape_glob_dirs # Paths which may contain glob-reserved characters need # to be escaped before globbing can be done. # http://stackoverflow.com/questions/14127343 def self.escape_glob(*parts, windows: ChefUtils.windows?) path = cleanpath(join(*parts, windows: windows), windows: windows) path.gsub(/[\\\{\}\[\]\*\?]/) { |x| "\\" + x } end # This function does not switch to backslashes for windows # This is because only forwardslashes should be used with dir (even for windows) def self.escape_glob_dir(*parts) path = Pathname.new(join(*parts)).cleanpath.to_s path.gsub(/[\\\{\}\[\]\*\?]/) { |x| "\\" + x } end def self.relative_path_from(from, to, windows: ChefUtils.windows?) Pathname.new(cleanpath(to, windows: windows)).relative_path_from(Pathname.new(cleanpath(from, windows: windows))) end # Set the project-specific home directory environment variable. # # This can be used to allow per-tool home directory aliases like $KNIFE_HOME. # # @param [env_var] Key for an environment variable to use. # @return [nil] def self.per_tool_home_environment=(env_var) @@per_tool_home_environment = env_var # Reset this in case .home was already called. @@home_dir = nil end # Retrieves the "home directory" of the current user while trying to ascertain the existence # of said directory. The path returned uses / for all separators (the ruby standard format). # If the home directory doesn't exist or an error is otherwise encountered, nil is returned. # # If a set of path elements is provided, they are appended as-is to the home path if the # homepath exists. # # If an optional block is provided, the joined path is passed to that block if the home path is # valid and the result of the block is returned instead. # # Home-path discovery is performed once. If a path is discovered, that value is memoized so # that subsequent calls to home_dir don't bounce around. # # @see all_homes # @param args [Array] Path components to look for under the home directory. # @return [String] def self.home(*args) @@home_dir ||= all_homes { |p| break p } if @@home_dir path = File.join(@@home_dir, *args) block_given? ? (yield path) : path end end # See self.home. This method performs a similar operation except that it yields all the different # possible values of 'HOME' that one could have on this platform. Hence, on windows, if # HOMEDRIVE\HOMEPATH and USERPROFILE are different, the provided block will be called twice. # This method goes out and checks the existence of each location at the time of the call. # # The return is a list of all the returned values from each block invocation or a list of paths # if no block is provided. def self.all_homes(*args, windows: ChefUtils.windows?) paths = [] paths << ENV[@@per_tool_home_environment] if defined?(@@per_tool_home_environment) && @@per_tool_home_environment && ENV[@@per_tool_home_environment] paths << ENV["CHEF_HOME"] if ENV["CHEF_HOME"] if windows # By default, Ruby uses the the following environment variables to determine Dir.home: # HOME # HOMEDRIVE HOMEPATH # USERPROFILE # Ruby only checks to see if the variable is specified - not if the directory actually exists. # On Windows, HOMEDRIVE HOMEPATH can point to a different location (such as an unavailable network mounted drive) # while USERPROFILE points to the location where the user application settings and profile are stored. HOME # is not defined as an environment variable (usually). If the home path actually uses UNC, then the prefix is # HOMESHARE instead of HOMEDRIVE. # # We instead walk down the following and only include paths that actually exist. # HOME # HOMEDRIVE HOMEPATH # HOMESHARE HOMEPATH # USERPROFILE paths << ENV["HOME"] paths << ENV["HOMEDRIVE"] + ENV["HOMEPATH"] if ENV["HOMEDRIVE"] && ENV["HOMEPATH"] paths << ENV["HOMESHARE"] + ENV["HOMEPATH"] if ENV["HOMESHARE"] && ENV["HOMEPATH"] paths << ENV["USERPROFILE"] end paths << Dir.home if ENV["HOME"] # Depending on what environment variables we're using, the slashes can go in any which way. # Just change them all to / to keep things consistent. # Note: Maybe this is a bad idea on some unixy systems where \ might be a valid character depending on # the particular brand of kool-aid you consume. This code assumes that \ and / are both # path separators on any system being used. paths = paths.map { |home_path| home_path.gsub(path_separator(windows: windows), ::File::SEPARATOR) if home_path } # Filter out duplicate paths and paths that don't exist. valid_paths = paths.select { |home_path| home_path && Dir.exist?(home_path.force_encoding("utf-8")) } valid_paths = valid_paths.uniq # Join all optional path elements at the end. # If a block is provided, invoke it - otherwise just return what we've got. joined_paths = valid_paths.map { |home_path| File.join(home_path, *args) } if block_given? joined_paths.each { |p| yield p } else joined_paths end end # Determine if the given path is protected by macOS System Integrity Protection. def self.is_sip_path?(path, node) if ChefUtils.macos? # @todo: parse rootless.conf for this? sip_paths = [ "/System", "/bin", "/sbin", "/usr" ] sip_paths.each do |sip_path| ChefConfig.logger.info("#{sip_path} is a SIP path, checking if it is in the exceptions list.") return true if path.start_with?(sip_path) end false else false end end # Determine if the given path is on the exception list for macOS System Integrity Protection. def self.writable_sip_path?(path) # todo: parse rootless.conf for this? sip_exceptions = [ "/System/Library/Caches", "/System/Library/Extensions", "/System/Library/Speech", "/System/Library/User Template", "/usr/libexec/cups", "/usr/local", "/usr/share/man" ] sip_exceptions.each do |exception_path| return true if path.start_with?(exception_path) end ChefConfig.logger.error("Cannot write to a SIP path #{path} on macOS!") false end # Splits a string into an array of tokens as commands and arguments # # str = 'command with "some arguments"' # split_args(str) => ["command", "with", "\"some arguments\""] # def self.split_args(line) cmd_args = [] field = "" line.scan(/\s*(?>([^\s\\"]+|"([^"]*)"|'([^']*)')|(\S))(\s|\z)?/m) do |word, within_dq, within_sq, esc, sep| # Append the string with Word & Escape Character field << (word || esc.gsub(/\\(.)/, '\\1')) # Re-build the field when any whitespace character or # End of string is encountered if sep cmd_args << field field = "" end end cmd_args end end end chef-config-16.12.3/lib/chef-config/mixin/0000755000175100017510000000000014034030210017107 5ustar pravipravichef-config-16.12.3/lib/chef-config/mixin/train_transport.rb0000644000175100017510000001235614034030210022674 0ustar pravipravi# Author:: Bryan McLellan # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require_relative "credentials" autoload :Train, "train" require_relative "../config" require "chef-utils/dist" unless defined?(ChefUtils::Dist) module ChefConfig module Mixin module TrainTransport include ChefConfig::Mixin::Credentials attr_accessor :logger def initialize(logger) @logger = logger end # # Returns a RFC099 credentials profile as a hash # def load_credentials(profile) # Tomlrb.load_file returns a hash with keys as strings credentials = parse_credentials_file if contains_split_fqdn?(credentials, profile) logger.warn("Credentials file #{credentials_file_path} contains target '#{profile}' as a Hash, expected a string.") logger.warn("Hostnames must be surrounded by single quotes, e.g. ['host.example.org']") end # host names must be specified in credentials file as ['foo.example.org'] with quotes if !credentials.nil? && !credentials[profile].nil? credentials[profile].transform_keys(&:to_sym) # return symbolized keys to match Train.options() else nil end end # Toml creates hashes when a key is separated by periods, e.g. # [host.example.org] => { host: { example: { org: {} } } } # # Returns true if the above example is true # # A hostname has to be specified as ['host.example.org'] # This will be a common mistake so we should catch it # def contains_split_fqdn?(hash, fqdn) fqdn.split(".").reduce(hash) do |h, k| v = h[k] if Hash === v v else break false end end end # ChefConfig::Mixin::Credentials.credentials_file_path is designed around knife, # overriding it here. # # Credentials file preference: # # 1) target_mode.credentials_file # 2) /etc/chef/TARGET_MODE_HOST/credentials # 3) #credentials_file_path from parent ($HOME/.chef/credentials) # def credentials_file_path tm_config = config.target_mode profile = tm_config.host credentials_file = if tm_config.credentials_file && File.exist?(tm_config.credentials_file) tm_config.credentials_file elsif File.exist?(config.platform_specific_path("#{ChefConfig::Config.etc_chef_dir}/#{profile}/credentials")) config.platform_specific_path("#{ChefConfig::Config.etc_chef_dir}/#{profile}/credentials") else super end raise ArgumentError, "No credentials file found for target '#{profile}'" unless credentials_file raise ArgumentError, "Credentials file specified for target mode does not exist: '#{credentials_file}'" unless File.exist?(credentials_file) logger.debug("Loading credentials file '#{credentials_file}' for target '#{profile}'") credentials_file end def build_transport return nil unless config.target_mode? # TODO: Consider supporting parsing the protocol from a URI passed to `--target` # train_config = {} # Load the target_mode config context from config, and place any valid settings into the train configuration tm_config = config.target_mode protocol = tm_config.protocol train_config = tm_config.to_hash.select { |k| Train.options(protocol).key?(k) } logger.trace("Using target mode options from #{ChefUtils::Dist::Infra::PRODUCT} config file: #{train_config.keys.join(", ")}") if train_config # Load the credentials file, and place any valid settings into the train configuration credentials = load_credentials(tm_config.host) if credentials valid_settings = credentials.select { |k| Train.options(protocol).key?(k) } valid_settings[:enable_password] = credentials[:enable_password] if credentials.key?(:enable_password) train_config.merge!(valid_settings) logger.trace("Using target mode options from credentials file: #{valid_settings.keys.join(", ")}") if valid_settings end train_config[:logger] = logger # Train handles connection retries for us Train.create(protocol, train_config) rescue SocketError => e # likely a dns failure, not caught by train e.message.replace "Error connecting to #{train_config[:target]} - #{e.message}" raise e rescue Train::PluginLoadError logger.error("Invalid target mode protocol: #{protocol}") exit(1) end def config raise NotImplementedError end end end end chef-config-16.12.3/lib/chef-config/mixin/fuzzy_hostname_matcher.rb0000644000175100017510000000276614034030210024237 0ustar pravipravi# # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "fuzzyurl" module ChefConfig module Mixin module FuzzyHostnameMatcher # # Check to see if a hostname matches a match string. Used to see if hosts fall under our no_proxy config # # @param [String] hostname the hostname to check # @param [String] matches the pattern to match # # @return [Boolean] # def fuzzy_hostname_match_any?(hostname, matches) if hostname && matches return matches.to_s.split(/\s*,\s*/).compact.any? do |m| fuzzy_hostname_match?(hostname, m) end end false end def fuzzy_hostname_match?(hostname, match) # Do greedy matching by adding wildcard if it is not specified match = "*" + match unless match.start_with?("*") Fuzzyurl.matches?(Fuzzyurl.mask(hostname: match), hostname) end end end end chef-config-16.12.3/lib/chef-config/mixin/credentials.rb0000644000175100017510000000666114034030210021742 0ustar pravipravi# # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # autoload :Tomlrb, "tomlrb" require_relative "../path_helper" require "chef-utils/dist" unless defined?(ChefUtils::Dist) module ChefConfig module Mixin # Helper methods for working with credentials files. # # @since 13.7 # @api internal module Credentials # Compute the active credentials profile name. # # The lookup order is argument (from --profile), environment variable # ($CHEF_PROFILE), context file (~/.chef/context), and then "default" as # a fallback. # # @since 14.4 # @param profile [String, nil] Optional override for the active profile, # normally set via a command-line option. # @return [String] def credentials_profile(profile = nil) context_file = PathHelper.home(ChefUtils::Dist::Infra::USER_CONF_DIR, "context").freeze if !profile.nil? profile elsif ENV.include?("CHEF_PROFILE") ENV["CHEF_PROFILE"] elsif File.file?(context_file) File.read(context_file).strip else "default" end end # Compute the path to the credentials file. # # @since 14.4 # @return [String] def credentials_file_path PathHelper.home(ChefUtils::Dist::Infra::USER_CONF_DIR, "credentials").freeze end # Load and parse the credentials file. # # Returns `nil` if the credentials file is unavailable. # # @since 14.4 # @return [String, nil] def parse_credentials_file credentials_file = credentials_file_path return nil unless File.file?(credentials_file) begin Tomlrb.load_file(credentials_file) rescue => e # TOML's error messages are mostly rubbish, so we'll just give a generic one message = "Unable to parse Credentials file: #{credentials_file}\n" message << e.message raise ChefConfig::ConfigurationError, message end end # Load and process the active credentials. # # @see WorkstationConfigLoader#apply_credentials # @param profile [String, nil] Optional override for the active profile, # normally set via a command-line option. # @return [void] def load_credentials(profile = nil) profile = credentials_profile(profile) cred_config = parse_credentials_file return if cred_config.nil? # No credentials, nothing to do here. if cred_config[profile].nil? # Unknown profile name. For "default" just silently ignore, otherwise # raise an error. return if profile == "default" raise ChefConfig::ConfigurationError, "Profile #{profile} doesn't exist. Please add it to #{credentials_file_path}." end apply_credentials(cred_config[profile], profile) end end end end chef-config-16.12.3/lib/chef-config/mixin/dot_d.rb0000644000175100017510000000272114034030210020527 0ustar pravipravi# # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require_relative "../path_helper" module ChefConfig module Mixin module DotD # Find available configuration files in a `.d/` style include directory. # Make sure we exclude anything that's not a file so we avoid directories ending in .rb (just in case) # # @api internal # @param path [String] Base .d/ path to load from. # @return [Array] def find_dot_d(path) Dir["#{PathHelper.escape_glob_dir(path)}/*.rb"].select { |entry| File.file?(entry) }.sort end # Load configuration from a `.d/` style include directory. # # @api internal # @param path [String] Base .d/ path to load from. # @return [void] def load_dot_d(path) find_dot_d(path).each do |conf| apply_config(IO.read(conf), conf) end end end end end chef-config-16.12.3/lib/chef-config/fips.rb0000644000175100017510000000321014034030210017245 0ustar pravipravi# # Author:: Matt Wrock () # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "chef-utils" unless defined?(ChefUtils::CANARY) module ChefConfig def self.fips? if ChefUtils.windows? begin require "win32/registry" unless defined?(Win32::Registry) rescue LoadError return false end # from http://msdn.microsoft.com/en-us/library/windows/desktop/aa384129(v=vs.85).aspx reg_type = case ::RbConfig::CONFIG["target_cpu"] when "i386" Win32::Registry::KEY_READ | 0x100 when "x86_64" Win32::Registry::KEY_READ | 0x200 else Win32::Registry::KEY_READ end begin Win32::Registry::HKEY_LOCAL_MACHINE.open('System\CurrentControlSet\Control\Lsa\FIPSAlgorithmPolicy', reg_type) do |policy| policy["Enabled"] != 0 end rescue Win32::Registry::Error false end else fips_path = "/proc/sys/crypto/fips_enabled" File.exist?(fips_path) && File.read(fips_path).chomp != "0" end end end chef-config-16.12.3/lib/chef-config/config.rb0000644000175100017510000015422014034030210017561 0ustar pravipravi# # Author:: Adam Jacob () # Author:: Christopher Brown () # Author:: AJ Christensen () # Author:: Mark Mzyk () # Author:: Kyle Goodwin () # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "mixlib/config" unless defined?(Mixlib::Config) autoload :Pathname, "pathname" autoload :ChefUtils, "chef-utils" require_relative "fips" require_relative "logger" require_relative "windows" require_relative "path_helper" require_relative "mixin/fuzzy_hostname_matcher" module Mixlib autoload :ShellOut, "mixlib/shellout" end autoload :URI, "uri" module Addressable autoload :URI, "addressable/uri" end autoload :OpenSSL, "openssl" autoload :YAML, "yaml" require "chef-utils/dist" unless defined?(ChefUtils::Dist) module ChefConfig class Config extend Mixlib::Config extend ChefConfig::Mixin::FuzzyHostnameMatcher # Evaluates the given string as config. # # +filename+ is used for context in stacktraces, but doesn't need to be the name of an actual file. def self.from_string(string, filename) instance_eval(string, filename, 1) end def self.inspect configuration.inspect end # given a *nix style config path return the platform specific path # to that same config file # @example client.pem path on Windows # platform_specific_path("/etc/chef/client.pem") #=> "C:\\chef\\client.pem" # @param path [String] The unix path to convert to a platform specific path # @return [String] a platform specific path def self.platform_specific_path(path) path = PathHelper.cleanpath(path) if ChefUtils.windows? # turns \etc\chef\client.rb and \var\chef\client.rb into C:/chef/client.rb # Some installations will be on different drives so use the drive that # the expanded path to __FILE__ is found. drive = windows_installation_drive if drive && path[0] == '\\' && path.split('\\')[2] == "chef" path = PathHelper.join(drive, path.split('\\', 3)[2]) end end path end # On *nix, /etc/chef, on Windows C:\chef # # @param windows [Boolean] optional flag to force to windows or unix-style # @return [String] the platform-specific path # def self.etc_chef_dir(windows: ChefUtils.windows?) path = windows ? c_chef_dir : PathHelper.join("/etc", ChefUtils::Dist::Infra::DIR_SUFFIX, windows: windows) PathHelper.cleanpath(path, windows: windows) end # On *nix, /var/chef, on Windows C:\chef # # @param windows [Boolean] optional flag to force to windows or unix-style # @return [String] the platform-specific path # def self.var_chef_dir(windows: ChefUtils.windows?) path = windows ? c_chef_dir : PathHelper.join("/var", ChefUtils::Dist::Infra::DIR_SUFFIX, windows: windows) PathHelper.cleanpath(path, windows: windows) end # On *nix, /var, on Windows C:\ # # @param windows [Boolean] optional flag to force to windows or unix-style # @return [String] the platform-specific path # def self.var_root_dir(windows: ChefUtils.windows?) path = windows ? "C:\\" : "/var" PathHelper.cleanpath(path, windows: windows) end # On windows, C:/chef/ # # (should only be called in a windows-context) # # @return [String] the platform-specific path # def self.c_chef_dir(windows: ChefUtils.windows?) drive = windows_installation_drive || "C:" PathHelper.join(drive, ChefUtils::Dist::Infra::DIR_SUFFIX, windows: windows) end # On windows, C:/opscode # # (should only be called in a windows-context) # # @return [String] the platform-specific path # def self.c_opscode_dir(windows: ChefUtils.windows?) drive = windows_installation_drive || "C:" PathHelper.join(drive, ChefUtils::Dist::Org::LEGACY_CONF_DIR, ChefUtils::Dist::Infra::DIR_SUFFIX, windows: windows) end # the drive where Chef is installed on a windows host. This is determined # either by the drive containing the current file or by the SYSTEMDRIVE ENV # variable # # (should only be called in a windows-context) # # @return [String] the drive letter # def self.windows_installation_drive if ChefUtils.windows? drive = File.expand_path(__FILE__).split("/", 2)[0] drive = ENV["SYSTEMDRIVE"] if drive.to_s == "" drive end end # @param name [String] # @param file_path [String] def self.add_formatter(name, file_path = nil) formatters << [name, file_path] end # @param logger [String] def self.add_event_logger(logger) event_handlers << logger end def self.apply_extra_config_options(extra_config_options) if extra_config_options extra_parsed_options = extra_config_options.inject({}) do |memo, option| # Sanity check value. if option.empty? || !option.include?("=") raise UnparsableConfigOption, "Unparsable config option #{option.inspect}" end # Split including whitespace if someone does truly odd like # --config-option "foo = bar" key, value = option.split(/\s*=\s*/, 2) # Call to_sym because Chef::Config expects only symbol keys. Also # runs a simple parse on the string for some common types. memo[key.to_sym] = YAML.safe_load(value) memo end set_extra_config_options(extra_parsed_options) end end # We use :[]= assignment here to not bypass any coercions that happen via mixlib-config writes_value callbacks def self.set_extra_config_options(extra_parsed_options) extra_parsed_options.each do |key, value| self[key.to_sym] = value end end # Config file to load (client.rb, knife.rb, etc. defaults set differently in knife, chef-client, etc.) configurable(:config_file) default(:config_dir) do if config_file PathHelper.dirname(PathHelper.canonical_path(config_file, false)) else PathHelper.join(PathHelper.cleanpath(user_home), ChefUtils::Dist::Infra::USER_CONF_DIR, "") end end default :formatters, [] # @param uri [String] the URI to validate # # @return [Boolean] is the URL valid def self.is_valid_url?(uri) url = uri.to_s.strip %r{^http://} =~ url || %r{^https://} =~ url || /^chefzero:/ =~ url end # Override the config dispatch to set the value of multiple server options simultaneously # # @param [String] url String to be set for all of the chef-server-api URL's # configurable(:chef_server_url).writes_value do |uri| unless is_valid_url? uri raise ConfigurationError, "#{uri} is an invalid chef_server_url. The URL must start with http://, https://, or chefzero://." end uri.to_s.strip end # When you are using ActiveSupport, they monkey-patch 'daemonize' into Kernel. # So while this is basically identical to what method_missing would do, we pull # it up here and get a real method written so that things get dispatched # properly. configurable(:daemonize).writes_value { |v| v } def self.expand_relative_paths(path) unless path.nil? if path.is_a?(String) File.expand_path(path) else Array(path).map { |path| File.expand_path(path) } end end end configurable(:cookbook_path).writes_value { |path| expand_relative_paths(path) } configurable(:chef_repo_path).writes_value { |path| expand_relative_paths(path) } # The root where all local chef object data is stored. cookbooks, data bags, # environments are all assumed to be in separate directories under this. # chef-solo uses these directories for input data. knife commands # that upload or download files (such as knife upload, knife role from file, # etc.) work. default :chef_repo_path do if configuration[:cookbook_path] if configuration[:cookbook_path].is_a?(String) File.expand_path("..", configuration[:cookbook_path]) else configuration[:cookbook_path].map do |path| File.expand_path("..", path) end end elsif configuration[:cookbook_artifact_path] File.expand_path("..", configuration[:cookbook_artifact_path]) else cache_path end end def self.find_chef_repo_path(cwd) # In local mode, we auto-discover the repo root by looking for a path with "cookbooks" under it. # This allows us to run config-free. path = cwd until File.directory?(PathHelper.join(path, "cookbooks")) || File.directory?(PathHelper.join(path, "cookbook_artifacts")) new_path = File.expand_path("..", path) if new_path == path ChefConfig.logger.warn("No cookbooks directory found at or above current directory. Assuming #{cwd}.") return cwd end path = new_path end ChefConfig.logger.info("Auto-discovered #{ChefUtils::Dist::Infra::SHORT} repository at #{path}") path end # @param child_path [String] def self.derive_path_from_chef_repo_path(child_path) if chef_repo_path.is_a?(String) PathHelper.join(chef_repo_path, child_path) else chef_repo_path.uniq.map { |path| PathHelper.join(path, child_path) } end end # Location of acls on disk. String or array of strings. # Defaults to /acls. default(:acl_path) { derive_path_from_chef_repo_path("acls") }.writes_value { |path| expand_relative_paths(path) } # Location of clients on disk. String or array of strings. # Defaults to /clients. default(:client_path) { derive_path_from_chef_repo_path("clients") }.writes_value { |path| expand_relative_paths(path) } # Location of client keys on disk. String or array of strings. # Defaults to /client_keys. default(:client_key_path) { derive_path_from_chef_repo_path("client_keys") }.writes_value { |path| expand_relative_paths(path) } # Location of containers on disk. String or array of strings. # Defaults to /containers. default(:container_path) { derive_path_from_chef_repo_path("containers") }.writes_value { |path| expand_relative_paths(path) } # Location of cookbook_artifacts on disk. String or array of strings. # Defaults to /cookbook_artifacts. default(:cookbook_artifact_path) { derive_path_from_chef_repo_path("cookbook_artifacts") }.writes_value { |path| expand_relative_paths(path) } # Location of cookbooks on disk. String or array of strings. # Defaults to /cookbooks. If chef_repo_path # is not specified, this is set to /var/chef/cookbooks. default(:cookbook_path) { derive_path_from_chef_repo_path("cookbooks") } # Location of data bags on disk. String or array of strings. # Defaults to /data_bags. default(:data_bag_path) { derive_path_from_chef_repo_path("data_bags") }.writes_value { |path| expand_relative_paths(path) } # Location of environments on disk. String or array of strings. # Defaults to /environments. default(:environment_path) { derive_path_from_chef_repo_path("environments") }.writes_value { |path| expand_relative_paths(path) } # Location of groups on disk. String or array of strings. # Defaults to /groups. default(:group_path) { derive_path_from_chef_repo_path("groups") }.writes_value { |path| expand_relative_paths(path) } # Location of nodes on disk. String or array of strings. # Defaults to /nodes. default(:node_path) { derive_path_from_chef_repo_path("nodes") }.writes_value { |path| expand_relative_paths(path) } # Location of policies on disk. String or array of strings. # Defaults to /policies. default(:policy_path) { derive_path_from_chef_repo_path("policies") }.writes_value { |path| expand_relative_paths(path) } # Location of policy_groups on disk. String or array of strings. # Defaults to /policy_groups. default(:policy_group_path) { derive_path_from_chef_repo_path("policy_groups") }.writes_value { |path| expand_relative_paths(path) } # Location of roles on disk. String or array of strings. # Defaults to /roles. default(:role_path) { derive_path_from_chef_repo_path("roles") }.writes_value { |path| expand_relative_paths(path) } # Location of users on disk. String or array of strings. # Defaults to /users. default(:user_path) { derive_path_from_chef_repo_path("users") }.writes_value { |path| expand_relative_paths(path) } # DEPRECATED default :enforce_path_sanity, false # Enforce default paths by default for all APIs, not just the default internal shell_out default :enforce_default_paths, false # Formatted Chef Client output is a beta feature, disabled by default: default :formatter, "null" # The number of times the client should retry when registering with the server default :client_registration_retries, 5 # An array of paths to search for knife exec scripts if they aren't in the current directory default :script_path, [] # The root of all caches (checksums, cache and backup). If local mode is on, # this is under the user's home directory. default(:cache_path) do if local_mode PathHelper.join(config_dir, "local-mode-cache") else primary_cache_root = var_root_dir primary_cache_path = var_chef_dir # Use /var/chef as the cache path only if that folder exists and we can read and write # into it, or /var exists and we can read and write into it (we'll create /var/chef later). # Otherwise, we'll create .chef under the user's home directory and use that as # the cache path. unless path_accessible?(primary_cache_path) || path_accessible?(primary_cache_root) secondary_cache_path = PathHelper.join(user_home, ChefUtils::Dist::Infra::USER_CONF_DIR) secondary_cache_path = target_mode? ? PathHelper.join(secondary_cache_path, target_mode.host) : secondary_cache_path ChefConfig.logger.trace("Unable to access cache at #{primary_cache_path}. Switching cache to #{secondary_cache_path}") secondary_cache_path else target_mode? ? PathHelper.join(primary_cache_path, target_mode.host) : primary_cache_path end end end # Returns true only if the path exists and is readable and writeable for the user. # # @param path [String] def self.path_accessible?(path) File.exist?(path) && File.readable?(path) && File.writable?(path) end # Where cookbook files are stored on the server (by content checksum) default(:checksum_path) { PathHelper.join(cache_path, "checksums") } # Where chef's cache files should be stored default(:file_cache_path) { PathHelper.join(cache_path, "cache") }.writes_value { |path| expand_relative_paths(path) } # Where backups of chef-managed files should go default(:file_backup_path) { PathHelper.join(cache_path, "backup") } # The chef-client (or solo) lockfile. # # If your `file_cache_path` resides on a NFS (or non-flock()-supporting # fs), it's recommended to set this to something like # '/tmp/chef-client-running.pid' default(:lockfile) { PathHelper.join(file_cache_path, "#{ChefUtils::Dist::Infra::CLIENT}-running.pid") } ## Daemonization Settings ## # What user should Chef run as? default :user, nil default :group, nil default :umask, 0022 # Valid log_levels are: # * :trace # * :debug # * :info # * :warn # * :fatal # These work as you'd expect. There is also a special `:auto` setting. # When set to :auto, Chef will auto adjust the log verbosity based on # context. When a tty is available (usually because the user is running chef # in a console), the log level is set to :warn, and output formatters are # used as the primary mode of output. When a tty is not available, the # logger is the primary mode of output, and the log level is set to :info default :log_level, :auto # Logging location as either an IO stream or string representing log file path default :log_location, nil # Using `force_formatter` causes chef to default to formatter output when STDOUT is not a tty default :force_formatter, false # Using `force_logger` causes chef to default to logger output when STDOUT is a tty default :force_logger, false # When set to true always print the stacktrace even if we haven't done -l debug default :always_dump_stacktrace, false # Using 'stream_execute_output' will have Chef always stream the execute output default :stream_execute_output, false # Using `show_download_progress` will display the overall progress # of a remote file download default :show_download_progress, false # How often to update the progress meter, in percent default :download_progress_interval, 10 default :http_retry_count, 5 default :http_retry_delay, 5 # Whether or not to send the Authorization header again on http redirects. # As per the plan in https://github.com/chef/chef/pull/7006, this will be # False in Chef 14, True in Chef 15, and will be removed entirely in Chef 16. default :http_disable_auth_on_redirect, true default :interval, nil default :once, nil default :json_attribs, nil # toggle info level log items that can create a lot of output default :verbose_logging, true default :node_name, nil default :diff_disabled, false default :diff_filesize_threshold, 10000000 default :diff_output_threshold, 1000000 # This is true for "local mode" which uses a chef-zero server listening on # localhost one way or another. This is true for both `chef-solo` (without # the --legacy-mode flag) or `chef-client -z` methods of starting a client run. # default :local_mode, false # Configures the mode of operation for ChefFS, which is applied to the # ChefFS-based knife commands and chef-client's local mode. (ChefFS-based # knife commands include: knife delete, knife deps, knife diff, knife down, # knife edit, knife list, knife show, knife upload, and knife xargs.) # # Valid values are: # * "static": ChefFS only manages objects that exist in a traditional Chef # Repo as of Chef 11. # * "everything": ChefFS manages all object types that existed on the OSS # Chef 11 server. # * "hosted_everything": ChefFS manages all object types as of the Chef 12 # Server, including RBAC objects and Policyfile objects (new to Chef 12). default :repo_mode do if local_mode && !chef_zero.osc_compat "hosted_everything" elsif %r{/+organizations/.+}.match?(chef_server_url) "hosted_everything" else "everything" end end default :pid_file, nil # Whether Chef Zero local mode should bind to a port. All internal requests # will go through the socketless code path regardless, so the socket is # only needed if other processes will connect to the local mode server. default :listen, false config_context :chef_zero do config_strict_mode true default(:enabled) { ChefConfig::Config.local_mode } default :host, "localhost" default :port, 8889.upto(9999) # Will try ports from 8889-9999 until one works # When set to a String, Chef Zero disables multitenant support. This is # what you want when using Chef Zero to serve a single Chef Repo. Setting # this to `false` enables multi-tenant. default :single_org, "chef" # Whether Chef Zero should operate in a mode analogous to OSS Chef Server # 11 (true) or Chef Server 12 (false). Chef Zero can still serve # policyfile objects in Chef 11 mode, as long as `repo_mode` is set to # "hosted_everything". The primary differences are: # * Chef 11 mode doesn't support multi-tenant, so there is no # distinction between global and org-specific objects (since there are # no orgs). # * Chef 11 mode doesn't expose RBAC objects default :osc_compat, false end # RFCxxx Target Mode support, value is the name of a remote device to Chef against # --target exists as a shortcut to enabling target_mode and setting the host configurable(:target) config_context :target_mode do config_strict_mode false # we don't want to have to add all train configuration keys here default :enabled, false default :protocol, "ssh" # typical additional keys: host, user, password end def self.target_mode? target_mode.enabled end default :chef_server_url, "https://localhost:443" default(:chef_server_root) do # if the chef_server_url is a path to an organization, aka # 'some_url.../organizations/*' then remove the '/organization/*' by default if %r{/organizations/\S*$}.match?(configuration[:chef_server_url]) configuration[:chef_server_url].split("/")[0..-3].join("/") elsif configuration[:chef_server_url] # default to whatever chef_server_url is configuration[:chef_server_url] else "https://localhost:443" end end default :rest_timeout, 300 # This solo setting is now almost entirely useless. It is set to true if chef-solo was # invoked that way from the command-line (i.e. from Application::Solo as opposed to # Application::Client). The more useful information is contained in the :solo_legacy_mode # vs the :local_mode flags which will be set to true or false depending on how solo was # invoked and actually change more of the behavior. There might be slight differences in # the behavior of :local_mode due to the behavioral differences in Application::Solo vs. # Application::Client and `chef-solo` vs `chef-client -z`, but checking this value and # switching based on it is almost certainly doing the wrong thing and papering over # bugs that should be fixed in one or the other class, and will be brittle and destined # to break in the future (and not necessarily on a major version bump). Checking this value # is also not sufficient to determine if we are not running against a server since this can # be unset but :local_mode may be set. It would be accurate to check both :solo and :local_mode # to determine if we're not running against a server, but the more semantically accurate test # is going to be combining :solo_legacy_mode and :local_mode. # # TL;DR: `if Chef::Config[:solo]` is almost certainly buggy code, you should use: # `if Chef::Config[:local_mode] || Chef::Config[:solo_legacy_mode]` # # @api private default :solo, false # This is true for old chef-solo legacy mode without any chef-zero server (chef-solo --legacy-mode) default :solo_legacy_mode, false default :splay, nil default :why_run, false default :color, false default :client_fork, nil default :ez, false default :enable_reporting, true default :enable_reporting_url_fatals, false # Chef only needs ohai to run the hostname plugin for the most basic # functionality. If the rest of the ohai plugins are not needed (like in # most of our testing scenarios) default :minimal_ohai, false # When consuming Ohai plugins from cookbook segments, we place those plugins in this directory. # Subsequent chef client runs will wipe and re-populate the directory to ensure cleanliness default(:ohai_segment_plugin_path) { PathHelper.join(config_dir, "ohai", "cookbook_plugins") } ### # Policyfile Settings # # Policyfile is a feature where a node gets its run list and cookbook # version set from a single document on the server instead of expanding the # run list and having the server compute the cookbook version set based on # environment constraints. # # Policyfiles are auto-versioned. The user groups nodes by `policy_name`, # which generally describes a hosts's functional role, and `policy_group`, # which generally groups nodes by deployment phase (a.k.a., "environment"). # The Chef Server maps a given set of `policy_name` plus `policy_group` to # a particular revision of a policy. default :policy_name, nil default :policy_group, nil # Policyfiles can have multiple run lists, via the named run list feature. # Generally this will be set by a CLI option via Chef::Application::Client, # but it could be set in client.rb if desired. default :named_run_list, nil # Policyfiles can be used in a native mode (default) or compatibility mode. # Native mode requires Chef Server 12.1 (it can be enabled via feature flag # on some prior versions). In native mode, policies and associated # cookbooks are accessed via feature-specific APIs. In compat mode, # policies are stored as data bags and cookbooks are stored at the # cookbooks/ endpoint. Compatibility mode can be dangerous on existing Chef # Servers; it's recommended to upgrade your Chef Server rather than use # compatibility mode. Compatibility mode remains available so you can use # policyfiles with servers that don't yet support the native endpoints. default :policy_document_native_api, true # When policyfiles are used in compatibility mode, `policy_name` and # `policy_group` are instead specified using a combined configuration # setting, `deployment_group`. For example, if policy_name should be # "webserver" and policy_group should be "staging", then `deployment_group` # should be set to "webserver-staging", which is the name of the data bag # item that the policy will be stored as. NOTE: this setting only has an # effect if `policy_document_native_api` is set to `false`. default :deployment_group, nil # Set these to enable SSL authentication / mutual-authentication # with the server # Client side SSL cert/key for mutual auth default :ssl_client_cert, nil default :ssl_client_key, nil # Whether or not to verify the SSL cert for all HTTPS requests. When set to # :verify_peer (default), all HTTPS requests will be validated regardless of other # SSL verification settings. When set to :verify_none no HTTPS requests will # be validated. default :ssl_verify_mode, :verify_peer # Needed to coerce string value to a symbol when loading settings from the # credentials toml files which doesn't allow ruby symbol values configurable(:ssl_verify_mode).writes_value do |value| if value.is_a?(String) && value[0] == ":" value[1..].to_sym else value.to_sym end end # Whether or not to verify the SSL cert for HTTPS requests to the Chef # server API. If set to `true`, the server's cert will be validated # regardless of the :ssl_verify_mode setting. This is set to `true` when # running in local-mode. # NOTE: This is a workaround until verify_peer is enabled by default. default(:verify_api_cert) { ChefConfig::Config.local_mode } # Path to the default CA bundle files. default :ssl_ca_path, nil default(:ssl_ca_file) do if ChefUtils.windows? && embedded_dir cacert_path = File.join(embedded_dir, "ssl/certs/cacert.pem") cacert_path if File.exist?(cacert_path) else nil end end # A directory that contains additional SSL certificates to trust. Any # certificates in this directory will be added to whatever CA bundle ruby # is using. Use this to add self-signed certs for your Chef Server or local # HTTP file servers. default(:trusted_certs_dir) { PathHelper.join(config_dir, "trusted_certs") } # A directory that contains additional configuration scripts to load for chef-client default(:client_d_dir) { PathHelper.join(config_dir, "client.d") } # A directory that contains additional configuration scripts to load for solo default(:solo_d_dir) { PathHelper.join(config_dir, "solo.d") } # A directory that contains additional configuration scripts to load for # the workstation config default(:config_d_dir) { PathHelper.join(config_dir, "config.d") } # Where should chef-solo download recipes from? default :recipe_url, nil # Set to true if Chef is to set OpenSSL to run in FIPS mode default(:fips) do # CHEF_FIPS is used in testing to override checking for system level # enablement. There are 3 possible values that this variable may have: # nil - no override and the system will be checked # empty - FIPS is NOT enabled # a non empty value - FIPS is enabled if ENV["CHEF_FIPS"] == "" false else !ENV["CHEF_FIPS"].nil? || ChefConfig.fips? end end # Initialize openssl def self.init_openssl if fips enable_fips_mode end end # Sets the version of the signed header authentication protocol to use (see # the 'mixlib-authorization' project for more detail). Currently, versions # 1.0, 1.1, and 1.3 are available. default :authentication_protocol_version do if fips || ssh_agent_signing "1.3" else "1.1" end end # This key will be used to sign requests to the Chef server. This location # must be writable by Chef during initial setup when generating a client # identity on the server. # # The chef-server will look up the public key for the client using the # `node_name` of the client. # # If chef-zero is enabled, this defaults to nil (no authentication). default(:client_key) do if chef_zero.enabled nil elsif target_mode? PathHelper.cleanpath("#{etc_chef_dir}/#{target_mode.host}/client.pem") else PathHelper.cleanpath("#{etc_chef_dir}/client.pem") end end # A credentials file may contain a complete client key, rather than the path # to one. # # We'll use this preferentially. default :client_key_contents, nil # When registering the client, should we allow the client key location to # be a symlink? eg: /etc/chef/client.pem -> /etc/chef/prod-client.pem # If the path of the key goes through a directory like /tmp this should # never be set to true or its possibly an easily exploitable security hole. default :follow_client_key_symlink, false # Enable ssh-agent signing mode. This requires {client_key} be set to a # public key rather than the usual private key. default :ssh_agent_signing, false # This secret is used to decrypt encrypted data bag items. default(:encrypted_data_bag_secret) do if target_mode? && File.exist?(PathHelper.cleanpath("#{etc_chef_dir}/#{target_mode.host}/encrypted_data_bag_secret")) PathHelper.cleanpath("#{etc_chef_dir}/#{target_mode.host}/encrypted_data_bag_secret") elsif File.exist?(PathHelper.cleanpath("#{etc_chef_dir}/encrypted_data_bag_secret")) PathHelper.cleanpath("#{etc_chef_dir}/encrypted_data_bag_secret") else nil end end # As of Chef 13.0, version "3" is the default encrypted data bag item # format. # default :data_bag_encrypt_version, 3 # When reading data bag items, any supported version is accepted. However, # if all encrypted data bags have been generated with the version 2 format, # it is recommended to disable support for earlier formats to improve # security. For example, the version 2 format is identical to version 1 # except for the addition of an HMAC, so an attacker with MITM capability # could downgrade an encrypted data bag to version 1 as part of an attack. default :data_bag_decrypt_minimum_version, 0 # If there is no file in the location given by `client_key`, chef-client # will temporarily use the "validator" identity to generate one. If the # `client_key` is not present and the `validation_key` is also not present, # chef-client will not be able to authenticate to the server. # # The `validation_key` is never used if the `client_key` exists. # # If chef-zero is enabled, this defaults to nil (no authentication). default(:validation_key) { chef_zero.enabled ? nil : PathHelper.cleanpath("#{etc_chef_dir}/validation.pem") } default :validation_client_name do # If the URL is set and looks like a normal Chef Server URL, extract the # org name and use that as part of the default. if chef_server_url.to_s =~ %r{/organizations/(.*)$} "#{$1}-validator" else "#{ChefUtils::Dist::Infra::SHORT}-validator" end end default :validation_key_contents, nil # When creating a new client via the validation_client account, Chef 11 # servers allow the client to generate a key pair locally and send the # public key to the server. This is more secure and helps offload work from # the server, enhancing scalability. If enabled and the remote server # implements only the Chef 10 API, client registration will not work # properly. # # The default value is `true`. Set to `false` to disable client-side key # generation (server generates client keys). default(:local_key_generation) { true } # Zypper package provider gpg checks. Set to false to disable package # gpg signature checking globally. This will warn you that it is a # bad thing to do. default :zypper_check_gpg, true # Report Handlers default :report_handlers, [] # Event Handlers default :event_handlers, [] default :disable_event_loggers, false # Exception Handlers default :exception_handlers, [] # Start handlers default :start_handlers, [] # Syntax Check Cache. Knife keeps track of files that is has already syntax # checked by storing files in this directory. `syntax_check_cache_path` is # the new (and preferred) configuration setting. If not set, knife will # fall back to using cache_options[:path], which is deprecated but exists in # many client configs generated by pre-Chef-11 bootstrappers. default(:syntax_check_cache_path) { cache_options[:path] }.writes_value { |path| expand_relative_paths(path) } # Deprecated: # Move this to the default value of syntax_cache_path when this is removed. default(:cache_options) { { path: PathHelper.join(config_dir, "syntaxcache") } } # Whether errors should be raised for deprecation warnings. When set to # `false` (the default setting), a warning is emitted but code using # deprecated methods/features/etc. should work normally otherwise. When set # to `true`, usage of deprecated methods/features will raise a # `DeprecatedFeatureError`. This is used by Chef's tests to ensure that # deprecated functionality is not used internally by Chef. End users # should generally leave this at the default setting (especially in # production), but it may be useful when testing cookbooks or other code if # the user wishes to aggressively address deprecations. default(:treat_deprecation_warnings_as_errors) do # Using an environment variable allows this setting to be inherited in # tests that spawn new processes. ENV.key?("CHEF_TREAT_DEPRECATION_WARNINGS_AS_ERRORS") end # Which deprecations warnings to silence. Can be set to `true` to silence # all warnings, or an array of strings like either `"deprecation_type"` or # `"filename.rb:lineno"`. default :silence_deprecation_warnings, [] # Whether the resource count should be updated for log resource # on running chef-client default :count_log_resource_updates, false # The selected profile when using credentials. default :profile, nil default :chef_guid_path do PathHelper.join(config_dir, "#{ChefUtils::Dist::Infra::SHORT}_guid") end default :chef_guid, nil # knife configuration data config_context :knife do default :hints, {} end def self.set_defaults_for_windows # Those lists of regular expressions define what chef considers a # valid user and group name # From http://technet.microsoft.com/en-us/library/cc776019(WS.10).aspx principal_valid_regex_part = '[^"\/\\\\\[\]\:;|=,+*?<>]+' default :user_valid_regex, [ /^(#{principal_valid_regex_part}\\)?#{principal_valid_regex_part}$/ ] default :group_valid_regex, [ /^(#{principal_valid_regex_part}\\)?#{principal_valid_regex_part}$/ ] default :fatal_windows_admin_check, false end def self.set_defaults_for_nix # Those lists of regular expressions define what chef considers a # valid user and group name # # user/group cannot start with '-', '+' or '~' # user/group cannot contain ':', ',' or non-space-whitespace or null byte # everything else is allowed (UTF-8, spaces, etc) and we delegate to your O/S useradd program to barf or not # copies: http://anonscm.debian.org/viewvc/pkg-shadow/debian/trunk/debian/patches/506_relaxed_usernames?view=markup default :user_valid_regex, [ /^[^-+~:,\t\r\n\f\0]+[^:,\t\r\n\f\0]*$/ ] default :group_valid_regex, [ /^[^-+~:,\t\r\n\f\0]+[^:,\t\r\n\f\0]*$/ ] end # Those lists of regular expressions define what chef considers a # valid user and group name if ChefUtils.windows? set_defaults_for_windows else set_defaults_for_nix end # This provides a hook which rspec can stub so that we can avoid twiddling # global state in tests. def self.env ENV end def self.windows_home_path ChefConfig.logger.deprecation("Chef::Config.windows_home_path is now deprecated. Consider using Chef::Util::PathHelper.home instead.") PathHelper.home end # returns a platform specific path to the user home dir if set, otherwise default to current directory. default( :user_home ) { PathHelper.home || Dir.pwd } # Enable file permission fixup for selinux. Fixup will be done # only if selinux is enabled in the system. default :enable_selinux_file_permission_fixup, true # Use atomic updates (i.e. move operation) while updating contents # of the files resources. When set to false copy operation is # used to update files. # # NOTE: CHANGING THIS SETTING MAY CAUSE CORRUPTION, DATA LOSS AND # INSTABILITY. # default :file_atomic_update, true # There are 3 possible values for this configuration setting. # true => file staging is done in the destination directory # false => file staging is done via tempfiles under ENV['TMP'] # :auto => file staging will try using destination directory if possible and # will fall back to ENV['TMP'] if destination directory is not usable. # default :file_staging_uses_destdir, :auto # Exit if another run is in progress and the chef-client is unable to # get the lock before time expires. If nil, no timeout is enforced. (Exits # immediately if 0.) # default :run_lock_timeout, nil # Number of worker threads for syncing cookbooks in parallel. Increasing # this number can result in gateway errors from the server (namely 503 and 504). # If you are seeing this behavior while using the default setting, reducing # the number of threads will help. # default :cookbook_sync_threads, 10 # True if all resources by default default to unified mode, with all resources # applying in "compile" mode, with no "converge" mode. False is backwards compatible # setting for Chef 11-15 behavior. This will break forward notifications. # default :resource_unified_mode_default, false # At the beginning of the Chef Client run, the cookbook manifests are downloaded which # contain URLs for every file in every relevant cookbook. Most of the files # (recipes, resources, providers, libraries, etc) are immediately synchronized # at the start of the run. The handling of "files" and "templates" directories, # however, have two modes of operation. They can either all be downloaded immediately # at the start of the run (no_lazy_load==true) or else they can be lazily loaded as # cookbook_file or template resources are converged which require them (no_lazy_load==false). # # The advantage of lazily loading these files is that unnecessary files are not # synchronized. This may be useful to users with large files checked into cookbooks which # are only selectively downloaded to a subset of clients which use the cookbook. However, # better solutions are to either isolate large files into individual cookbooks and only # include those cookbooks in the run lists of the servers that need them -- or move to # using remote_file and a more appropriate backing store like S3 for large file # distribution. # # The disadvantages of lazily loading files are that users some time find it # confusing that their cookbooks are not fully synchronized to the cache initially, # and more importantly the time-sensitive URLs which are in the manifest may time # out on long Chef runs before the resource that uses the file is converged # (leading to many confusing 403 errors on template/cookbook_file resources). # default :no_lazy_load, true # A array of attributes you want sent over the wire when node # data is saved. The default setting is nil, which collects all data. # NOTE: Setting to [] will not collect ANY data to save. default :allowed_automatic_attributes, nil default :allowed_default_attributes, nil default :allowed_normal_attributes, nil default :allowed_override_attributes, nil # An array of attributes you do not want to send over the # wire when node data is saved # The default setting is nil, which collects all data. # NOTE: Setting to [] will still collect all data to save default :blocked_automatic_attributes, nil default :blocked_default_attributes, nil default :blocked_normal_attributes, nil default :blocked_override_attributes, nil # deprecated config options that will be removed in Chef Infra Client 17 default :automatic_attribute_blacklist, nil default :default_attribute_blacklist, nil default :normal_attribute_blacklist, nil default :override_attribute_blacklist, nil default :automatic_attribute_whitelist, nil default :default_attribute_whitelist, nil default :normal_attribute_whitelist, nil default :override_attribute_whitelist, nil # Pull down all the rubygems versions from rubygems and cache them the first time we do a gem_package or # chef_gem install. This is memory-expensive and will grow without bounds, but will reduce network # round trips. default :rubygems_cache_enabled, false config_context :windows_service do # Set `watchdog_timeout` to the number of seconds to wait for a chef-client run # to finish default :watchdog_timeout, 2 * (60 * 60) # 2 hours end # Add an empty and non-strict config_context for chefdk and chefcli. # This lets the user have code like `chefdk.generator_cookbook "/path/to/cookbook"` or # `chefcli[:generator_cookbook] = "/path/to/cookbook"` in their config.rb, # and it will be ignored by tools like knife and ohai. ChefDK and ChefCLI # themselves can define the config options it accepts and enable strict mode, # and that will only apply when running `chef` commands. config_context :chefdk do end config_context :chefcli do end # Configuration options for Data Collector reporting. These settings allow # the user to configure where to send their Data Collector data, what token # to send, and whether Data Collector should report its findings in client # mode vs. solo mode. config_context :data_collector do # Full URL to the endpoint that will receive our data. If nil, the # data collector will not run. # Ex: http://my-data-collector.mycompany.com/ingest default(:server_url) do if config_parent.solo_legacy_mode || config_parent.local_mode nil else File.join(config_parent.chef_server_url, "/data-collector") end end # An optional pre-shared token to pass as an HTTP header (x-data-collector-token) # that can be used to determine whether or not the poster of this # run data should be trusted. # Ex: some-uuid-here default :token, nil # The Chef mode during which Data Collector is allowed to function. This # can be used to run Data Collector only when running as Chef Solo but # not when using Chef Client. # Options: :solo (for both Solo Legacy Mode and Client Local Mode), :client, :both default :mode, :both # When the Data Collector cannot send the "starting a run" message to # the Data Collector server, the Data Collector will be disabled for that # run. In some situations, such as highly-regulated environments, it # may be more reasonable to prevent Chef from performing the actual run. # In these situations, setting this value to true will cause the Chef # run to raise an exception before starting any converge activities. default :raise_on_failure, false # A user-supplied Organization string that can be sent in payloads # generated by the DataCollector when Chef is run in Solo mode. This # allows users to associate their Solo nodes with faux organizations # without the nodes being connected to an actual Chef Server. default :organization, "#{ChefUtils::Dist::Infra::SHORT}_solo" end configurable(:http_proxy) configurable(:http_proxy_user) configurable(:http_proxy_pass) configurable(:https_proxy) configurable(:https_proxy_user) configurable(:https_proxy_pass) configurable(:ftp_proxy) configurable(:ftp_proxy_user) configurable(:ftp_proxy_pass) configurable(:no_proxy) # Public method that users should call to export proxies to the appropriate # environment variables. This method should be called after the config file is # parsed and loaded. # TODO add some post-file-parsing logic that automatically calls this so # users don't have to def self.export_proxies export_proxy("http", http_proxy, http_proxy_user, http_proxy_pass) if key?(:http_proxy) && http_proxy export_proxy("https", https_proxy, https_proxy_user, https_proxy_pass) if key?(:https_proxy) && https_proxy export_proxy("ftp", ftp_proxy, ftp_proxy_user, ftp_proxy_pass) if key?(:ftp_proxy) && ftp_proxy export_no_proxy(no_proxy) if key?(:no_proxy) && no_proxy end # Builds a proxy uri and exports it to the appropriate environment variables. Examples: # http://username:password@hostname:port # https://username@hostname:port # ftp://hostname:port # when # scheme = "http", "https", or "ftp" # hostport = hostname:port or scheme://hostname:port # user = username # pass = password # @api private def self.export_proxy(scheme, path, user, pass) # Character classes for Addressable # See https://www.ietf.org/rfc/rfc3986.txt 3.2.1 # The user part may not have a : in it user_class = Addressable::URI::CharacterClasses::UNRESERVED + Addressable::URI::CharacterClasses::SUB_DELIMS # The password part may have any valid USERINFO characters password_class = user_class + "\\:" path = "#{scheme}://#{path}" unless path.include?("://") # URI.split returns the following parts: # [scheme, userinfo, host, port, registry, path, opaque, query, fragment] uri = Addressable::URI.encode(path, Addressable::URI) if user && !user.empty? userinfo = Addressable::URI.encode_component(user, user_class) if pass userinfo << ":#{Addressable::URI.encode_component(pass, password_class)}" end uri.userinfo = userinfo end path = uri.to_s ENV["#{scheme}_proxy".downcase] = path unless ENV["#{scheme}_proxy".downcase] ENV["#{scheme}_proxy".upcase] = path unless ENV["#{scheme}_proxy".upcase] end # @api private def self.export_no_proxy(value) ENV["no_proxy"] = value unless ENV["no_proxy"] ENV["NO_PROXY"] = value unless ENV["NO_PROXY"] end # Given a scheme, host, and port, return the correct proxy URI based on the # set environment variables, unless excluded by no_proxy, in which case nil # is returned def self.proxy_uri(scheme, host, port) proxy_env_var = ENV["#{scheme}_proxy"].to_s.strip # Check if the proxy string contains a scheme. If not, add the url's scheme to the # proxy before parsing. The regex /^.*:\/\// matches, for example, http://. Reusing proxy # here since we are really just trying to get the string built correctly. proxy = unless proxy_env_var.empty? if %r{^.*://}.match?(proxy_env_var) URI.parse(proxy_env_var) else URI.parse("#{scheme}://#{proxy_env_var}") end end return proxy unless fuzzy_hostname_match_any?(host, ENV["no_proxy"]) end # Chef requires an English-language UTF-8 locale to function properly. We attempt # to use the 'locale -a' command and search through a list of preferences until we # find one that we can use. On Ubuntu systems we should find 'C.UTF-8' and be # able to use that even if there is no English locale on the server, but Mac, Solaris, # AIX, etc do not have that locale. We then try to find an English locale and fall # back to 'C' if we do not. The choice of fallback is pick-your-poison. If we try # to do the work to return a non-US UTF-8 locale then we fail inside of providers when # things like 'svn info' return Japanese and we can't parse them. OTOH, if we pick 'C' then # we will blow up on UTF-8 characters. Between the warn we throw and the Encoding # exception that ruby will throw it is more obvious what is broken if we drop UTF-8 by # default rather than drop English. # # If there is no 'locale -a' then we return 'en_US.UTF-8' since that is the most commonly # available English UTF-8 locale. However, all modern POSIXen should support 'locale -a'. def self.guess_internal_locale # https://github.com/chef/chef/issues/2181 # Some systems have the `locale -a` command, but the result has # invalid characters for the default encoding. # # For example, on CentOS 6 with ENV['LANG'] = "en_US.UTF-8", # `locale -a`.split fails with ArgumentError invalid UTF-8 encoding. cmd = Mixlib::ShellOut.new("locale -a").run_command cmd.error! locales = cmd.stdout.split case when locales.include?("C.UTF-8") "C.UTF-8" when locales.include?("en_US.UTF-8"), locales.include?("en_US.utf8") "en_US.UTF-8" when locales.include?("en.UTF-8") "en.UTF-8" else # Will match en_ZZ.UTF-8, en_ZZ.utf-8, en_ZZ.UTF8, en_ZZ.utf8 guesses = locales.select { |l| l =~ /^en_.*UTF-?8$/i } unless guesses.empty? guessed_locale = guesses.first # Transform into the form en_ZZ.UTF-8 guessed_locale.gsub(/UTF-?8$/i, "UTF-8") else ChefConfig.logger.warn "Please install an English UTF-8 locale for #{ChefUtils::Dist::Infra::PRODUCT} to use, falling back to C locale and disabling UTF-8 support." "C" end end rescue if ChefUtils.windows? ChefConfig.logger.trace "Defaulting to locale en_US.UTF-8 on Windows, until it matters that we do something else." else ChefConfig.logger.trace "No usable locale -a command found, assuming you have en_US.UTF-8 installed." end "en_US.UTF-8" end default :internal_locale, guess_internal_locale # Force UTF-8 Encoding, for when we fire up in the 'C' locale or other strange locales (e.g. # japanese windows encodings). If we do not do this, then knife upload will fail when a cookbook's # README.md has UTF-8 characters that do not encode in whatever surrounding encoding we have been # passed. Effectively, the Chef Ecosystem is globally UTF-8 by default. Anyone who wants to be # able to upload Shift_JIS or ISO-8859-1 files needs to mark *those* files explicitly with # magic tags to make ruby correctly identify the encoding being used. Changing this default will # break Chef community cookbooks and is very highly discouraged. default :ruby_encoding, Encoding::UTF_8 # can be set to a string or array of strings for URIs to set as rubygems sources default :rubygems_url, nil # globally sets the default of the clear_sources property on the gem_package and chef_gem resources default :clear_gem_sources, nil # If installed via an omnibus installer, this gives the path to the # "embedded" directory which contains all of the software packaged with # omnibus. This is used to locate the cacert.pem file on windows. def self.embedded_dir Pathname.new(_this_file).ascend do |path| if path.basename.to_s == "embedded" return path.to_s end end nil end # Path to this file in the current install. def self._this_file File.expand_path(__FILE__) end # Set fips mode in openssl. Do any patching necessary to make # sure Chef runs do not crash. # @api private def self.enable_fips_mode OpenSSL.fips_mode = true require "digest" unless defined?(Digest) require "digest/sha1" unless defined?(Digest::SHA1) require "digest/md5" unless defined?(Digest::MD5) # Remove pre-existing constants if they do exist to reduce the # amount of log spam and warnings. Digest.send(:remove_const, "SHA1") if Digest.const_defined?("SHA1") Digest.const_set("SHA1", OpenSSL::Digest::SHA1) OpenSSL::Digest.send(:remove_const, "MD5") if OpenSSL::Digest.const_defined?("MD5") OpenSSL::Digest.const_set("MD5", Digest::MD5) ChefConfig.logger.debug "FIPS mode is enabled." end end end chef-config-16.12.3/lib/chef-config/version.rb0000644000175100017510000000134114034030210017774 0ustar pravipravi# Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module ChefConfig CHEFCONFIG_ROOT = File.expand_path("..", __dir__) VERSION = "16.12.3".freeze end chef-config-16.12.3/lib/chef-config/windows.rb0000644000175100017510000000137614034030210020011 0ustar pravipravi# # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "chef-utils" unless defined?(ChefUtils::CANARY) module ChefConfig def self.windows? ChefUtils.windows? end end chef-config-16.12.3/lib/chef-config/exceptions.rb0000644000175100017510000000153114034030210020471 0ustar pravipravi# # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require_relative "windows" require_relative "logger" module ChefConfig class ConfigurationError < ArgumentError; end class InvalidPath < StandardError; end class UnparsableConfigOption < StandardError; end end chef-config-16.12.3/lib/chef-config/logger.rb0000644000175100017510000000246214034030210017573 0ustar pravipravi# # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module ChefConfig # Implements enough of Logger's API that we can use it in place of a real # logger for `ChefConfig.logger` class NullLogger def <<(_msg); end def add(_severity, _message = nil, _progname = nil); end def trace(_progname = nil, &block); end def debug(_progname = nil, &block); end def info(_progname = nil, &block); end def warn(_progname = nil, &block); end def deprecation(_progname = nil, &block); end def error(_progname = nil, &block); end def fatal(_progname = nil, &block); end end @logger = NullLogger.new def self.logger=(new_logger) @logger = new_logger end def self.logger @logger end end chef-config-16.12.3/chef-config.gemspec0000644000175100017510000000272714034030210016572 0ustar pravipravilib = File.expand_path("lib", __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "chef-config/version" Gem::Specification.new do |spec| spec.name = "chef-config" spec.version = ChefConfig::VERSION spec.authors = ["Adam Jacob"] spec.email = ["adam@chef.io"] spec.summary = %q{Chef Infra's default configuration and config loading library} spec.homepage = "https://github.com/chef/chef" spec.license = "Apache-2.0" spec.required_ruby_version = ">= 2.6.0" spec.metadata = { "bug_tracker_uri" => "https://github.com/chef/chef/issues", "changelog_uri" => "https://github.com/chef/chef/blob/master/CHANGELOG.md", "documentation_uri" => "https://github.com/chef/chef/tree/master/chef-config/README.md", "homepage_uri" => "https://github.com/chef/chef/tree/master/chef-config", "source_code_uri" => "https://github.com/chef/chef/tree/master/chef-config", } spec.require_paths = ["lib"] spec.add_dependency "chef-utils", "= #{ChefConfig::VERSION}" spec.add_dependency "mixlib-shellout", ">= 2.0", "< 4.0" spec.add_dependency "mixlib-config", ">= 2.2.12", "< 4.0" spec.add_dependency "fuzzyurl" spec.add_dependency "addressable" spec.add_dependency "tomlrb", "~> 1.2" spec.files = %w{Rakefile LICENSE} + Dir.glob("*.gemspec") + Dir.glob("{lib,spec}/**/*", File::FNM_DOTMATCH).reject { |f| File.directory?(f) } spec.bindir = "bin" spec.executables = [] end chef-config-16.12.3/LICENSE0000644000175100017510000002514214034030210014056 0ustar pravipravi Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.