12707: Some fixes and additions on storage classes:
[arvados.git] / services / api / app / models / collection.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'arvados/keep'
6 require 'sweep_trashed_collections'
7 require 'trashable'
8
9 class Collection < ArvadosModel
10   extend CurrentApiClient
11   extend DbCurrentTime
12   include HasUuid
13   include KindAndEtag
14   include CommonApiTemplate
15   include Trashable
16
17   serialize :properties, Hash
18   serialize :storage_classes_desired, Array
19   serialize :storage_classes_confirmed, Array
20
21   before_validation :default_empty_manifest
22   before_validation :check_encoding
23   before_validation :check_manifest_validity
24   before_validation :check_signatures
25   before_validation :strip_signatures_and_update_replication_confirmed
26   validate :ensure_pdh_matches_manifest_text
27   validate :ensure_storage_classes_desired_is_not_empty
28   validate :ensure_storage_classes_contain_non_empty_strings
29   before_save :set_file_names
30
31   api_accessible :user, extend: :common do |t|
32     t.add :name
33     t.add :description
34     t.add :properties
35     t.add :portable_data_hash
36     t.add :signed_manifest_text, as: :manifest_text
37     t.add :manifest_text, as: :unsigned_manifest_text
38     t.add :replication_desired
39     t.add :replication_confirmed
40     t.add :replication_confirmed_at
41     t.add :storage_classes_desired
42     t.add :storage_classes_confirmed
43     t.add :storage_classes_confirmed_at
44     t.add :delete_at
45     t.add :trash_at
46     t.add :is_trashed
47   end
48
49   after_initialize do
50     @signatures_checked = false
51     @computed_pdh_for_manifest_text = false
52   end
53
54   def self.attributes_required_columns
55     super.merge(
56                 # If we don't list manifest_text explicitly, the
57                 # params[:select] code gets confused by the way we
58                 # expose signed_manifest_text as manifest_text in the
59                 # API response, and never let clients select the
60                 # manifest_text column.
61                 #
62                 # We need trash_at and is_trashed to determine the
63                 # correct timestamp in signed_manifest_text.
64                 'manifest_text' => ['manifest_text', 'trash_at', 'is_trashed'],
65                 'unsigned_manifest_text' => ['manifest_text'],
66                 )
67   end
68
69   def self.ignored_select_attributes
70     super + ["updated_at", "file_names"]
71   end
72
73   def self.limit_index_columns_read
74     ["manifest_text"]
75   end
76
77   FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
78   def check_signatures
79     return false if self.manifest_text.nil?
80
81     return true if current_user.andand.is_admin
82
83     # Provided the manifest_text hasn't changed materially since an
84     # earlier validation, it's safe to pass this validation on
85     # subsequent passes without checking any signatures. This is
86     # important because the signatures have probably been stripped off
87     # by the time we get to a second validation pass!
88     if @signatures_checked && @signatures_checked == computed_pdh
89       return true
90     end
91
92     if self.manifest_text_changed?
93       # Check permissions on the collection manifest.
94       # If any signature cannot be verified, raise PermissionDeniedError
95       # which will return 403 Permission denied to the client.
96       api_token = current_api_client_authorization.andand.api_token
97       signing_opts = {
98         api_token: api_token,
99         now: @validation_timestamp.to_i,
100       }
101       self.manifest_text.each_line do |entry|
102         entry.split.each do |tok|
103           if tok == '.' or tok.starts_with? './'
104             # Stream name token.
105           elsif tok =~ FILE_TOKEN
106             # This is a filename token, not a blob locator. Note that we
107             # keep checking tokens after this, even though manifest
108             # format dictates that all subsequent tokens will also be
109             # filenames. Safety first!
110           elsif Blob.verify_signature tok, signing_opts
111             # OK.
112           elsif Keep::Locator.parse(tok).andand.signature
113             # Signature provided, but verify_signature did not like it.
114             logger.warn "Invalid signature on locator #{tok}"
115             raise ArvadosModel::PermissionDeniedError
116           elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
117             # No signature provided, but we are running in insecure mode.
118             logger.debug "Missing signature on locator #{tok} ignored"
119           elsif Blob.new(tok).empty?
120             # No signature provided -- but no data to protect, either.
121           else
122             logger.warn "Missing signature on locator #{tok}"
123             raise ArvadosModel::PermissionDeniedError
124           end
125         end
126       end
127     end
128     @signatures_checked = computed_pdh
129   end
130
131   def strip_signatures_and_update_replication_confirmed
132     if self.manifest_text_changed?
133       in_old_manifest = {}
134       if not self.replication_confirmed.nil?
135         self.class.each_manifest_locator(manifest_text_was) do |match|
136           in_old_manifest[match[1]] = true
137         end
138       end
139
140       stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
141         if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
142           # If the new manifest_text contains locators whose hashes
143           # weren't in the old manifest_text, storage replication is no
144           # longer confirmed.
145           self.replication_confirmed_at = nil
146           self.replication_confirmed = nil
147         end
148
149         # Return the locator with all permission signatures removed,
150         # but otherwise intact.
151         match[0].gsub(/\+A[^+]*/, '')
152       end
153
154       if @computed_pdh_for_manifest_text == manifest_text
155         # If the cached PDH was valid before stripping, it is still
156         # valid after stripping.
157         @computed_pdh_for_manifest_text = stripped_manifest.dup
158       end
159
160       self[:manifest_text] = stripped_manifest
161     end
162     true
163   end
164
165   def ensure_pdh_matches_manifest_text
166     if not manifest_text_changed? and not portable_data_hash_changed?
167       true
168     elsif portable_data_hash.nil? or not portable_data_hash_changed?
169       self.portable_data_hash = computed_pdh
170     elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
171       errors.add(:portable_data_hash, "is not a valid locator")
172       false
173     elsif portable_data_hash[0..31] != computed_pdh[0..31]
174       errors.add(:portable_data_hash,
175                  "'#{portable_data_hash}' does not match computed hash '#{computed_pdh}'")
176       false
177     else
178       # Ignore the client-provided size part: always store
179       # computed_pdh in the database.
180       self.portable_data_hash = computed_pdh
181     end
182   end
183
184   def set_file_names
185     if self.manifest_text_changed?
186       self.file_names = manifest_files
187     end
188     true
189   end
190
191   def manifest_files
192     names = ''
193     if self.manifest_text
194       self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
195         names << name.first.gsub('\040',' ') + "\n"
196         break if names.length > 2**12
197       end
198     end
199
200     if self.manifest_text and names.length < 2**12
201       self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
202         names << stream_name.first.gsub('\040',' ') + "\n"
203         break if names.length > 2**12
204       end
205     end
206
207     names[0,2**12]
208   end
209
210   def default_empty_manifest
211     self.manifest_text ||= ''
212   end
213
214   def check_encoding
215     if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
216       true
217     else
218       begin
219         # If Ruby thinks the encoding is something else, like 7-bit
220         # ASCII, but its stored bytes are equal to the (valid) UTF-8
221         # encoding of the same string, we declare it to be a UTF-8
222         # string.
223         utf8 = manifest_text
224         utf8.force_encoding Encoding::UTF_8
225         if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
226           self.manifest_text = utf8
227           return true
228         end
229       rescue
230       end
231       errors.add :manifest_text, "must use UTF-8 encoding"
232       false
233     end
234   end
235
236   def check_manifest_validity
237     begin
238       Keep::Manifest.validate! manifest_text
239       true
240     rescue ArgumentError => e
241       errors.add :manifest_text, e.message
242       false
243     end
244   end
245
246   def signed_manifest_text
247     if !has_attribute? :manifest_text
248       return nil
249     elsif is_trashed
250       return manifest_text
251     else
252       token = current_api_client_authorization.andand.api_token
253       exp = [db_current_time.to_i + Rails.configuration.blob_signature_ttl,
254              trash_at].compact.map(&:to_i).min
255       self.class.sign_manifest manifest_text, token, exp
256     end
257   end
258
259   def self.sign_manifest manifest, token, exp=nil
260     if exp.nil?
261       exp = db_current_time.to_i + Rails.configuration.blob_signature_ttl
262     end
263     signing_opts = {
264       api_token: token,
265       expire: exp,
266     }
267     m = munge_manifest_locators(manifest) do |match|
268       Blob.sign_locator(match[0], signing_opts)
269     end
270     return m
271   end
272
273   def self.munge_manifest_locators manifest
274     # Given a manifest text and a block, yield the regexp MatchData
275     # for each locator. Return a new manifest in which each locator
276     # has been replaced by the block's return value.
277     return nil if !manifest
278     return '' if manifest == ''
279
280     new_lines = []
281     manifest.each_line do |line|
282       line.rstrip!
283       new_words = []
284       line.split(' ').each do |word|
285         if new_words.empty?
286           new_words << word
287         elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
288           new_words << yield(match)
289         else
290           new_words << word
291         end
292       end
293       new_lines << new_words.join(' ')
294     end
295     new_lines.join("\n") + "\n"
296   end
297
298   def self.each_manifest_locator manifest
299     # Given a manifest text and a block, yield the regexp match object
300     # for each locator.
301     manifest.each_line do |line|
302       # line will have a trailing newline, but the last token is never
303       # a locator, so it's harmless here.
304       line.split(' ').each do |word|
305         if match = Keep::Locator::LOCATOR_REGEXP.match(word)
306           yield(match)
307         end
308       end
309     end
310   end
311
312   def self.normalize_uuid uuid
313     hash_part = nil
314     size_part = nil
315     uuid.split('+').each do |token|
316       if token.match(/^[0-9a-f]{32,}$/)
317         raise "uuid #{uuid} has multiple hash parts" if hash_part
318         hash_part = token
319       elsif token.match(/^\d+$/)
320         raise "uuid #{uuid} has multiple size parts" if size_part
321         size_part = token
322       end
323     end
324     raise "uuid #{uuid} has no hash part" if !hash_part
325     [hash_part, size_part].compact.join '+'
326   end
327
328   def self.get_compatible_images(readers, pattern, collections)
329     if collections.empty?
330       return []
331     end
332
333     migrations = Hash[
334       Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
335                  collections.map(&:portable_data_hash),
336                  'docker_image_migration',
337                  system_user_uuid).
338       order('links.created_at asc').
339       map { |l|
340         [l.tail_uuid, l.head_uuid]
341       }]
342
343     migrated_collections = Hash[
344       Collection.readable_by(*readers).
345       where('portable_data_hash in (?)', migrations.values).
346       map { |c|
347         [c.portable_data_hash, c]
348       }]
349
350     collections.map { |c|
351       # Check if the listed image is compatible first, if not, then try the
352       # migration link.
353       manifest = Keep::Manifest.new(c.manifest_text)
354       if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
355         c
356       elsif m = migrated_collections[migrations[c.portable_data_hash]]
357         manifest = Keep::Manifest.new(m.manifest_text)
358         if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
359           m
360         end
361       end
362     }.compact
363   end
364
365   # Resolve a Docker repo+tag, hash, or collection PDH to an array of
366   # Collection objects, sorted by timestamp starting with the most recent
367   # match.
368   #
369   # If filter_compatible_format is true (the default), only return image
370   # collections which are support by the installation as indicated by
371   # Rails.configuration.docker_image_formats.  Will follow
372   # 'docker_image_migration' links if search_term resolves to an incompatible
373   # image, but an equivalent compatible image is available.
374   def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
375     readers ||= [Thread.current[:user]]
376     base_search = Link.
377       readable_by(*readers).
378       readable_by(*readers, table_name: "collections").
379       joins("JOIN collections ON links.head_uuid = collections.uuid").
380       order("links.created_at DESC")
381
382     if (Rails.configuration.docker_image_formats.include? 'v1' and
383         Rails.configuration.docker_image_formats.include? 'v2') or filter_compatible_format == false
384       pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
385     elsif Rails.configuration.docker_image_formats.include? 'v2'
386       pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
387     elsif Rails.configuration.docker_image_formats.include? 'v1'
388       pattern = /^[0-9A-Fa-f]{64}\.tar$/
389     else
390       raise "Unrecognized configuration for docker_image_formats #{Rails.configuration.docker_image_formats}"
391     end
392
393     # If the search term is a Collection locator that contains one file
394     # that looks like a Docker image, return it.
395     if loc = Keep::Locator.parse(search_term)
396       loc.strip_hints!
397       coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
398       return get_compatible_images(readers, pattern, coll_match)
399     end
400
401     if search_tag.nil? and (n = search_term.index(":"))
402       search_tag = search_term[n+1..-1]
403       search_term = search_term[0..n-1]
404     end
405
406     # Find Collections with matching Docker image repository+tag pairs.
407     matches = base_search.
408       where(link_class: "docker_image_repo+tag",
409             name: "#{search_term}:#{search_tag || 'latest'}")
410
411     # If that didn't work, find Collections with matching Docker image hashes.
412     if matches.empty?
413       matches = base_search.
414         where("link_class = ? and links.name LIKE ?",
415               "docker_image_hash", "#{search_term}%")
416     end
417
418     # Generate an order key for each result.  We want to order the results
419     # so that anything with an image timestamp is considered more recent than
420     # anything without; then we use the link's created_at as a tiebreaker.
421     uuid_timestamps = {}
422     matches.each do |link|
423       uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
424        -link.created_at.to_i]
425      end
426
427     sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
428       uuid_timestamps[c.uuid]
429     }
430     compatible = get_compatible_images(readers, pattern, sorted)
431     if sorted.length > 0 and compatible.empty?
432       raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
433     end
434     compatible
435   end
436
437   def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
438     find_all_for_docker_image(search_term, search_tag, readers).first
439   end
440
441   def self.searchable_columns operator
442     super - ["manifest_text"]
443   end
444
445   def self.full_text_searchable_columns
446     super - ["manifest_text", "storage_classes_desired", "storage_classes_confirmed"]
447   end
448
449   def self.where *args
450     SweepTrashedCollections.sweep_if_stale
451     super
452   end
453
454   protected
455
456   def portable_manifest_text
457     self.class.munge_manifest_locators(manifest_text) do |match|
458       if match[2] # size
459         match[1] + match[2]
460       else
461         match[1]
462       end
463     end
464   end
465
466   def compute_pdh
467     portable_manifest = portable_manifest_text
468     (Digest::MD5.hexdigest(portable_manifest) +
469      '+' +
470      portable_manifest.bytesize.to_s)
471   end
472
473   def computed_pdh
474     if @computed_pdh_for_manifest_text == manifest_text
475       return @computed_pdh
476     end
477     @computed_pdh = compute_pdh
478     @computed_pdh_for_manifest_text = manifest_text.dup
479     @computed_pdh
480   end
481
482   def ensure_permission_to_save
483     if (not current_user.andand.is_admin)
484       if (replication_confirmed_at_changed? or replication_confirmed_changed?) and
485         not (replication_confirmed_at.nil? and replication_confirmed.nil?)
486         raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
487       end
488       if (storage_classes_confirmed_changed? or storage_classes_confirmed_at_changed?) and
489         not (storage_classes_confirmed == [] and storage_classes_confirmed_at.nil?)
490         raise ArvadosModel::PermissionDeniedError.new("storage_classes_confirmed and storage_classes_confirmed_at attributes cannot be changed, except by setting them to [] and nil respectively")
491       end
492     end
493     super
494   end
495
496   def ensure_storage_classes_desired_is_not_empty
497     if self.storage_classes_desired.empty?
498       raise ArvadosModel::InvalidStateTransitionError.new("storage_classes_desired shouldn't be empty")
499     end
500   end
501
502   def ensure_storage_classes_contain_non_empty_strings
503     (self.storage_classes_desired + self.storage_classes_confirmed).each do |c|
504       if !c.is_a?(String) || c == ''
505         raise ArvadosModel::InvalidStateTransitionError.new("storage classes should only be non-empty strings")
506       end
507     end
508   end
509 end