MODULES-10956 remove redundant code in provider apt_key
[puppet-modules/puppetlabs-apt.git] / lib / puppet / provider / apt_key / apt_key.rb
1 # frozen_string_literal: true
2
3 require 'open-uri'
4 require 'net/ftp'
5 require 'tempfile'
6
7 Puppet::Type.type(:apt_key).provide(:apt_key) do
8   desc 'apt-key provider for apt_key resource'
9
10   confine    osfamily: :debian
11   defaultfor osfamily: :debian
12   commands   apt_key: 'apt-key'
13   commands   gpg: '/usr/bin/gpg'
14
15   def self.instances
16     cli_args = ['adv', '--no-tty', '--list-keys', '--with-colons', '--fingerprint', '--fixed-list-mode']
17
18     key_output = apt_key(cli_args).encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
19
20     pub_line, sub_line, fpr_line = nil
21
22     key_array = key_output.split("\n").map do |line|
23       if line.start_with?('pub')
24         pub_line = line
25         # reset fpr_line, to skip any previous subkeys which were collected
26         fpr_line = nil
27         sub_line = nil
28       elsif line.start_with?('sub')
29         sub_line = line
30       elsif line.start_with?('fpr')
31         fpr_line = line
32       end
33
34       if sub_line && fpr_line
35         sub_line, fpr_line = nil
36         next
37       end
38
39       next unless pub_line && fpr_line
40
41       line_hash = key_line_hash(pub_line, fpr_line)
42
43       # reset everything
44       pub_line, fpr_line = nil
45
46       expired = false
47
48       if line_hash[:key_expiry]
49         expired = Time.now >= line_hash[:key_expiry]
50       end
51
52       new(
53         name: line_hash[:key_fingerprint],
54         id: line_hash[:key_long],
55         fingerprint: line_hash[:key_fingerprint],
56         short: line_hash[:key_short],
57         long: line_hash[:key_long],
58         ensure: :present,
59         expired: expired,
60         expiry: line_hash[:key_expiry].nil? ? nil : line_hash[:key_expiry].strftime('%Y-%m-%d'),
61         size: line_hash[:key_size],
62         type: line_hash[:key_type],
63         created: line_hash[:key_created].strftime('%Y-%m-%d'),
64       )
65     end
66     key_array.compact!
67   end
68
69   def self.prefetch(resources)
70     apt_keys = instances
71     resources.each_key do |name|
72       if name.length == 40
73         provider = apt_keys.find { |key| key.fingerprint == name }
74         resources[name].provider = provider if provider
75       elsif name.length == 16
76         provider = apt_keys.find { |key| key.long == name }
77         resources[name].provider = provider if provider
78       elsif name.length == 8
79         provider = apt_keys.find { |key| key.short == name }
80         resources[name].provider = provider if provider
81       end
82     end
83   end
84
85   def self.key_line_hash(pub_line, fpr_line)
86     pub_split = pub_line.split(':')
87     fpr_split = fpr_line.split(':')
88
89     fingerprint = fpr_split.last
90     return_hash = {
91       key_fingerprint: fingerprint,
92       key_long: fingerprint[-16..-1], # last 16 characters of fingerprint
93       key_short: fingerprint[-8..-1], # last 8 characters of fingerprint
94       key_size: pub_split[2],
95       key_type: nil,
96       key_created: Time.at(pub_split[5].to_i),
97       key_expiry: pub_split[6].empty? ? nil : Time.at(pub_split[6].to_i),
98     }
99
100     # set key type based on types defined in /usr/share/doc/gnupg/DETAILS.gz
101     case pub_split[3]
102     when '1'
103       return_hash[:key_type] = :rsa
104     when '17'
105       return_hash[:key_type] = :dsa
106     when '18'
107       return_hash[:key_type] = :ecc
108     when '19'
109       return_hash[:key_type] = :ecdsa
110     end
111
112     return_hash
113   end
114
115   def source_to_file(value)
116     parsed_value = URI.parse(value)
117     if parsed_value.scheme.nil?
118       raise(_('The file %{_value} does not exist') % { _value: value }) unless File.exist?(value)
119       # Because the tempfile method has to return a live object to prevent GC
120       # of the underlying file from occuring too early, we also have to return
121       # a file object here.  The caller can still call the #path method on the
122       # closed file handle to get the path.
123       f = File.open(value, 'r')
124       f.close
125       f
126     else
127       begin
128         # Only send basic auth if URL contains userinfo
129         # Some webservers (e.g. Amazon S3) return code 400 if empty basic auth is sent
130         if parsed_value.userinfo.nil?
131           key = if parsed_value.scheme == 'https' && resource[:weak_ssl] == true
132                   open(parsed_value, ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE).read
133                 else
134                   parsed_value.read
135                 end
136         else
137           user_pass = parsed_value.userinfo.split(':')
138           parsed_value.userinfo = ''
139           key = open(parsed_value, http_basic_authentication: user_pass).read
140         end
141       rescue OpenURI::HTTPError, Net::FTPPermError => e
142         raise(_('%{_e} for %{_resource}') % { _e: e.message, _resource: resource[:source] })
143       rescue SocketError
144         raise(_('could not resolve %{_resource}') % { _resource: resource[:source] })
145       else
146         tempfile(key)
147       end
148     end
149   end
150
151   # The tempfile method needs to return the tempfile object to the caller, so
152   # that it doesn't get deleted by the GC immediately after it returns.  We
153   # want the caller to control when it goes out of scope.
154   def tempfile(content)
155     file = Tempfile.new('apt_key')
156     file.write content
157     file.close
158     # confirm that the fingerprint from the file, matches the long key that is in the manifest
159     if name.size == 40
160       if File.executable? command(:gpg)
161         extracted_key = execute(["#{command(:gpg)} --no-tty --with-fingerprint --with-colons #{file.path} | awk -F: '/^fpr:/ { print $10 }'"], failonfail: false)
162         extracted_key = extracted_key.chomp
163
164         found_match = false
165         extracted_key.each_line do |line|
166           if line.chomp == name
167             found_match = true
168           end
169         end
170         unless found_match
171           raise(_('The id in your manifest %{_resource} and the fingerprint from content/source don\'t match. Check for an error in the id and content/source is legitimate.') % { _resource: resource[:name] }) # rubocop:disable Layout/LineLength
172         end
173       else
174         warning('/usr/bin/gpg cannot be found for verification of the id.')
175       end
176     end
177     file
178   end
179
180   def exists?
181     # report expired keys as non-existing when refresh => true
182     @property_hash[:ensure] == :present && !(resource[:refresh] && @property_hash[:expired])
183   end
184
185   def create
186     command = []
187     if resource[:source].nil? && resource[:content].nil?
188       # Breaking up the command like this is needed because it blows up
189       # if --recv-keys isn't the last argument.
190       command.push('adv', '--no-tty', '--keyserver', resource[:server])
191       unless resource[:options].nil?
192         command.push('--keyserver-options', resource[:options])
193       end
194       command.push('--recv-keys', resource[:id])
195     elsif resource[:content]
196       key_file = tempfile(resource[:content])
197       command.push('add', key_file.path)
198     elsif resource[:source]
199       key_file = source_to_file(resource[:source])
200       command.push('add', key_file.path)
201     # In case we really screwed up, better safe than sorry.
202     else
203       raise(_('an unexpected condition occurred while trying to add the key: %{_resource}') % { _resource: resource[:id] })
204     end
205     apt_key(command)
206     @property_hash[:ensure] = :present
207   end
208
209   def destroy
210     loop do
211       apt_key('del', resource.provider.short)
212       r = execute(["#{command(:apt_key)} list | grep '/#{resource.provider.short}\s'"], failonfail: false)
213       break unless r.exitstatus.zero?
214     end
215     @property_hash.clear
216   end
217
218   def read_only(_value)
219     raise(_('This is a read-only property.'))
220   end
221
222   mk_resource_methods
223
224   # Alias the setters of read-only properties
225   # to the read_only function.
226   alias_method :created=, :read_only
227   alias_method :expired=, :read_only
228   alias_method :expiry=, :read_only
229   alias_method :size=, :read_only
230   alias_method :type=, :read_only
231 end