6087: Use app-configured key by default for blob signing and verification.
[arvados.git] / services / api / app / models / collection.rb
1 require 'arvados/keep'
2
3 class Collection < ArvadosModel
4   extend DbCurrentTime
5   include HasUuid
6   include KindAndEtag
7   include CommonApiTemplate
8
9   serialize :properties, Hash
10
11   before_validation :check_encoding
12   before_validation :check_signatures
13   before_validation :strip_manifest_text
14   before_validation :set_portable_data_hash
15   before_validation :maybe_clear_replication_confirmed
16   validate :ensure_hash_matches_manifest_text
17   before_save :set_file_names
18
19   # Query only undeleted collections by default.
20   default_scope where("expires_at IS NULL or expires_at > CURRENT_TIMESTAMP")
21
22   api_accessible :user, extend: :common do |t|
23     t.add :name
24     t.add :description
25     t.add :properties
26     t.add :portable_data_hash
27     t.add :signed_manifest_text, as: :manifest_text
28     t.add :replication_desired
29     t.add :replication_confirmed
30     t.add :replication_confirmed_at
31   end
32
33   def self.attributes_required_columns
34     super.merge(
35                 # If we don't list manifest_text explicitly, the
36                 # params[:select] code gets confused by the way we
37                 # expose signed_manifest_text as manifest_text in the
38                 # API response, and never let clients select the
39                 # manifest_text column.
40                 'manifest_text' => ['manifest_text'],
41                 )
42   end
43
44   def check_signatures
45     return false if self.manifest_text.nil?
46
47     return true if current_user.andand.is_admin
48
49     # Provided the manifest_text hasn't changed materially since an
50     # earlier validation, it's safe to pass this validation on
51     # subsequent passes without checking any signatures. This is
52     # important because the signatures have probably been stripped off
53     # by the time we get to a second validation pass!
54     return true if @signatures_checked and @signatures_checked == compute_pdh
55
56     if self.manifest_text_changed?
57       # Check permissions on the collection manifest.
58       # If any signature cannot be verified, raise PermissionDeniedError
59       # which will return 403 Permission denied to the client.
60       api_token = current_api_client_authorization.andand.api_token
61       signing_opts = {
62         api_token: api_token,
63         now: db_current_time.to_i,
64       }
65       self.manifest_text.lines.each do |entry|
66         entry.split[1..-1].each do |tok|
67           if /^[[:digit:]]+:[[:digit:]]+:/.match tok
68             # This is a filename token, not a blob locator. Note that we
69             # keep checking tokens after this, even though manifest
70             # format dictates that all subsequent tokens will also be
71             # filenames. Safety first!
72           elsif Blob.verify_signature tok, signing_opts
73             # OK.
74           elsif Keep::Locator.parse(tok).andand.signature
75             # Signature provided, but verify_signature did not like it.
76             logger.warn "Invalid signature on locator #{tok}"
77             raise ArvadosModel::PermissionDeniedError
78           elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
79             # No signature provided, but we are running in insecure mode.
80             logger.debug "Missing signature on locator #{tok} ignored"
81           elsif Blob.new(tok).empty?
82             # No signature provided -- but no data to protect, either.
83           else
84             logger.warn "Missing signature on locator #{tok}"
85             raise ArvadosModel::PermissionDeniedError
86           end
87         end
88       end
89     end
90     @signatures_checked = compute_pdh
91   end
92
93   def strip_manifest_text
94     if self.manifest_text_changed?
95       # Remove any permission signatures from the manifest.
96       self.class.munge_manifest_locators!(self[:manifest_text]) do |loc|
97         loc.without_signature.to_s
98       end
99     end
100     true
101   end
102
103   def set_portable_data_hash
104     if (portable_data_hash.nil? or
105         portable_data_hash == "" or
106         (manifest_text_changed? and !portable_data_hash_changed?))
107       @need_pdh_validation = false
108       self.portable_data_hash = compute_pdh
109     elsif portable_data_hash_changed?
110       @need_pdh_validation = true
111       begin
112         loc = Keep::Locator.parse!(self.portable_data_hash)
113         loc.strip_hints!
114         if loc.size
115           self.portable_data_hash = loc.to_s
116         else
117           self.portable_data_hash = "#{loc.hash}+#{portable_manifest_text.bytesize}"
118         end
119       rescue ArgumentError => e
120         errors.add(:portable_data_hash, "#{e}")
121         return false
122       end
123     end
124     true
125   end
126
127   def ensure_hash_matches_manifest_text
128     return true unless manifest_text_changed? or portable_data_hash_changed?
129     # No need verify it if :set_portable_data_hash just computed it!
130     return true if not @need_pdh_validation
131     expect_pdh = compute_pdh
132     if expect_pdh != portable_data_hash
133       errors.add(:portable_data_hash,
134                  "does not match computed hash #{expect_pdh}")
135       return false
136     end
137   end
138
139   def set_file_names
140     if self.manifest_text_changed?
141       self.file_names = manifest_files
142     end
143     true
144   end
145
146   def manifest_files
147     names = ''
148     if self.manifest_text
149       self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
150         names << name.first.gsub('\040',' ') + "\n"
151         break if names.length > 2**12
152       end
153     end
154
155     if self.manifest_text and names.length < 2**12
156       self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
157         names << stream_name.first.gsub('\040',' ') + "\n"
158         break if names.length > 2**12
159       end
160     end
161
162     names[0,2**12]
163   end
164
165   def check_encoding
166     if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
167       true
168     else
169       begin
170         # If Ruby thinks the encoding is something else, like 7-bit
171         # ASCII, but its stored bytes are equal to the (valid) UTF-8
172         # encoding of the same string, we declare it to be a UTF-8
173         # string.
174         utf8 = manifest_text
175         utf8.force_encoding Encoding::UTF_8
176         if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
177           manifest_text = utf8
178           return true
179         end
180       rescue
181       end
182       errors.add :manifest_text, "must use UTF-8 encoding"
183       false
184     end
185   end
186
187   def signed_manifest_text
188     if has_attribute? :manifest_text
189       token = current_api_client_authorization.andand.api_token
190       @signed_manifest_text = self.class.sign_manifest manifest_text, token
191     end
192   end
193
194   def self.sign_manifest manifest, token
195     signing_opts = {
196       api_token: token,
197       expire: db_current_time.to_i + Rails.configuration.blob_signature_ttl,
198     }
199     m = manifest.dup
200     munge_manifest_locators!(m) do |loc|
201       Blob.sign_locator(loc.to_s, signing_opts)
202     end
203     return m
204   end
205
206   def self.munge_manifest_locators! manifest
207     # Given a manifest text and a block, yield each locator,
208     # and replace it with whatever the block returns.
209     manifest.andand.gsub!(/ [[:xdigit:]]{32}(\+\S+)?/) do |word|
210       if loc = Keep::Locator.parse(word.strip)
211         " " + yield(loc)
212       else
213         " " + word
214       end
215     end
216   end
217
218   def self.each_manifest_locator manifest
219     # Given a manifest text and a block, yield each locator.
220     manifest.andand.scan(/ ([[:xdigit:]]{32}(\+\S+)?)/) do |word, _|
221       if loc = Keep::Locator.parse(word)
222         yield loc
223       end
224     end
225   end
226
227   def self.normalize_uuid uuid
228     hash_part = nil
229     size_part = nil
230     uuid.split('+').each do |token|
231       if token.match /^[0-9a-f]{32,}$/
232         raise "uuid #{uuid} has multiple hash parts" if hash_part
233         hash_part = token
234       elsif token.match /^\d+$/
235         raise "uuid #{uuid} has multiple size parts" if size_part
236         size_part = token
237       end
238     end
239     raise "uuid #{uuid} has no hash part" if !hash_part
240     [hash_part, size_part].compact.join '+'
241   end
242
243   # Return array of Collection objects
244   def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil)
245     readers ||= [Thread.current[:user]]
246     base_search = Link.
247       readable_by(*readers).
248       readable_by(*readers, table_name: "collections").
249       joins("JOIN collections ON links.head_uuid = collections.uuid").
250       order("links.created_at DESC")
251
252     # If the search term is a Collection locator that contains one file
253     # that looks like a Docker image, return it.
254     if loc = Keep::Locator.parse(search_term)
255       loc.strip_hints!
256       coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1).first
257       if coll_match
258         # Check if the Collection contains exactly one file whose name
259         # looks like a saved Docker image.
260         manifest = Keep::Manifest.new(coll_match.manifest_text)
261         if manifest.exact_file_count?(1) and
262             (manifest.files[0][1] =~ /^[0-9A-Fa-f]{64}\.tar$/)
263           return [coll_match]
264         end
265       end
266     end
267
268     if search_tag.nil? and (n = search_term.index(":"))
269       search_tag = search_term[n+1..-1]
270       search_term = search_term[0..n-1]
271     end
272
273     # Find Collections with matching Docker image repository+tag pairs.
274     matches = base_search.
275       where(link_class: "docker_image_repo+tag",
276             name: "#{search_term}:#{search_tag || 'latest'}")
277
278     # If that didn't work, find Collections with matching Docker image hashes.
279     if matches.empty?
280       matches = base_search.
281         where("link_class = ? and links.name LIKE ?",
282               "docker_image_hash", "#{search_term}%")
283     end
284
285     # Generate an order key for each result.  We want to order the results
286     # so that anything with an image timestamp is considered more recent than
287     # anything without; then we use the link's created_at as a tiebreaker.
288     uuid_timestamps = {}
289     matches.all.map do |link|
290       uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
291        -link.created_at.to_i]
292     end
293     Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c| uuid_timestamps[c.uuid] }
294   end
295
296   def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
297     find_all_for_docker_image(search_term, search_tag, readers).first
298   end
299
300   def self.searchable_columns operator
301     super - ["manifest_text"]
302   end
303
304   def self.full_text_searchable_columns
305     super - ["manifest_text"]
306   end
307
308   protected
309   def portable_manifest_text
310     portable_manifest = self[:manifest_text].dup
311     self.class.munge_manifest_locators!(portable_manifest) do |loc|
312       if loc.size
313         loc.hash + '+' + loc.size.to_s
314       else
315         loc.hash
316       end
317     end
318     portable_manifest
319   end
320
321   def compute_pdh
322     portable_manifest = portable_manifest_text
323     (Digest::MD5.hexdigest(portable_manifest) +
324      '+' +
325      portable_manifest.bytesize.to_s)
326   end
327
328   def maybe_clear_replication_confirmed
329     if manifest_text_changed?
330       # If the new manifest_text contains locators whose hashes
331       # weren't in the old manifest_text, storage replication is no
332       # longer confirmed.
333       in_old_manifest = {}
334       self.class.each_manifest_locator(manifest_text_was) do |loc|
335         in_old_manifest[loc.hash] = true
336       end
337       self.class.each_manifest_locator(manifest_text) do |loc|
338         if not in_old_manifest[loc.hash]
339           self.replication_confirmed_at = nil
340           self.replication_confirmed = nil
341           break
342         end
343       end
344     end
345   end
346
347   def ensure_permission_to_save
348     if (not current_user.andand.is_admin and
349         (replication_confirmed_at_changed? or replication_confirmed_changed?) and
350         not (replication_confirmed_at.nil? and replication_confirmed.nil?))
351       raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
352     end
353     super
354   end
355 end