Don't truncate to short keys in the type
[puppet-modules/puppetlabs-apt.git] / lib / puppet / provider / apt_key / apt_key.rb
1 require 'date'
2 require 'open-uri'
3 require 'net/ftp'
4 require 'tempfile'
5
6 if RUBY_VERSION == '1.8.7'
7   # Mothers cry, puppies die and Ruby 1.8.7's open-uri needs to be
8   # monkeypatched to support passing in :ftp_passive_mode.
9   require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..',
10                                     'puppet_x', 'apt_key', 'patch_openuri.rb'))
11   OpenURI::Options.merge!({:ftp_active_mode => false,})
12 end
13
14 Puppet::Type.type(:apt_key).provide(:apt_key) do
15
16   KEY_LINE = {
17     :date     => '[0-9]{4}-[0-9]{2}-[0-9]{2}',
18     :key_type => '(R|D)',
19     :key_size => '\d{4}',
20     :key_id   => '[0-9a-fA-F]+',
21     :expires  => 'expire(d|s)',
22   }
23
24   confine    :osfamily => :debian
25   defaultfor :osfamily => :debian
26   commands   :apt_key  => 'apt-key'
27
28   def self.instances
29     if RUBY_VERSION > '1.8.7'
30       key_output = apt_key('list').encode('UTF-8', 'binary', :invalid => :replace, :undef => :replace, :replace => '')
31     else
32       key_output = apt_key('list')
33     end
34     key_array = key_output.split("\n").collect do |line|
35       line_hash = key_line_hash(line)
36       next unless line_hash
37       expired = false
38
39       if line_hash[:key_expiry]
40         expired = Date.today > Date.parse(line_hash[:key_expiry])
41       end
42
43       new(
44         :name    => line_hash[:key_id],
45         :id      => line_hash[:key_id],
46         :ensure  => :present,
47         :expired => expired,
48         :expiry  => line_hash[:key_expiry],
49         :size    => line_hash[:key_size],
50         :type    => line_hash[:key_type] == 'R' ? :rsa : :dsa,
51         :created => line_hash[:key_created]
52       )
53     end
54     key_array.compact!
55   end
56
57   def self.prefetch(resources)
58     apt_keys = instances
59     resources.keys.each do |name|
60       if name.length == 16
61         shortname=name[8..-1]
62       else
63         shortname=name
64       end
65       if provider = apt_keys.find{ |key| key.name == shortname }
66         resources[name].provider = provider
67       end
68     end
69   end
70
71   def self.key_line_hash(line)
72     line_array = line.match(key_line_regexp).to_a
73     return nil if line_array.length < 5
74
75     return_hash = {
76       :key_id      => line_array[3],
77       :key_size    => line_array[1],
78       :key_type    => line_array[2],
79       :key_created => line_array[4],
80       :key_expiry  => nil,
81     }
82
83     return_hash[:key_expiry] = line_array[7] if line_array.length == 8
84     return return_hash
85   end
86
87   def self.key_line_regexp
88     # This regexp is trying to match the following output
89     # pub   4096R/4BD6EC30 2010-07-10 [expires: 2016-07-08]
90     # pub   1024D/CD2EFD2A 2009-12-15
91     regexp = /\A
92       pub  # match only the public key, not signatures
93       \s+  # bunch of spaces after that
94       (#{KEY_LINE[:key_size]})  # size of the key, usually a multiple of 1024
95       #{KEY_LINE[:key_type]}  # type of the key, usually R or D
96       \/  # separator between key_type and key_id
97       (#{KEY_LINE[:key_id]})  # hex id of the key
98       \s+  # bunch of spaces after that
99       (#{KEY_LINE[:date]})  # date the key was added to the keyring
100       # following an optional block which indicates if the key has an expiration
101       # date and if it has expired yet
102       (
103         \s+  # again with thes paces
104         \[  # we open with a square bracket
105         #{KEY_LINE[:expires]}  # expires or expired
106         \:  # a colon
107         \s+  # more spaces
108         (#{KEY_LINE[:date]})  # date indicating key expiry
109         \]  # we close with a square bracket
110       )?  # end of the optional block
111       \Z/x
112       regexp
113   end
114
115   def source_to_file(value)
116     if URI::parse(value).scheme.nil?
117       fail("The file #{value} does not exist") unless File.exists?(value)
118       value
119     else
120       begin
121         key = open(value, :ftp_active_mode => false).read
122       rescue OpenURI::HTTPError, Net::FTPPermError => e
123         fail("#{e.message} for #{resource[:source]}")
124       rescue SocketError
125         fail("could not resolve #{resource[:source]}")
126       else
127         tempfile(key)
128       end
129     end
130   end
131
132   def tempfile(content)
133     file = Tempfile.new('apt_key')
134     file.write content
135     file.close
136     file.path
137   end
138
139   def exists?
140     @property_hash[:ensure] == :present
141   end
142
143   def create
144     command = []
145     if resource[:source].nil? and resource[:content].nil?
146       # Breaking up the command like this is needed because it blows up
147       # if --recv-keys isn't the last argument.
148       command.push('adv', '--keyserver', resource[:server])
149       unless resource[:keyserver_options].nil?
150         command.push('--keyserver-options', resource[:keyserver_options])
151       end
152       command.push('--recv-keys', resource[:id])
153     elsif resource[:content]
154       command.push('add', tempfile(resource[:content]))
155     elsif resource[:source]
156       command.push('add', source_to_file(resource[:source]))
157     # In case we really screwed up, better safe than sorry.
158     else
159       fail("an unexpected condition occurred while trying to add the key: #{resource[:id]}")
160     end
161     apt_key(command)
162     @property_hash[:ensure] = :present
163   end
164
165   def destroy
166     apt_key('del', resource[:id])
167     @property_hash.clear
168   end
169
170   def read_only(value)
171     fail('This is a read-only property.')
172   end
173
174   mk_resource_methods
175
176   # Needed until PUP-1470 is fixed and we can drop support for Puppet versions
177   # before that.
178   def expired
179     @property_hash[:expired]
180   end
181
182   # Alias the setters of read-only properties
183   # to the read_only function.
184   alias :created= :read_only
185   alias :expired= :read_only
186   alias :expiry=  :read_only
187   alias :size=    :read_only
188   alias :type=    :read_only
189 end