Merge branch 'master' into 14873-api-rails5-upgrade
[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
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.permit_create_collection_with_unsigned_manifest
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         snapshot.manifest_text = snapshot.signed_manifest_text
285         snapshot.save
286       end
287     end
288   end
289
290   def syncable_updates
291     updates = {}
292     (syncable_attrs & self.changes.keys).each do |attr|
293       if attr == 'uuid'
294         # Point old versions to current version's new UUID
295         updates['current_version_uuid'] = self.changes[attr].last
296       else
297         updates[attr] = self.changes[attr].last
298       end
299     end
300     return updates
301   end
302
303   def sync_past_versions
304     updates = self.syncable_updates
305     Collection.where('current_version_uuid = ? AND uuid != ?', self.uuid_was, self.uuid_was).each do |c|
306       c.attributes = updates
307       # Use a different validation context to skip the 'old_versions_cannot_be_updated'
308       # validator, as on this case it is legal to update some fields.
309       leave_modified_by_user_alone do
310         leave_modified_at_alone do
311           c.save(context: :update_old_versions)
312         end
313       end
314     end
315   end
316
317   def versionable_updates?(attrs)
318     (['manifest_text', 'description', 'properties', 'name'] & attrs).any?
319   end
320
321   def syncable_attrs
322     ['uuid', 'owner_uuid', 'delete_at', 'trash_at', 'is_trashed', 'replication_desired', 'storage_classes_desired']
323   end
324
325   def should_preserve_version?
326     return false unless (Rails.configuration.collection_versioning && versionable_updates?(self.changes.keys))
327
328     idle_threshold = Rails.configuration.preserve_version_if_idle
329     if !self.preserve_version_was &&
330       (idle_threshold < 0 ||
331         (idle_threshold > 0 && self.modified_at_was > db_current_time-idle_threshold.seconds))
332       return false
333     end
334     return true
335   end
336
337   def check_encoding
338     if !(manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?)
339       begin
340         # If Ruby thinks the encoding is something else, like 7-bit
341         # ASCII, but its stored bytes are equal to the (valid) UTF-8
342         # encoding of the same string, we declare it to be a UTF-8
343         # string.
344         utf8 = manifest_text
345         utf8.force_encoding Encoding::UTF_8
346         if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
347           self.manifest_text = utf8
348           return true
349         end
350       rescue
351       end
352       errors.add :manifest_text, "must use UTF-8 encoding"
353       throw(:abort)
354     end
355   end
356
357   def check_manifest_validity
358     begin
359       Keep::Manifest.validate! manifest_text
360       true
361     rescue ArgumentError => e
362       errors.add :manifest_text, e.message
363       throw(:abort)
364     end
365   end
366
367   def signed_manifest_text
368     if !has_attribute? :manifest_text
369       return nil
370     elsif is_trashed
371       return manifest_text
372     else
373       token = Thread.current[:token]
374       exp = [db_current_time.to_i + Rails.configuration.blob_signature_ttl,
375              trash_at].compact.map(&:to_i).min
376       self.class.sign_manifest manifest_text, token, exp
377     end
378   end
379
380   def self.sign_manifest manifest, token, exp=nil
381     if exp.nil?
382       exp = db_current_time.to_i + Rails.configuration.blob_signature_ttl
383     end
384     signing_opts = {
385       api_token: token,
386       expire: exp,
387     }
388     m = munge_manifest_locators(manifest) do |match|
389       Blob.sign_locator(match[0], signing_opts)
390     end
391     return m
392   end
393
394   def self.munge_manifest_locators manifest
395     # Given a manifest text and a block, yield the regexp MatchData
396     # for each locator. Return a new manifest in which each locator
397     # has been replaced by the block's return value.
398     return nil if !manifest
399     return '' if manifest == ''
400
401     new_lines = []
402     manifest.each_line do |line|
403       line.rstrip!
404       new_words = []
405       line.split(' ').each do |word|
406         if new_words.empty?
407           new_words << word
408         elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
409           new_words << yield(match)
410         else
411           new_words << word
412         end
413       end
414       new_lines << new_words.join(' ')
415     end
416     new_lines.join("\n") + "\n"
417   end
418
419   def self.each_manifest_locator manifest
420     # Given a manifest text and a block, yield the regexp match object
421     # for each locator.
422     manifest.each_line do |line|
423       # line will have a trailing newline, but the last token is never
424       # a locator, so it's harmless here.
425       line.split(' ').each do |word|
426         if match = Keep::Locator::LOCATOR_REGEXP.match(word)
427           yield(match)
428         end
429       end
430     end
431   end
432
433   def self.normalize_uuid uuid
434     hash_part = nil
435     size_part = nil
436     uuid.split('+').each do |token|
437       if token.match(/^[0-9a-f]{32,}$/)
438         raise "uuid #{uuid} has multiple hash parts" if hash_part
439         hash_part = token
440       elsif token.match(/^\d+$/)
441         raise "uuid #{uuid} has multiple size parts" if size_part
442         size_part = token
443       end
444     end
445     raise "uuid #{uuid} has no hash part" if !hash_part
446     [hash_part, size_part].compact.join '+'
447   end
448
449   def self.get_compatible_images(readers, pattern, collections)
450     if collections.empty?
451       return []
452     end
453
454     migrations = Hash[
455       Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
456                  collections.map(&:portable_data_hash),
457                  'docker_image_migration',
458                  system_user_uuid).
459       order('links.created_at asc').
460       map { |l|
461         [l.tail_uuid, l.head_uuid]
462       }]
463
464     migrated_collections = Hash[
465       Collection.readable_by(*readers).
466       where('portable_data_hash in (?)', migrations.values).
467       map { |c|
468         [c.portable_data_hash, c]
469       }]
470
471     collections.map { |c|
472       # Check if the listed image is compatible first, if not, then try the
473       # migration link.
474       manifest = Keep::Manifest.new(c.manifest_text)
475       if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
476         c
477       elsif m = migrated_collections[migrations[c.portable_data_hash]]
478         manifest = Keep::Manifest.new(m.manifest_text)
479         if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
480           m
481         end
482       end
483     }.compact
484   end
485
486   # Resolve a Docker repo+tag, hash, or collection PDH to an array of
487   # Collection objects, sorted by timestamp starting with the most recent
488   # match.
489   #
490   # If filter_compatible_format is true (the default), only return image
491   # collections which are support by the installation as indicated by
492   # Rails.configuration.docker_image_formats.  Will follow
493   # 'docker_image_migration' links if search_term resolves to an incompatible
494   # image, but an equivalent compatible image is available.
495   def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
496     readers ||= [Thread.current[:user]]
497     base_search = Link.
498       readable_by(*readers).
499       readable_by(*readers, table_name: "collections").
500       joins("JOIN collections ON links.head_uuid = collections.uuid").
501       order("links.created_at DESC")
502
503     if (Rails.configuration.docker_image_formats.include? 'v1' and
504         Rails.configuration.docker_image_formats.include? 'v2') or filter_compatible_format == false
505       pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
506     elsif Rails.configuration.docker_image_formats.include? 'v2'
507       pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
508     elsif Rails.configuration.docker_image_formats.include? 'v1'
509       pattern = /^[0-9A-Fa-f]{64}\.tar$/
510     else
511       raise "Unrecognized configuration for docker_image_formats #{Rails.configuration.docker_image_formats}"
512     end
513
514     # If the search term is a Collection locator that contains one file
515     # that looks like a Docker image, return it.
516     if loc = Keep::Locator.parse(search_term)
517       loc.strip_hints!
518       coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
519       if coll_match.any? or Rails.configuration.remote_hosts.length == 0
520         return get_compatible_images(readers, pattern, coll_match)
521       else
522         # Allow bare pdh that doesn't exist in the local database so
523         # that federated container requests which refer to remotely
524         # stored containers will validate.
525         return [Collection.new(portable_data_hash: loc.to_s)]
526       end
527     end
528
529     if search_tag.nil? and (n = search_term.index(":"))
530       search_tag = search_term[n+1..-1]
531       search_term = search_term[0..n-1]
532     end
533
534     # Find Collections with matching Docker image repository+tag pairs.
535     matches = base_search.
536       where(link_class: "docker_image_repo+tag",
537             name: "#{search_term}:#{search_tag || 'latest'}")
538
539     # If that didn't work, find Collections with matching Docker image hashes.
540     if matches.empty?
541       matches = base_search.
542         where("link_class = ? and links.name LIKE ?",
543               "docker_image_hash", "#{search_term}%")
544     end
545
546     # Generate an order key for each result.  We want to order the results
547     # so that anything with an image timestamp is considered more recent than
548     # anything without; then we use the link's created_at as a tiebreaker.
549     uuid_timestamps = {}
550     matches.each do |link|
551       uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
552        -link.created_at.to_i]
553      end
554
555     sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
556       uuid_timestamps[c.uuid]
557     }
558     compatible = get_compatible_images(readers, pattern, sorted)
559     if sorted.length > 0 and compatible.empty?
560       raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
561     end
562     compatible
563   end
564
565   def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
566     find_all_for_docker_image(search_term, search_tag, readers).first
567   end
568
569   def self.searchable_columns operator
570     super - ["manifest_text"]
571   end
572
573   def self.full_text_searchable_columns
574     super - ["manifest_text", "storage_classes_desired", "storage_classes_confirmed", "current_version_uuid"]
575   end
576
577   def self.where *args
578     SweepTrashedObjects.sweep_if_stale
579     super
580   end
581
582   protected
583
584   # Although the defaults for these columns is already set up on the schema,
585   # collection creation from an API client seems to ignore them, making the
586   # validation on empty desired storage classes return an error.
587   def default_storage_classes
588     if self.storage_classes_desired.nil? || self.storage_classes_desired.empty?
589       self.storage_classes_desired = ["default"]
590     end
591     self.storage_classes_confirmed ||= []
592   end
593
594   def portable_manifest_text
595     self.class.munge_manifest_locators(manifest_text) do |match|
596       if match[2] # size
597         match[1] + match[2]
598       else
599         match[1]
600       end
601     end
602   end
603
604   def compute_pdh
605     portable_manifest = portable_manifest_text
606     (Digest::MD5.hexdigest(portable_manifest) +
607      '+' +
608      portable_manifest.bytesize.to_s)
609   end
610
611   def computed_pdh
612     if @computed_pdh_for_manifest_text == manifest_text
613       return @computed_pdh
614     end
615     @computed_pdh = compute_pdh
616     @computed_pdh_for_manifest_text = manifest_text.dup
617     @computed_pdh
618   end
619
620   def ensure_permission_to_save
621     if (not current_user.andand.is_admin)
622       if (replication_confirmed_at_changed? or replication_confirmed_changed?) and
623         not (replication_confirmed_at.nil? and replication_confirmed.nil?)
624         raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
625       end
626       if (storage_classes_confirmed_changed? or storage_classes_confirmed_at_changed?) and
627         not (storage_classes_confirmed == [] and storage_classes_confirmed_at.nil?)
628         raise ArvadosModel::PermissionDeniedError.new("storage_classes_confirmed and storage_classes_confirmed_at attributes cannot be changed, except by setting them to [] and nil respectively")
629       end
630     end
631     super
632   end
633
634   def ensure_storage_classes_desired_is_not_empty
635     if self.storage_classes_desired.empty?
636       raise ArvadosModel::InvalidStateTransitionError.new("storage_classes_desired shouldn't be empty")
637     end
638   end
639
640   def ensure_storage_classes_contain_non_empty_strings
641     (self.storage_classes_desired + self.storage_classes_confirmed).each do |c|
642       if !c.is_a?(String) || c == ''
643         raise ArvadosModel::InvalidStateTransitionError.new("storage classes should only be non-empty strings")
644       end
645     end
646   end
647
648   def past_versions_cannot_be_updated
649     # We check for the '_was' values just in case the update operation
650     # includes a change on current_version_uuid or uuid.
651     if current_version_uuid_was != uuid_was
652       errors.add(:base, "past versions cannot be updated")
653       false
654     end
655   end
656
657   def versioning_metadata_updates
658     valid = true
659     if (current_version_uuid_was == uuid_was) && current_version_uuid_changed?
660       errors.add(:current_version_uuid, "cannot be updated")
661       valid = false
662     end
663     if version_changed?
664       errors.add(:version, "cannot be updated")
665       valid = false
666     end
667     valid
668   end
669
670   def assign_uuid
671     super
672     self.current_version_uuid ||= self.uuid
673     true
674   end
675 end