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