1 # frozen_string_literal: true
7 # Ruby 3.0 changed net-ftp to a default gem
11 Puppet::Type.type(:apt_key).provide(:apt_key) do
12 desc 'apt-key provider for apt_key resource'
14 confine osfamily: :debian
15 defaultfor osfamily: :debian
16 commands apt_key: 'apt-key'
17 commands gpg: '/usr/bin/gpg'
20 cli_args = ['adv', '--no-tty', '--list-keys', '--with-colons', '--fingerprint', '--fixed-list-mode']
22 key_output = apt_key(cli_args).encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
24 pub_line, sub_line, fpr_line = nil
26 key_array = key_output.split("\n").map do |line|
27 if line.start_with?('pub')
29 # reset fpr_line, to skip any previous subkeys which were collected
32 elsif line.start_with?('sub')
34 elsif line.start_with?('fpr')
38 if sub_line && fpr_line
39 sub_line, fpr_line = nil
43 next unless pub_line && fpr_line
45 line_hash = key_line_hash(pub_line, fpr_line)
48 pub_line, fpr_line = nil
52 expired = Time.now >= line_hash[:key_expiry] if line_hash[:key_expiry]
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],
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'),
71 def self.prefetch(resources)
73 resources.each_key do |name|
76 provider = apt_keys.find { |key| key.fingerprint == name }
77 resources[name].provider = provider if provider
79 provider = apt_keys.find { |key| key.long == name }
80 resources[name].provider = provider if provider
82 provider = apt_keys.find { |key| key.short == name }
83 resources[name].provider = provider if provider
88 def self.key_line_hash(pub_line, fpr_line)
89 pub_split = pub_line.split(':')
90 fpr_split = fpr_line.split(':')
92 fingerprint = fpr_split.last
94 key_fingerprint: fingerprint,
95 key_long: fingerprint[-16..], # last 16 characters of fingerprint
96 key_short: fingerprint[-8..], # last 8 characters of fingerprint
97 key_size: pub_split[2],
99 key_created: Time.at(pub_split[5].to_i),
100 key_expiry: pub_split[6].empty? ? nil : Time.at(pub_split[6].to_i)
103 # set key type based on types defined in /usr/share/doc/gnupg/DETAILS.gz
106 return_hash[:key_type] = :rsa
108 return_hash[:key_type] = :dsa
110 return_hash[:key_type] = :ecc
112 return_hash[:key_type] = :ecdsa
118 def source_to_file(value)
119 parsed_value = URI.parse(value)
120 if parsed_value.scheme.nil?
121 raise(_('The file %{_value} does not exist') % { _value: value }) unless File.exist?(value)
123 # Because the tempfile method has to return a live object to prevent GC
124 # of the underlying file from occuring too early, we also have to return
125 # a file object here. The caller can still call the #path method on the
126 # closed file handle to get the path.
127 f = File.open(value, 'r')
131 exceptions = [OpenURI::HTTPError]
132 exceptions << Net::FTPPermError if defined?(Net::FTPPermError)
135 # Only send basic auth if URL contains userinfo
136 # Some webservers (e.g. Amazon S3) return code 400 if empty basic auth is sent
137 if parsed_value.userinfo.nil?
138 key = if parsed_value.scheme == 'https' && resource[:weak_ssl] == true
139 URI.open(parsed_value, ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE).read
144 user_pass = parsed_value.userinfo.split(':')
145 parsed_value.userinfo = ''
146 key = URI.open(parsed_value, http_basic_authentication: user_pass).read
148 rescue *exceptions => e
149 raise(_('%{_e} for %{_resource}') % { _e: e.message, _resource: resource[:source] })
151 raise(_('could not resolve %{_resource}') % { _resource: resource[:source] })
158 # The tempfile method needs to return the tempfile object to the caller, so
159 # that it doesn't get deleted by the GC immediately after it returns. We
160 # want the caller to control when it goes out of scope.
161 def tempfile(content)
162 file = Tempfile.new('apt_key')
165 # confirm that the fingerprint from the file, matches the long key that is in the manifest
167 if File.executable? command(:gpg)
168 extracted_key = execute(["#{command(:gpg)} --no-tty --with-fingerprint --with-colons #{file.path} | awk -F: '/^fpr:/ { print $10 }'"], failonfail: false)
169 extracted_key = extracted_key.chomp
172 extracted_key.each_line do |line|
173 found_match = true if line.chomp == name
176 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
179 warning('/usr/bin/gpg cannot be found for verification of the id.')
186 # report expired keys as non-existing when refresh => true
187 @property_hash[:ensure] == :present && !(resource[:refresh] && @property_hash[:expired])
192 if resource[:source].nil? && resource[:content].nil?
193 # Breaking up the command like this is needed because it blows up
194 # if --recv-keys isn't the last argument.
195 command.push('adv', '--no-tty', '--keyserver', resource[:server])
196 command.push('--keyserver-options', resource[:options]) unless resource[:options].nil?
197 command.push('--recv-keys', resource[:id])
198 elsif resource[:content]
199 key_file = tempfile(resource[:content])
200 command.push('add', key_file.path)
201 elsif resource[:source]
202 key_file = source_to_file(resource[:source])
203 command.push('add', key_file.path)
204 # In case we really screwed up, better safe than sorry.
206 raise(_('an unexpected condition occurred while trying to add the key: %{_resource}') % { _resource: resource[:id] })
209 @property_hash[:ensure] = :present
214 apt_key('del', resource.provider.short)
215 r = execute(["#{command(:apt_key)} list | grep '/#{resource.provider.short}\s'"], failonfail: false)
216 break unless r.exitstatus.zero?
221 def read_only(_value)
222 raise(_('This is a read-only property.'))
227 # Alias the setters of read-only properties
228 # to the read_only function.
229 alias_method :created=, :read_only
230 alias_method :expired=, :read_only
231 alias_method :expiry=, :read_only
232 alias_method :size=, :read_only
233 alias_method :type=, :read_only