1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
6 require 'sweep_trashed_objects'
9 class Collection < ArvadosModel
10 extend CurrentApiClient
14 include CommonApiTemplate
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: []
23 before_validation :default_empty_manifest
24 before_validation :default_storage_classes, on: :create
25 before_validation :managed_properties, on: :create
26 before_validation :check_encoding
27 before_validation :check_manifest_validity
28 before_validation :check_signatures
29 before_validation :strip_signatures_and_update_replication_confirmed
30 before_validation :name_null_if_empty
31 validate :ensure_pdh_matches_manifest_text
32 validate :ensure_storage_classes_desired_is_not_empty
33 validate :ensure_storage_classes_contain_non_empty_strings
34 validate :versioning_metadata_updates, on: :update
35 validate :past_versions_cannot_be_updated, on: :update
36 validate :protected_managed_properties_updates, on: :update
37 after_validation :set_file_count_and_total_size
38 before_save :set_file_names
39 around_update :manage_versioning, unless: :is_past_version?
41 api_accessible :user, extend: :common do |t|
42 t.add lambda { |x| x.name || "" }, as: :name
45 t.add :portable_data_hash
46 t.add :signed_manifest_text, as: :manifest_text
47 t.add :manifest_text, as: :unsigned_manifest_text
48 t.add :replication_desired
49 t.add :replication_confirmed
50 t.add :replication_confirmed_at
51 t.add :storage_classes_desired
52 t.add :storage_classes_confirmed
53 t.add :storage_classes_confirmed_at
58 t.add :current_version_uuid
59 t.add :preserve_version
61 t.add :file_size_total
65 @signatures_checked = false
66 @computed_pdh_for_manifest_text = false
69 def self.attributes_required_columns
71 # If we don't list manifest_text explicitly, the
72 # params[:select] code gets confused by the way we
73 # expose signed_manifest_text as manifest_text in the
74 # API response, and never let clients select the
75 # manifest_text column.
77 # We need trash_at and is_trashed to determine the
78 # correct timestamp in signed_manifest_text.
79 'manifest_text' => ['manifest_text', 'trash_at', 'is_trashed'],
80 'unsigned_manifest_text' => ['manifest_text'],
85 def self.ignored_select_attributes
86 super + ["updated_at", "file_names"]
89 def self.limit_index_columns_read
93 FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
95 throw(:abort) if self.manifest_text.nil?
97 return true if current_user.andand.is_admin
99 # Provided the manifest_text hasn't changed materially since an
100 # earlier validation, it's safe to pass this validation on
101 # subsequent passes without checking any signatures. This is
102 # important because the signatures have probably been stripped off
103 # by the time we get to a second validation pass!
104 if @signatures_checked && @signatures_checked == computed_pdh
108 if self.manifest_text_changed?
109 # Check permissions on the collection manifest.
110 # If any signature cannot be verified, raise PermissionDeniedError
111 # which will return 403 Permission denied to the client.
112 api_token = Thread.current[:token]
114 api_token: api_token,
115 now: @validation_timestamp.to_i,
117 self.manifest_text.each_line do |entry|
118 entry.split.each do |tok|
119 if tok == '.' or tok.starts_with? './'
121 elsif tok =~ FILE_TOKEN
122 # This is a filename token, not a blob locator. Note that we
123 # keep checking tokens after this, even though manifest
124 # format dictates that all subsequent tokens will also be
125 # filenames. Safety first!
126 elsif Blob.verify_signature tok, signing_opts
128 elsif Keep::Locator.parse(tok).andand.signature
129 # Signature provided, but verify_signature did not like it.
130 logger.warn "Invalid signature on locator #{tok}"
131 raise ArvadosModel::PermissionDeniedError
132 elsif !Rails.configuration.Collections.BlobSigning
133 # No signature provided, but we are running in insecure mode.
134 logger.debug "Missing signature on locator #{tok} ignored"
135 elsif Blob.new(tok).empty?
136 # No signature provided -- but no data to protect, either.
138 logger.warn "Missing signature on locator #{tok}"
139 raise ArvadosModel::PermissionDeniedError
144 @signatures_checked = computed_pdh
147 def strip_signatures_and_update_replication_confirmed
148 if self.manifest_text_changed?
150 if not self.replication_confirmed.nil?
151 self.class.each_manifest_locator(manifest_text_was) do |match|
152 in_old_manifest[match[1]] = true
156 stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
157 if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
158 # If the new manifest_text contains locators whose hashes
159 # weren't in the old manifest_text, storage replication is no
161 self.replication_confirmed_at = nil
162 self.replication_confirmed = nil
165 # Return the locator with all permission signatures removed,
166 # but otherwise intact.
167 match[0].gsub(/\+A[^+]*/, '')
170 if @computed_pdh_for_manifest_text == manifest_text
171 # If the cached PDH was valid before stripping, it is still
172 # valid after stripping.
173 @computed_pdh_for_manifest_text = stripped_manifest.dup
176 self[:manifest_text] = stripped_manifest
181 def ensure_pdh_matches_manifest_text
182 if not manifest_text_changed? and not portable_data_hash_changed?
184 elsif portable_data_hash.nil? or not portable_data_hash_changed?
185 self.portable_data_hash = computed_pdh
186 elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
187 errors.add(:portable_data_hash, "is not a valid locator")
189 elsif portable_data_hash[0..31] != computed_pdh[0..31]
190 errors.add(:portable_data_hash,
191 "'#{portable_data_hash}' does not match computed hash '#{computed_pdh}'")
194 # Ignore the client-provided size part: always store
195 # computed_pdh in the database.
196 self.portable_data_hash = computed_pdh
200 def name_null_if_empty
207 if self.manifest_text_changed?
208 self.file_names = manifest_files
213 def set_file_count_and_total_size
214 # Only update the file stats if the manifest changed
215 if self.manifest_text_changed?
216 m = Keep::Manifest.new(self.manifest_text)
217 self.file_size_total = m.files_size
218 self.file_count = m.files_count
219 # If the manifest didn't change but the attributes did, ignore the changes
220 elsif self.file_count_changed? || self.file_size_total_changed?
221 self.file_count = self.file_count_was
222 self.file_size_total = self.file_size_total_was
228 return '' if !self.manifest_text
232 self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
235 names << name.first.gsub('\040',' ') + "\n"
237 self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
238 next if done[stream_name]
239 done[stream_name] = true
240 names << stream_name.first.gsub('\040',' ') + "\n"
245 def default_empty_manifest
246 self.manifest_text ||= ''
249 def skip_uuid_existence_check
250 # Avoid checking the existence of current_version_uuid, as it's
251 # assigned on creation of a new 'current version' collection, so
252 # the collection's UUID only lives on memory when the validation check
254 ['current_version_uuid']
257 def manage_versioning
258 should_preserve_version = should_preserve_version? # Time sensitive, cache value
259 return(yield) unless (should_preserve_version || syncable_updates.any?)
261 # Put aside the changes because with_lock forces a record reload
262 changes = self.changes
265 # Copy the original state to save it as old version
266 if should_preserve_version
268 snapshot.uuid = nil # Reset UUID so it's created as a new record
269 snapshot.created_at = self.created_at
272 # Restore requested changes on the current version
273 changes.keys.each do |attr|
274 if attr == 'preserve_version' && changes[attr].last == false
275 next # Ignore false assignment, once true it'll be true until next version
277 self.attributes = {attr => changes[attr].last}
279 # Also update the current version reference
280 self.attributes = {'current_version_uuid' => changes[attr].last}
284 if should_preserve_version
286 self.preserve_version = false
291 sync_past_versions if syncable_updates.any?
293 snapshot.attributes = self.syncable_updates
294 leave_modified_by_user_alone do
295 act_as_system_user do
305 (syncable_attrs & self.changes.keys).each do |attr|
307 # Point old versions to current version's new UUID
308 updates['current_version_uuid'] = self.changes[attr].last
310 updates[attr] = self.changes[attr].last
316 def sync_past_versions
317 updates = self.syncable_updates
318 Collection.where('current_version_uuid = ? AND uuid != ?', self.uuid_was, self.uuid_was).each do |c|
319 c.attributes = updates
320 # Use a different validation context to skip the 'past_versions_cannot_be_updated'
321 # validator, as on this case it is legal to update some fields.
322 leave_modified_by_user_alone do
323 leave_modified_at_alone do
324 c.save(context: :update_old_versions)
330 def versionable_updates?(attrs)
331 (['manifest_text', 'description', 'properties', 'name'] & attrs).any?
335 ['uuid', 'owner_uuid', 'delete_at', 'trash_at', 'is_trashed', 'replication_desired', 'storage_classes_desired']
339 # Check for the '_was' values just in case the update operation
340 # includes a change on current_version_uuid or uuid.
341 !(new_record? || self.current_version_uuid_was == self.uuid_was)
344 def should_preserve_version?
345 return false unless (Rails.configuration.Collections.CollectionVersioning && versionable_updates?(self.changes.keys))
347 return false if self.is_trashed
349 idle_threshold = Rails.configuration.Collections.PreserveVersionIfIdle
350 if !self.preserve_version_was &&
351 (idle_threshold < 0 ||
352 (idle_threshold > 0 && self.modified_at_was > db_current_time-idle_threshold.seconds))
359 if !(manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?)
361 # If Ruby thinks the encoding is something else, like 7-bit
362 # ASCII, but its stored bytes are equal to the (valid) UTF-8
363 # encoding of the same string, we declare it to be a UTF-8
366 utf8.force_encoding Encoding::UTF_8
367 if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
368 self.manifest_text = utf8
373 errors.add :manifest_text, "must use UTF-8 encoding"
378 def check_manifest_validity
380 Keep::Manifest.validate! manifest_text
382 rescue ArgumentError => e
383 errors.add :manifest_text, e.message
388 def signed_manifest_text
389 if !has_attribute? :manifest_text
394 token = Thread.current[:token]
395 exp = [db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i,
396 trash_at].compact.map(&:to_i).min
397 self.class.sign_manifest manifest_text, token, exp
401 def self.sign_manifest manifest, token, exp=nil
403 exp = db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i
409 m = munge_manifest_locators(manifest) do |match|
410 Blob.sign_locator(match[0], signing_opts)
415 def self.munge_manifest_locators manifest
416 # Given a manifest text and a block, yield the regexp MatchData
417 # for each locator. Return a new manifest in which each locator
418 # has been replaced by the block's return value.
419 return nil if !manifest
420 return '' if manifest == ''
423 manifest.each_line do |line|
426 line.split(' ').each do |word|
429 elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
430 new_words << yield(match)
435 new_lines << new_words.join(' ')
437 new_lines.join("\n") + "\n"
440 def self.each_manifest_locator manifest
441 # Given a manifest text and a block, yield the regexp match object
443 manifest.each_line do |line|
444 # line will have a trailing newline, but the last token is never
445 # a locator, so it's harmless here.
446 line.split(' ').each do |word|
447 if match = Keep::Locator::LOCATOR_REGEXP.match(word)
454 def self.normalize_uuid uuid
457 uuid.split('+').each do |token|
458 if token.match(/^[0-9a-f]{32,}$/)
459 raise "uuid #{uuid} has multiple hash parts" if hash_part
461 elsif token.match(/^\d+$/)
462 raise "uuid #{uuid} has multiple size parts" if size_part
466 raise "uuid #{uuid} has no hash part" if !hash_part
467 [hash_part, size_part].compact.join '+'
470 def self.get_compatible_images(readers, pattern, collections)
471 if collections.empty?
476 Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
477 collections.map(&:portable_data_hash),
478 'docker_image_migration',
480 order('links.created_at asc').
482 [l.tail_uuid, l.head_uuid]
485 migrated_collections = Hash[
486 Collection.readable_by(*readers).
487 where('portable_data_hash in (?)', migrations.values).
489 [c.portable_data_hash, c]
492 collections.map { |c|
493 # Check if the listed image is compatible first, if not, then try the
495 manifest = Keep::Manifest.new(c.manifest_text)
496 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
498 elsif m = migrated_collections[migrations[c.portable_data_hash]]
499 manifest = Keep::Manifest.new(m.manifest_text)
500 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
507 # Resolve a Docker repo+tag, hash, or collection PDH to an array of
508 # Collection objects, sorted by timestamp starting with the most recent
511 # If filter_compatible_format is true (the default), only return image
512 # collections which are support by the installation as indicated by
513 # Rails.configuration.Containers.SupportedDockerImageFormats. Will follow
514 # 'docker_image_migration' links if search_term resolves to an incompatible
515 # image, but an equivalent compatible image is available.
516 def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
517 readers ||= [Thread.current[:user]]
519 readable_by(*readers).
520 readable_by(*readers, table_name: "collections").
521 joins("JOIN collections ON links.head_uuid = collections.uuid").
522 order("links.created_at DESC")
524 docker_image_formats = Rails.configuration.Containers.SupportedDockerImageFormats
526 if (docker_image_formats.include? 'v1' and
527 docker_image_formats.include? 'v2') or filter_compatible_format == false
528 pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
529 elsif docker_image_formats.include? 'v2'
530 pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
531 elsif docker_image_formats.include? 'v1'
532 pattern = /^[0-9A-Fa-f]{64}\.tar$/
534 raise "Unrecognized configuration for docker_image_formats #{docker_image_formats}"
537 # If the search term is a Collection locator that contains one file
538 # that looks like a Docker image, return it.
539 if loc = Keep::Locator.parse(search_term)
541 coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
542 rc = Rails.configuration.RemoteClusters.select{ |k|
543 k != :"*" && k != Rails.configuration.ClusterID}
544 if coll_match.any? or rc.length == 0
545 return get_compatible_images(readers, pattern, coll_match)
547 # Allow bare pdh that doesn't exist in the local database so
548 # that federated container requests which refer to remotely
549 # stored containers will validate.
550 return [Collection.new(portable_data_hash: loc.to_s)]
554 if search_tag.nil? and (n = search_term.index(":"))
555 search_tag = search_term[n+1..-1]
556 search_term = search_term[0..n-1]
559 # Find Collections with matching Docker image repository+tag pairs.
560 matches = base_search.
561 where(link_class: "docker_image_repo+tag",
562 name: "#{search_term}:#{search_tag || 'latest'}")
564 # If that didn't work, find Collections with matching Docker image hashes.
566 matches = base_search.
567 where("link_class = ? and links.name LIKE ?",
568 "docker_image_hash", "#{search_term}%")
571 # Generate an order key for each result. We want to order the results
572 # so that anything with an image timestamp is considered more recent than
573 # anything without; then we use the link's created_at as a tiebreaker.
575 matches.each do |link|
576 uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
577 -link.created_at.to_i]
580 sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
581 uuid_timestamps[c.uuid]
583 compatible = get_compatible_images(readers, pattern, sorted)
584 if sorted.length > 0 and compatible.empty?
585 raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
590 def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
591 find_all_for_docker_image(search_term, search_tag, readers).first
594 def self.searchable_columns operator
595 super - ["manifest_text"]
598 def self.full_text_searchable_columns
599 super - ["manifest_text", "storage_classes_desired", "storage_classes_confirmed", "current_version_uuid"]
603 SweepTrashedObjects.sweep_if_stale
609 # Although the defaults for these columns is already set up on the schema,
610 # collection creation from an API client seems to ignore them, making the
611 # validation on empty desired storage classes return an error.
612 def default_storage_classes
613 if self.storage_classes_desired.nil? || self.storage_classes_desired.empty?
614 self.storage_classes_desired = ["default"]
616 self.storage_classes_confirmed ||= []
619 # Sets managed properties at creation time
620 def managed_properties
621 managed_props = Rails.configuration.Collections.ManagedProperties.with_indifferent_access
622 if managed_props.empty?
625 (managed_props.keys - self.properties.keys).each do |key|
626 if managed_props[key].has_key?('Value')
627 self.properties[key] = managed_props[key]['Value']
628 elsif managed_props[key]['Function'].andand == 'original_owner'
629 self.properties[key] = self.user_owner_uuid
631 logger.warn "Unidentified default property definition '#{key}': #{managed_props[key].inspect}"
636 def portable_manifest_text
637 self.class.munge_manifest_locators(manifest_text) do |match|
647 portable_manifest = portable_manifest_text
648 (Digest::MD5.hexdigest(portable_manifest) +
650 portable_manifest.bytesize.to_s)
654 if @computed_pdh_for_manifest_text == manifest_text
657 @computed_pdh = compute_pdh
658 @computed_pdh_for_manifest_text = manifest_text.dup
662 def ensure_permission_to_save
663 if (not current_user.andand.is_admin)
664 if (replication_confirmed_at_changed? or replication_confirmed_changed?) and
665 not (replication_confirmed_at.nil? and replication_confirmed.nil?)
666 raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
668 if (storage_classes_confirmed_changed? or storage_classes_confirmed_at_changed?) and
669 not (storage_classes_confirmed == [] and storage_classes_confirmed_at.nil?)
670 raise ArvadosModel::PermissionDeniedError.new("storage_classes_confirmed and storage_classes_confirmed_at attributes cannot be changed, except by setting them to [] and nil respectively")
676 def ensure_storage_classes_desired_is_not_empty
677 if self.storage_classes_desired.empty?
678 raise ArvadosModel::InvalidStateTransitionError.new("storage_classes_desired shouldn't be empty")
682 def ensure_storage_classes_contain_non_empty_strings
683 (self.storage_classes_desired + self.storage_classes_confirmed).each do |c|
684 if !c.is_a?(String) || c == ''
685 raise ArvadosModel::InvalidStateTransitionError.new("storage classes should only be non-empty strings")
690 def past_versions_cannot_be_updated
692 errors.add(:base, "past versions cannot be updated")
697 def protected_managed_properties_updates
698 managed_properties = Rails.configuration.Collections.ManagedProperties.with_indifferent_access
699 if managed_properties.empty? || !properties_changed? || current_user.is_admin
702 protected_props = managed_properties.keys.select do |p|
703 Rails.configuration.Collections.ManagedProperties[p]['Protected']
705 # Pre-existent protected properties can't be updated
706 invalid_updates = properties_was.keys.select{|p| properties_was[p] != properties[p]} & protected_props
707 if !invalid_updates.empty?
708 invalid_updates.each do |p|
709 errors.add("protected property cannot be updated:", p)
711 raise PermissionDeniedError.new
716 def versioning_metadata_updates
718 if !is_past_version? && current_version_uuid_changed?
719 errors.add(:current_version_uuid, "cannot be updated")
723 errors.add(:version, "cannot be updated")
731 self.current_version_uuid ||= self.uuid