8dca6fc9fbada7411e4ef2f4dd45c0effb7c71bb
[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_objects'
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   # Posgresql JSONB columns should NOT be declared as serialized, Rails 5
18   # already know how to properly treat them.
19   attribute :properties, :jsonbHash, default: {}
20   attribute :storage_classes_desired, :jsonbArray, default: ["default"]
21   attribute :storage_classes_confirmed, :jsonbArray, default: []
22
23   before_validation :default_empty_manifest
24   before_validation :default_storage_classes, on: :create
25   before_validation :check_encoding
26   before_validation :check_manifest_validity
27   before_validation :check_signatures
28   before_validation :strip_signatures_and_update_replication_confirmed
29   validate :ensure_pdh_matches_manifest_text
30   validate :ensure_storage_classes_desired_is_not_empty
31   validate :ensure_storage_classes_contain_non_empty_strings
32   validate :versioning_metadata_updates, on: :update
33   validate :past_versions_cannot_be_updated, on: :update
34   after_validation :set_file_count_and_total_size
35   before_save :set_file_names
36   around_update :manage_versioning, unless: :is_past_version?
37
38   api_accessible :user, extend: :common do |t|
39     t.add :name
40     t.add :description
41     t.add :properties
42     t.add :portable_data_hash
43     t.add :signed_manifest_text, as: :manifest_text
44     t.add :manifest_text, as: :unsigned_manifest_text
45     t.add :replication_desired
46     t.add :replication_confirmed
47     t.add :replication_confirmed_at
48     t.add :storage_classes_desired
49     t.add :storage_classes_confirmed
50     t.add :storage_classes_confirmed_at
51     t.add :delete_at
52     t.add :trash_at
53     t.add :is_trashed
54     t.add :version
55     t.add :current_version_uuid
56     t.add :preserve_version
57     t.add :file_count
58     t.add :file_size_total
59   end
60
61   after_initialize do
62     @signatures_checked = false
63     @computed_pdh_for_manifest_text = false
64   end
65
66   def self.attributes_required_columns
67     super.merge(
68                 # If we don't list manifest_text explicitly, the
69                 # params[:select] code gets confused by the way we
70                 # expose signed_manifest_text as manifest_text in the
71                 # API response, and never let clients select the
72                 # manifest_text column.
73                 #
74                 # We need trash_at and is_trashed to determine the
75                 # correct timestamp in signed_manifest_text.
76                 'manifest_text' => ['manifest_text', 'trash_at', 'is_trashed'],
77                 'unsigned_manifest_text' => ['manifest_text'],
78                 )
79   end
80
81   def self.ignored_select_attributes
82     super + ["updated_at", "file_names"]
83   end
84
85   def self.limit_index_columns_read
86     ["manifest_text"]
87   end
88
89   FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
90   def check_signatures
91     throw(:abort) if self.manifest_text.nil?
92
93     return true if current_user.andand.is_admin
94
95     # Provided the manifest_text hasn't changed materially since an
96     # earlier validation, it's safe to pass this validation on
97     # subsequent passes without checking any signatures. This is
98     # important because the signatures have probably been stripped off
99     # by the time we get to a second validation pass!
100     if @signatures_checked && @signatures_checked == computed_pdh
101       return true
102     end
103
104     if self.manifest_text_changed?
105       # Check permissions on the collection manifest.
106       # If any signature cannot be verified, raise PermissionDeniedError
107       # which will return 403 Permission denied to the client.
108       api_token = Thread.current[:token]
109       signing_opts = {
110         api_token: api_token,
111         now: @validation_timestamp.to_i,
112       }
113       self.manifest_text.each_line do |entry|
114         entry.split.each do |tok|
115           if tok == '.' or tok.starts_with? './'
116             # Stream name token.
117           elsif tok =~ FILE_TOKEN
118             # This is a filename token, not a blob locator. Note that we
119             # keep checking tokens after this, even though manifest
120             # format dictates that all subsequent tokens will also be
121             # filenames. Safety first!
122           elsif Blob.verify_signature tok, signing_opts
123             # OK.
124           elsif Keep::Locator.parse(tok).andand.signature
125             # Signature provided, but verify_signature did not like it.
126             logger.warn "Invalid signature on locator #{tok}"
127             raise ArvadosModel::PermissionDeniedError
128           elsif !Rails.configuration.Collections.BlobSigning
129             # No signature provided, but we are running in insecure mode.
130             logger.debug "Missing signature on locator #{tok} ignored"
131           elsif Blob.new(tok).empty?
132             # No signature provided -- but no data to protect, either.
133           else
134             logger.warn "Missing signature on locator #{tok}"
135             raise ArvadosModel::PermissionDeniedError
136           end
137         end
138       end
139     end
140     @signatures_checked = computed_pdh
141   end
142
143   def strip_signatures_and_update_replication_confirmed
144     if self.manifest_text_changed?
145       in_old_manifest = {}
146       if not self.replication_confirmed.nil?
147         self.class.each_manifest_locator(manifest_text_was) do |match|
148           in_old_manifest[match[1]] = true
149         end
150       end
151
152       stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
153         if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
154           # If the new manifest_text contains locators whose hashes
155           # weren't in the old manifest_text, storage replication is no
156           # longer confirmed.
157           self.replication_confirmed_at = nil
158           self.replication_confirmed = nil
159         end
160
161         # Return the locator with all permission signatures removed,
162         # but otherwise intact.
163         match[0].gsub(/\+A[^+]*/, '')
164       end
165
166       if @computed_pdh_for_manifest_text == manifest_text
167         # If the cached PDH was valid before stripping, it is still
168         # valid after stripping.
169         @computed_pdh_for_manifest_text = stripped_manifest.dup
170       end
171
172       self[:manifest_text] = stripped_manifest
173     end
174     true
175   end
176
177   def ensure_pdh_matches_manifest_text
178     if not manifest_text_changed? and not portable_data_hash_changed?
179       true
180     elsif portable_data_hash.nil? or not portable_data_hash_changed?
181       self.portable_data_hash = computed_pdh
182     elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
183       errors.add(:portable_data_hash, "is not a valid locator")
184       false
185     elsif portable_data_hash[0..31] != computed_pdh[0..31]
186       errors.add(:portable_data_hash,
187                  "'#{portable_data_hash}' does not match computed hash '#{computed_pdh}'")
188       false
189     else
190       # Ignore the client-provided size part: always store
191       # computed_pdh in the database.
192       self.portable_data_hash = computed_pdh
193     end
194   end
195
196   def set_file_names
197     if self.manifest_text_changed?
198       self.file_names = manifest_files
199     end
200     true
201   end
202
203   def set_file_count_and_total_size
204     # Only update the file stats if the manifest changed
205     if self.manifest_text_changed?
206       m = Keep::Manifest.new(self.manifest_text)
207       self.file_size_total = m.files_size
208       self.file_count = m.files_count
209     # If the manifest didn't change but the attributes did, ignore the changes
210     elsif self.file_count_changed? || self.file_size_total_changed?
211       self.file_count = self.file_count_was
212       self.file_size_total = self.file_size_total_was
213     end
214     true
215   end
216
217   def manifest_files
218     return '' if !self.manifest_text
219
220     done = {}
221     names = ''
222     self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
223       next if done[name]
224       done[name] = true
225       names << name.first.gsub('\040',' ') + "\n"
226     end
227     self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
228       next if done[stream_name]
229       done[stream_name] = true
230       names << stream_name.first.gsub('\040',' ') + "\n"
231     end
232     names
233   end
234
235   def default_empty_manifest
236     self.manifest_text ||= ''
237   end
238
239   def skip_uuid_existence_check
240     # Avoid checking the existence of current_version_uuid, as it's
241     # assigned on creation of a new 'current version' collection, so
242     # the collection's UUID only lives on memory when the validation check
243     # is performed.
244     ['current_version_uuid']
245   end
246
247   def manage_versioning
248     should_preserve_version = should_preserve_version? # Time sensitive, cache value
249     return(yield) unless (should_preserve_version || syncable_updates.any?)
250
251     # Put aside the changes because with_lock forces a record reload
252     changes = self.changes
253     snapshot = nil
254     with_lock do
255       # Copy the original state to save it as old version
256       if should_preserve_version
257         snapshot = self.dup
258         snapshot.uuid = nil # Reset UUID so it's created as a new record
259         snapshot.created_at = self.created_at
260       end
261
262       # Restore requested changes on the current version
263       changes.keys.each do |attr|
264         if attr == 'preserve_version' && changes[attr].last == false
265           next # Ignore false assignment, once true it'll be true until next version
266         end
267         self.attributes = {attr => changes[attr].last}
268         if attr == 'uuid'
269           # Also update the current version reference
270           self.attributes = {'current_version_uuid' => changes[attr].last}
271         end
272       end
273
274       if should_preserve_version
275         self.version += 1
276         self.preserve_version = false
277       end
278
279       yield
280
281       sync_past_versions if syncable_updates.any?
282       if snapshot
283         snapshot.attributes = self.syncable_updates
284         leave_modified_by_user_alone do
285           act_as_system_user do
286             snapshot.save
287           end
288         end
289       end
290     end
291   end
292
293   def syncable_updates
294     updates = {}
295     (syncable_attrs & self.changes.keys).each do |attr|
296       if attr == 'uuid'
297         # Point old versions to current version's new UUID
298         updates['current_version_uuid'] = self.changes[attr].last
299       else
300         updates[attr] = self.changes[attr].last
301       end
302     end
303     return updates
304   end
305
306   def sync_past_versions
307     updates = self.syncable_updates
308     Collection.where('current_version_uuid = ? AND uuid != ?', self.uuid_was, self.uuid_was).each do |c|
309       c.attributes = updates
310       # Use a different validation context to skip the 'past_versions_cannot_be_updated'
311       # validator, as on this case it is legal to update some fields.
312       leave_modified_by_user_alone do
313         leave_modified_at_alone do
314           c.save(context: :update_old_versions)
315         end
316       end
317     end
318   end
319
320   def versionable_updates?(attrs)
321     (['manifest_text', 'description', 'properties', 'name'] & attrs).any?
322   end
323
324   def syncable_attrs
325     ['uuid', 'owner_uuid', 'delete_at', 'trash_at', 'is_trashed', 'replication_desired', 'storage_classes_desired']
326   end
327
328   def is_past_version?
329     # Check for the '_was' values just in case the update operation
330     # includes a change on current_version_uuid or uuid.
331     if !new_record? && self.current_version_uuid_was != self.uuid_was
332       return true
333     else
334       return false
335     end
336   end
337
338   def should_preserve_version?
339     return false unless (Rails.configuration.Collections.CollectionVersioning && versionable_updates?(self.changes.keys))
340
341     return false if self.changes.keys.include?('is_trashed') && self.is_trashed_was == false
342
343     idle_threshold = Rails.configuration.Collections.PreserveVersionIfIdle
344     if !self.preserve_version_was &&
345       (idle_threshold < 0 ||
346         (idle_threshold > 0 && self.modified_at_was > db_current_time-idle_threshold.seconds))
347       return false
348     end
349     return true
350   end
351
352   def check_encoding
353     if !(manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?)
354       begin
355         # If Ruby thinks the encoding is something else, like 7-bit
356         # ASCII, but its stored bytes are equal to the (valid) UTF-8
357         # encoding of the same string, we declare it to be a UTF-8
358         # string.
359         utf8 = manifest_text
360         utf8.force_encoding Encoding::UTF_8
361         if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
362           self.manifest_text = utf8
363           return true
364         end
365       rescue
366       end
367       errors.add :manifest_text, "must use UTF-8 encoding"
368       throw(:abort)
369     end
370   end
371
372   def check_manifest_validity
373     begin
374       Keep::Manifest.validate! manifest_text
375       true
376     rescue ArgumentError => e
377       errors.add :manifest_text, e.message
378       throw(:abort)
379     end
380   end
381
382   def signed_manifest_text
383     if !has_attribute? :manifest_text
384       return nil
385     elsif is_trashed
386       return manifest_text
387     else
388       token = Thread.current[:token]
389       exp = [db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i,
390              trash_at].compact.map(&:to_i).min
391       self.class.sign_manifest manifest_text, token, exp
392     end
393   end
394
395   def self.sign_manifest manifest, token, exp=nil
396     if exp.nil?
397       exp = db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i
398     end
399     signing_opts = {
400       api_token: token,
401       expire: exp,
402     }
403     m = munge_manifest_locators(manifest) do |match|
404       Blob.sign_locator(match[0], signing_opts)
405     end
406     return m
407   end
408
409   def self.munge_manifest_locators manifest
410     # Given a manifest text and a block, yield the regexp MatchData
411     # for each locator. Return a new manifest in which each locator
412     # has been replaced by the block's return value.
413     return nil if !manifest
414     return '' if manifest == ''
415
416     new_lines = []
417     manifest.each_line do |line|
418       line.rstrip!
419       new_words = []
420       line.split(' ').each do |word|
421         if new_words.empty?
422           new_words << word
423         elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
424           new_words << yield(match)
425         else
426           new_words << word
427         end
428       end
429       new_lines << new_words.join(' ')
430     end
431     new_lines.join("\n") + "\n"
432   end
433
434   def self.each_manifest_locator manifest
435     # Given a manifest text and a block, yield the regexp match object
436     # for each locator.
437     manifest.each_line do |line|
438       # line will have a trailing newline, but the last token is never
439       # a locator, so it's harmless here.
440       line.split(' ').each do |word|
441         if match = Keep::Locator::LOCATOR_REGEXP.match(word)
442           yield(match)
443         end
444       end
445     end
446   end
447
448   def self.normalize_uuid uuid
449     hash_part = nil
450     size_part = nil
451     uuid.split('+').each do |token|
452       if token.match(/^[0-9a-f]{32,}$/)
453         raise "uuid #{uuid} has multiple hash parts" if hash_part
454         hash_part = token
455       elsif token.match(/^\d+$/)
456         raise "uuid #{uuid} has multiple size parts" if size_part
457         size_part = token
458       end
459     end
460     raise "uuid #{uuid} has no hash part" if !hash_part
461     [hash_part, size_part].compact.join '+'
462   end
463
464   def self.get_compatible_images(readers, pattern, collections)
465     if collections.empty?
466       return []
467     end
468
469     migrations = Hash[
470       Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
471                  collections.map(&:portable_data_hash),
472                  'docker_image_migration',
473                  system_user_uuid).
474       order('links.created_at asc').
475       map { |l|
476         [l.tail_uuid, l.head_uuid]
477       }]
478
479     migrated_collections = Hash[
480       Collection.readable_by(*readers).
481       where('portable_data_hash in (?)', migrations.values).
482       map { |c|
483         [c.portable_data_hash, c]
484       }]
485
486     collections.map { |c|
487       # Check if the listed image is compatible first, if not, then try the
488       # migration link.
489       manifest = Keep::Manifest.new(c.manifest_text)
490       if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
491         c
492       elsif m = migrated_collections[migrations[c.portable_data_hash]]
493         manifest = Keep::Manifest.new(m.manifest_text)
494         if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
495           m
496         end
497       end
498     }.compact
499   end
500
501   # Resolve a Docker repo+tag, hash, or collection PDH to an array of
502   # Collection objects, sorted by timestamp starting with the most recent
503   # match.
504   #
505   # If filter_compatible_format is true (the default), only return image
506   # collections which are support by the installation as indicated by
507   # Rails.configuration.Containers.SupportedDockerImageFormats.  Will follow
508   # 'docker_image_migration' links if search_term resolves to an incompatible
509   # image, but an equivalent compatible image is available.
510   def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
511     readers ||= [Thread.current[:user]]
512     base_search = Link.
513       readable_by(*readers).
514       readable_by(*readers, table_name: "collections").
515       joins("JOIN collections ON links.head_uuid = collections.uuid").
516       order("links.created_at DESC")
517
518     docker_image_formats = Rails.configuration.Containers.SupportedDockerImageFormats
519
520     if (docker_image_formats.include? 'v1' and
521         docker_image_formats.include? 'v2') or filter_compatible_format == false
522       pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
523     elsif docker_image_formats.include? 'v2'
524       pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
525     elsif docker_image_formats.include? 'v1'
526       pattern = /^[0-9A-Fa-f]{64}\.tar$/
527     else
528       raise "Unrecognized configuration for docker_image_formats #{docker_image_formats}"
529     end
530
531     # If the search term is a Collection locator that contains one file
532     # that looks like a Docker image, return it.
533     if loc = Keep::Locator.parse(search_term)
534       loc.strip_hints!
535       coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
536       rc = Rails.configuration.RemoteClusters.select{ |k|
537         k != :"*" && k != Rails.configuration.ClusterID}
538       if coll_match.any? or rc.length == 0
539         return get_compatible_images(readers, pattern, coll_match)
540       else
541         # Allow bare pdh that doesn't exist in the local database so
542         # that federated container requests which refer to remotely
543         # stored containers will validate.
544         return [Collection.new(portable_data_hash: loc.to_s)]
545       end
546     end
547
548     if search_tag.nil? and (n = search_term.index(":"))
549       search_tag = search_term[n+1..-1]
550       search_term = search_term[0..n-1]
551     end
552
553     # Find Collections with matching Docker image repository+tag pairs.
554     matches = base_search.
555       where(link_class: "docker_image_repo+tag",
556             name: "#{search_term}:#{search_tag || 'latest'}")
557
558     # If that didn't work, find Collections with matching Docker image hashes.
559     if matches.empty?
560       matches = base_search.
561         where("link_class = ? and links.name LIKE ?",
562               "docker_image_hash", "#{search_term}%")
563     end
564
565     # Generate an order key for each result.  We want to order the results
566     # so that anything with an image timestamp is considered more recent than
567     # anything without; then we use the link's created_at as a tiebreaker.
568     uuid_timestamps = {}
569     matches.each do |link|
570       uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
571        -link.created_at.to_i]
572      end
573
574     sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
575       uuid_timestamps[c.uuid]
576     }
577     compatible = get_compatible_images(readers, pattern, sorted)
578     if sorted.length > 0 and compatible.empty?
579       raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
580     end
581     compatible
582   end
583
584   def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
585     find_all_for_docker_image(search_term, search_tag, readers).first
586   end
587
588   def self.searchable_columns operator
589     super - ["manifest_text"]
590   end
591
592   def self.full_text_searchable_columns
593     super - ["manifest_text", "storage_classes_desired", "storage_classes_confirmed", "current_version_uuid"]
594   end
595
596   def self.where *args
597     SweepTrashedObjects.sweep_if_stale
598     super
599   end
600
601   protected
602
603   # Although the defaults for these columns is already set up on the schema,
604   # collection creation from an API client seems to ignore them, making the
605   # validation on empty desired storage classes return an error.
606   def default_storage_classes
607     if self.storage_classes_desired.nil? || self.storage_classes_desired.empty?
608       self.storage_classes_desired = ["default"]
609     end
610     self.storage_classes_confirmed ||= []
611   end
612
613   def portable_manifest_text
614     self.class.munge_manifest_locators(manifest_text) do |match|
615       if match[2] # size
616         match[1] + match[2]
617       else
618         match[1]
619       end
620     end
621   end
622
623   def compute_pdh
624     portable_manifest = portable_manifest_text
625     (Digest::MD5.hexdigest(portable_manifest) +
626      '+' +
627      portable_manifest.bytesize.to_s)
628   end
629
630   def computed_pdh
631     if @computed_pdh_for_manifest_text == manifest_text
632       return @computed_pdh
633     end
634     @computed_pdh = compute_pdh
635     @computed_pdh_for_manifest_text = manifest_text.dup
636     @computed_pdh
637   end
638
639   def ensure_permission_to_save
640     if (not current_user.andand.is_admin)
641       if (replication_confirmed_at_changed? or replication_confirmed_changed?) and
642         not (replication_confirmed_at.nil? and replication_confirmed.nil?)
643         raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
644       end
645       if (storage_classes_confirmed_changed? or storage_classes_confirmed_at_changed?) and
646         not (storage_classes_confirmed == [] and storage_classes_confirmed_at.nil?)
647         raise ArvadosModel::PermissionDeniedError.new("storage_classes_confirmed and storage_classes_confirmed_at attributes cannot be changed, except by setting them to [] and nil respectively")
648       end
649     end
650     super
651   end
652
653   def ensure_storage_classes_desired_is_not_empty
654     if self.storage_classes_desired.empty?
655       raise ArvadosModel::InvalidStateTransitionError.new("storage_classes_desired shouldn't be empty")
656     end
657   end
658
659   def ensure_storage_classes_contain_non_empty_strings
660     (self.storage_classes_desired + self.storage_classes_confirmed).each do |c|
661       if !c.is_a?(String) || c == ''
662         raise ArvadosModel::InvalidStateTransitionError.new("storage classes should only be non-empty strings")
663       end
664     end
665   end
666
667   def past_versions_cannot_be_updated
668     if is_past_version?
669       errors.add(:base, "past versions cannot be updated")
670       false
671     end
672   end
673
674   def versioning_metadata_updates
675     valid = true
676     if !is_past_version? && current_version_uuid_changed?
677       errors.add(:current_version_uuid, "cannot be updated")
678       valid = false
679     end
680     if version_changed?
681       errors.add(:version, "cannot be updated")
682       valid = false
683     end
684     valid
685   end
686
687   def assign_uuid
688     super
689     self.current_version_uuid ||= self.uuid
690     true
691   end
692 end