From e34cef0cd2fcf9a01d3f3b6dd215bbcc25d65d27 Mon Sep 17 00:00:00 2001 From: Alexis Reigel Date: Wed, 22 Feb 2017 17:20:42 +0100 Subject: [PATCH] extract gpg functionality to lib class --- app/models/gpg_key.rb | 6 +----- lib/gitlab/gpg.rb | 32 ++++++++++++++++++++++++++++++++ spec/lib/gitlab/gpg_spec.rb | 20 ++++++++++++++++++++ spec/spec_helper.rb | 8 +------- 4 files changed, 54 insertions(+), 12 deletions(-) create mode 100644 lib/gitlab/gpg.rb create mode 100644 spec/lib/gitlab/gpg_spec.rb diff --git a/app/models/gpg_key.rb b/app/models/gpg_key.rb index b012db1428f..aa0e8883a47 100644 --- a/app/models/gpg_key.rb +++ b/app/models/gpg_key.rb @@ -33,12 +33,8 @@ class GpgKey < ActiveRecord::Base private def extract_fingerprint - import = GPGME::Key.import(key) - - return if import.considered == 0 - # we can assume that the result only contains one item as the validation # only allows one key - self.fingerprint = import.imports.first.fingerprint + self.fingerprint = Gitlab::Gpg.fingerprints_from_key(key).first end end diff --git a/lib/gitlab/gpg.rb b/lib/gitlab/gpg.rb new file mode 100644 index 00000000000..373ef79ab85 --- /dev/null +++ b/lib/gitlab/gpg.rb @@ -0,0 +1,32 @@ +module Gitlab + module Gpg + extend self + + def fingerprints_from_key(key) + using_tmp_keychain do + import = GPGME::Key.import(key) + + return [] if import.imported == 0 + + import.imports.map(&:fingerprint) + end + end + + def using_tmp_keychain + Dir.mktmpdir do |dir| + @original_dirs ||= [GPGME::Engine.dirinfo('homedir')] + @original_dirs.push(dir) + + GPGME::Engine.home_dir = dir + + return_value = yield + + @original_dirs.pop + + GPGME::Engine.home_dir = @original_dirs[-1] + + return_value + end + end + end +end diff --git a/spec/lib/gitlab/gpg_spec.rb b/spec/lib/gitlab/gpg_spec.rb new file mode 100644 index 00000000000..a59302e6738 --- /dev/null +++ b/spec/lib/gitlab/gpg_spec.rb @@ -0,0 +1,20 @@ +require 'rails_helper' + +describe Gitlab::Gpg do + describe '.fingerprints_from_key' do + it 'returns the fingerprint' do + expect( + described_class.fingerprints_from_key(GpgHelpers.public_key) + ).to eq ['4F4840A503964251CF7D7F5DC728AF10972E97C0'] + end + + it 'returns an empty array when the key is invalid' do + expect( + described_class.fingerprints_from_key('bogus') + ).to eq [] + end + end + + describe '.add_to_keychain' do + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 6b4ec608efb..a0df233507b 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -143,14 +143,8 @@ RSpec.configure do |config| end config.around(:each, :gpg) do |example| - Dir.mktmpdir do |dir| - original_dir = GPGME::Engine.dirinfo('homedir') - - GPGME::Engine.home_dir = dir - + Gitlab::Gpg.using_tmp_keychain do example.run - - GPGME::Engine.home_dir = original_dir end end end