diff --git a/lib/localhost/authority.rb b/lib/localhost/authority.rb index 7ace655..ddfb3bb 100644 --- a/lib/localhost/authority.rb +++ b/lib/localhost/authority.rb @@ -184,7 +184,7 @@ def load(path = @root) certificate_path = File.join(path, "#{@hostname}.crt") key_path = File.join(path, "#{@hostname}.key") - + return false unless File.exist?(certificate_path) and File.exist?(key_path) certificate = OpenSSL::X509::Certificate.new(File.read(certificate_path)) @@ -228,12 +228,10 @@ def save(path = @root) def ensure_authority_path_exists(path = @root) old_root = File.expand_path("~/.localhost") - if File.directory?(old_root) and not File.directory?(path) - # Migrates the legacy dir ~/.localhost/ to the XDG compliant directory - File.rename(old_root, path) - elsif not File.directory?(path) - FileUtils.makedirs(path, mode: 0700) - end + FileUtils.mkdir_p(path, mode: 0700) unless File.directory?(path) + + # Migrates the legacy dir ~/.localhost/ to the XDG compliant directory + FileUtils.mv("#{@old_root}/.", path, force: true) if File.directory?(old_root) end end end diff --git a/test/localhost/authority.rb b/test/localhost/authority.rb index c771f14..dfe1799 100644 --- a/test/localhost/authority.rb +++ b/test/localhost/authority.rb @@ -17,12 +17,31 @@ require 'tempfile' describe Localhost::Authority do + def before + @old_root = File.expand_path("~/.localhost") + @old_root_exists = File.directory?(@old_root) + + if @old_root_exists + @tmp_folder = File.expand_path("~/.localhost_test") + FileUtils.mkdir_p(@tmp_folder, mode: 0700) + FileUtils.cp_r("#{@old_root}/.", @tmp_folder) + end + end + + def after + if @old_root_exists + FileUtils.mkdir_p(@old_root, mode: 0700) + FileUtils.mv("#{@tmp_folder}/.", @old_root, force: true) + FileUtils.rm_r(@tmp_folder) + end + end + let(:xdg_dir) { File.join(Dir.pwd, "state") } let(:authority) { ENV["XDG_STATE_HOME"] = xdg_dir subject.new } - + with '#certificate' do it "is not valid for more than 1 year" do certificate = authority.certificate @@ -47,23 +66,23 @@ authority.save(authority.class.path) expect(File).to be(:exist?, authority.certificate_path) expect(File).to be(:exist?, authority.key_path) - + expect(authority.key_path).to be == File.join(xdg_dir, "localhost.rb", "localhost.key") expect(authority.certificate_path).to be == File.join(xdg_dir, "localhost.rb", "localhost.crt") end - + it "properly falls back when XDG_STATE_HOME is not set" do ENV.delete("XDG_STATE_HOME") authority = subject.new - + authority.save(authority.class.path) expect(File).to be(:exist?, authority.certificate_path) expect(File).to be(:exist?, authority.key_path) - + expect(authority.key_path).to be == File.join(File.expand_path("~/.local/state/"), "localhost.rb", "localhost.key") expect(authority.certificate_path).to be == File.join(File.expand_path("~/.local/state/"), "localhost.rb", "localhost.crt") end - + with '#store' do it "can verify certificate" do expect(authority.store.verify(authority.certificate)).to be == true