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 serialize :properties, Hash
18 serialize :storage_classes_desired, Array
19 serialize :storage_classes_confirmed, Array
21 before_validation :default_empty_manifest
22 before_validation :default_storage_classes, on: :create
23 before_validation :check_encoding
24 before_validation :check_manifest_validity
25 before_validation :check_signatures
26 before_validation :strip_signatures_and_update_replication_confirmed
27 validate :ensure_pdh_matches_manifest_text
28 validate :ensure_storage_classes_desired_is_not_empty
29 validate :ensure_storage_classes_contain_non_empty_strings
30 validate :versioning_metadata_updates, on: :update
31 validate :past_versions_cannot_be_updated, on: :update
32 before_save :set_file_names
33 around_update :manage_versioning
35 api_accessible :user, extend: :common do |t|
39 t.add :portable_data_hash
40 t.add :signed_manifest_text, as: :manifest_text
41 t.add :manifest_text, as: :unsigned_manifest_text
42 t.add :replication_desired
43 t.add :replication_confirmed
44 t.add :replication_confirmed_at
45 t.add :storage_classes_desired
46 t.add :storage_classes_confirmed
47 t.add :storage_classes_confirmed_at
52 t.add :current_version_uuid
53 t.add :preserve_version
57 @signatures_checked = false
58 @computed_pdh_for_manifest_text = false
61 def self.attributes_required_columns
63 # If we don't list manifest_text explicitly, the
64 # params[:select] code gets confused by the way we
65 # expose signed_manifest_text as manifest_text in the
66 # API response, and never let clients select the
67 # manifest_text column.
69 # We need trash_at and is_trashed to determine the
70 # correct timestamp in signed_manifest_text.
71 'manifest_text' => ['manifest_text', 'trash_at', 'is_trashed'],
72 'unsigned_manifest_text' => ['manifest_text'],
76 def self.ignored_select_attributes
77 super + ["updated_at", "file_names"]
80 def self.limit_index_columns_read
84 FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
86 return false if self.manifest_text.nil?
88 return true if current_user.andand.is_admin
90 # Provided the manifest_text hasn't changed materially since an
91 # earlier validation, it's safe to pass this validation on
92 # subsequent passes without checking any signatures. This is
93 # important because the signatures have probably been stripped off
94 # by the time we get to a second validation pass!
95 if @signatures_checked && @signatures_checked == computed_pdh
99 if self.manifest_text_changed?
100 # Check permissions on the collection manifest.
101 # If any signature cannot be verified, raise PermissionDeniedError
102 # which will return 403 Permission denied to the client.
103 api_token = Thread.current[:token]
105 api_token: api_token,
106 now: @validation_timestamp.to_i,
108 self.manifest_text.each_line do |entry|
109 entry.split.each do |tok|
110 if tok == '.' or tok.starts_with? './'
112 elsif tok =~ FILE_TOKEN
113 # This is a filename token, not a blob locator. Note that we
114 # keep checking tokens after this, even though manifest
115 # format dictates that all subsequent tokens will also be
116 # filenames. Safety first!
117 elsif Blob.verify_signature tok, signing_opts
119 elsif Keep::Locator.parse(tok).andand.signature
120 # Signature provided, but verify_signature did not like it.
121 logger.warn "Invalid signature on locator #{tok}"
122 raise ArvadosModel::PermissionDeniedError
123 elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
124 # No signature provided, but we are running in insecure mode.
125 logger.debug "Missing signature on locator #{tok} ignored"
126 elsif Blob.new(tok).empty?
127 # No signature provided -- but no data to protect, either.
129 logger.warn "Missing signature on locator #{tok}"
130 raise ArvadosModel::PermissionDeniedError
135 @signatures_checked = computed_pdh
138 def strip_signatures_and_update_replication_confirmed
139 if self.manifest_text_changed?
141 if not self.replication_confirmed.nil?
142 self.class.each_manifest_locator(manifest_text_was) do |match|
143 in_old_manifest[match[1]] = true
147 stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
148 if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
149 # If the new manifest_text contains locators whose hashes
150 # weren't in the old manifest_text, storage replication is no
152 self.replication_confirmed_at = nil
153 self.replication_confirmed = nil
156 # Return the locator with all permission signatures removed,
157 # but otherwise intact.
158 match[0].gsub(/\+A[^+]*/, '')
161 if @computed_pdh_for_manifest_text == manifest_text
162 # If the cached PDH was valid before stripping, it is still
163 # valid after stripping.
164 @computed_pdh_for_manifest_text = stripped_manifest.dup
167 self[:manifest_text] = stripped_manifest
172 def ensure_pdh_matches_manifest_text
173 if not manifest_text_changed? and not portable_data_hash_changed?
175 elsif portable_data_hash.nil? or not portable_data_hash_changed?
176 self.portable_data_hash = computed_pdh
177 elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
178 errors.add(:portable_data_hash, "is not a valid locator")
180 elsif portable_data_hash[0..31] != computed_pdh[0..31]
181 errors.add(:portable_data_hash,
182 "'#{portable_data_hash}' does not match computed hash '#{computed_pdh}'")
185 # Ignore the client-provided size part: always store
186 # computed_pdh in the database.
187 self.portable_data_hash = computed_pdh
192 if self.manifest_text_changed?
193 self.file_names = manifest_files
199 return '' if !self.manifest_text
203 self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
206 names << name.first.gsub('\040',' ') + "\n"
208 self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
209 next if done[stream_name]
210 done[stream_name] = true
211 names << stream_name.first.gsub('\040',' ') + "\n"
216 def default_empty_manifest
217 self.manifest_text ||= ''
220 def skip_uuid_existence_check
221 # Avoid checking the existence of current_version_uuid, as it's
222 # assigned on creation of a new 'current version' collection, so
223 # the collection's UUID only lives on memory when the validation check
225 ['current_version_uuid']
228 def manage_versioning
229 should_preserve_version = should_preserve_version? # Time sensitive, cache value
230 return(yield) unless (should_preserve_version || syncable_updates.any?)
232 # Put aside the changes because with_lock forces a record reload
233 changes = self.changes
236 # Copy the original state to save it as old version
237 if should_preserve_version
239 snapshot.uuid = nil # Reset UUID so it's created as a new record
240 snapshot.created_at = self.created_at
243 # Restore requested changes on the current version
244 changes.keys.each do |attr|
245 if attr == 'preserve_version' && changes[attr].last == false
246 next # Ignore false assignment, once true it'll be true until next version
248 self.attributes = {attr => changes[attr].last}
250 # Also update the current version reference
251 self.attributes = {'current_version_uuid' => changes[attr].last}
255 if should_preserve_version
257 self.preserve_version = false
262 sync_past_versions if syncable_updates.any?
264 snapshot.attributes = self.syncable_updates
272 (syncable_attrs & self.changes.keys).each do |attr|
274 # Point old versions to current version's new UUID
275 updates['current_version_uuid'] = self.changes[attr].last
277 updates[attr] = self.changes[attr].last
283 def sync_past_versions
284 updates = self.syncable_updates
285 Collection.where('current_version_uuid = ? AND uuid != ?', self.uuid_was, self.uuid_was).each do |c|
286 c.attributes = updates
287 # Use a different validation context to skip the 'old_versions_cannot_be_updated'
288 # validator, as on this case it is legal to update some fields.
289 leave_modified_by_user_alone do
290 leave_modified_at_alone do
291 c.save(context: :update_old_versions)
297 def versionable_updates?(attrs)
298 (['manifest_text', 'description', 'properties', 'name'] & attrs).any?
302 ['uuid', 'owner_uuid', 'delete_at', 'trash_at', 'is_trashed', 'replication_desired', 'storage_classes_desired']
305 def should_preserve_version?
306 return false unless (Rails.configuration.collection_versioning && versionable_updates?(self.changes.keys))
308 idle_threshold = Rails.configuration.preserve_version_if_idle
309 if !self.preserve_version_was &&
310 (idle_threshold < 0 ||
311 (idle_threshold > 0 && self.modified_at_was > db_current_time-idle_threshold.seconds))
318 if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
322 # If Ruby thinks the encoding is something else, like 7-bit
323 # ASCII, but its stored bytes are equal to the (valid) UTF-8
324 # encoding of the same string, we declare it to be a UTF-8
327 utf8.force_encoding Encoding::UTF_8
328 if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
329 self.manifest_text = utf8
334 errors.add :manifest_text, "must use UTF-8 encoding"
339 def check_manifest_validity
341 Keep::Manifest.validate! manifest_text
343 rescue ArgumentError => e
344 errors.add :manifest_text, e.message
349 def signed_manifest_text
350 if !has_attribute? :manifest_text
355 token = Thread.current[:token]
356 exp = [db_current_time.to_i + Rails.configuration.blob_signature_ttl,
357 trash_at].compact.map(&:to_i).min
358 self.class.sign_manifest manifest_text, token, exp
362 def self.sign_manifest manifest, token, exp=nil
364 exp = db_current_time.to_i + Rails.configuration.blob_signature_ttl
370 m = munge_manifest_locators(manifest) do |match|
371 Blob.sign_locator(match[0], signing_opts)
376 def self.munge_manifest_locators manifest
377 # Given a manifest text and a block, yield the regexp MatchData
378 # for each locator. Return a new manifest in which each locator
379 # has been replaced by the block's return value.
380 return nil if !manifest
381 return '' if manifest == ''
384 manifest.each_line do |line|
387 line.split(' ').each do |word|
390 elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
391 new_words << yield(match)
396 new_lines << new_words.join(' ')
398 new_lines.join("\n") + "\n"
401 def self.each_manifest_locator manifest
402 # Given a manifest text and a block, yield the regexp match object
404 manifest.each_line do |line|
405 # line will have a trailing newline, but the last token is never
406 # a locator, so it's harmless here.
407 line.split(' ').each do |word|
408 if match = Keep::Locator::LOCATOR_REGEXP.match(word)
415 def self.normalize_uuid uuid
418 uuid.split('+').each do |token|
419 if token.match(/^[0-9a-f]{32,}$/)
420 raise "uuid #{uuid} has multiple hash parts" if hash_part
422 elsif token.match(/^\d+$/)
423 raise "uuid #{uuid} has multiple size parts" if size_part
427 raise "uuid #{uuid} has no hash part" if !hash_part
428 [hash_part, size_part].compact.join '+'
431 def self.get_compatible_images(readers, pattern, collections)
432 if collections.empty?
437 Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
438 collections.map(&:portable_data_hash),
439 'docker_image_migration',
441 order('links.created_at asc').
443 [l.tail_uuid, l.head_uuid]
446 migrated_collections = Hash[
447 Collection.readable_by(*readers).
448 where('portable_data_hash in (?)', migrations.values).
450 [c.portable_data_hash, c]
453 collections.map { |c|
454 # Check if the listed image is compatible first, if not, then try the
456 manifest = Keep::Manifest.new(c.manifest_text)
457 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
459 elsif m = migrated_collections[migrations[c.portable_data_hash]]
460 manifest = Keep::Manifest.new(m.manifest_text)
461 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
468 # Resolve a Docker repo+tag, hash, or collection PDH to an array of
469 # Collection objects, sorted by timestamp starting with the most recent
472 # If filter_compatible_format is true (the default), only return image
473 # collections which are support by the installation as indicated by
474 # Rails.configuration.docker_image_formats. Will follow
475 # 'docker_image_migration' links if search_term resolves to an incompatible
476 # image, but an equivalent compatible image is available.
477 def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
478 readers ||= [Thread.current[:user]]
480 readable_by(*readers).
481 readable_by(*readers, table_name: "collections").
482 joins("JOIN collections ON links.head_uuid = collections.uuid").
483 order("links.created_at DESC")
485 if (Rails.configuration.docker_image_formats.include? 'v1' and
486 Rails.configuration.docker_image_formats.include? 'v2') or filter_compatible_format == false
487 pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
488 elsif Rails.configuration.docker_image_formats.include? 'v2'
489 pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
490 elsif Rails.configuration.docker_image_formats.include? 'v1'
491 pattern = /^[0-9A-Fa-f]{64}\.tar$/
493 raise "Unrecognized configuration for docker_image_formats #{Rails.configuration.docker_image_formats}"
496 # If the search term is a Collection locator that contains one file
497 # that looks like a Docker image, return it.
498 if loc = Keep::Locator.parse(search_term)
500 coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
501 if coll_match.any? or Rails.configuration.remote_hosts.length == 0
502 return get_compatible_images(readers, pattern, coll_match)
504 # Allow bare pdh that doesn't exist in the local database so
505 # that federated container requests which refer to remotely
506 # stored containers will validate.
507 return [Collection.new(portable_data_hash: loc.to_s)]
511 if search_tag.nil? and (n = search_term.index(":"))
512 search_tag = search_term[n+1..-1]
513 search_term = search_term[0..n-1]
516 # Find Collections with matching Docker image repository+tag pairs.
517 matches = base_search.
518 where(link_class: "docker_image_repo+tag",
519 name: "#{search_term}:#{search_tag || 'latest'}")
521 # If that didn't work, find Collections with matching Docker image hashes.
523 matches = base_search.
524 where("link_class = ? and links.name LIKE ?",
525 "docker_image_hash", "#{search_term}%")
528 # Generate an order key for each result. We want to order the results
529 # so that anything with an image timestamp is considered more recent than
530 # anything without; then we use the link's created_at as a tiebreaker.
532 matches.each do |link|
533 uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
534 -link.created_at.to_i]
537 sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
538 uuid_timestamps[c.uuid]
540 compatible = get_compatible_images(readers, pattern, sorted)
541 if sorted.length > 0 and compatible.empty?
542 raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
547 def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
548 find_all_for_docker_image(search_term, search_tag, readers).first
551 def self.searchable_columns operator
552 super - ["manifest_text"]
555 def self.full_text_searchable_columns
556 super - ["manifest_text", "storage_classes_desired", "storage_classes_confirmed", "current_version_uuid"]
560 SweepTrashedObjects.sweep_if_stale
566 # Although the defaults for these columns is already set up on the schema,
567 # collection creation from an API client seems to ignore them, making the
568 # validation on empty desired storage classes return an error.
569 def default_storage_classes
570 if self.storage_classes_desired.nil? || self.storage_classes_desired.empty?
571 self.storage_classes_desired = ["default"]
573 self.storage_classes_confirmed ||= []
576 def portable_manifest_text
577 self.class.munge_manifest_locators(manifest_text) do |match|
587 portable_manifest = portable_manifest_text
588 (Digest::MD5.hexdigest(portable_manifest) +
590 portable_manifest.bytesize.to_s)
594 if @computed_pdh_for_manifest_text == manifest_text
597 @computed_pdh = compute_pdh
598 @computed_pdh_for_manifest_text = manifest_text.dup
602 def ensure_permission_to_save
603 if (not current_user.andand.is_admin)
604 if (replication_confirmed_at_changed? or replication_confirmed_changed?) and
605 not (replication_confirmed_at.nil? and replication_confirmed.nil?)
606 raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
608 if (storage_classes_confirmed_changed? or storage_classes_confirmed_at_changed?) and
609 not (storage_classes_confirmed == [] and storage_classes_confirmed_at.nil?)
610 raise ArvadosModel::PermissionDeniedError.new("storage_classes_confirmed and storage_classes_confirmed_at attributes cannot be changed, except by setting them to [] and nil respectively")
616 def ensure_storage_classes_desired_is_not_empty
617 if self.storage_classes_desired.empty?
618 raise ArvadosModel::InvalidStateTransitionError.new("storage_classes_desired shouldn't be empty")
622 def ensure_storage_classes_contain_non_empty_strings
623 (self.storage_classes_desired + self.storage_classes_confirmed).each do |c|
624 if !c.is_a?(String) || c == ''
625 raise ArvadosModel::InvalidStateTransitionError.new("storage classes should only be non-empty strings")
630 def past_versions_cannot_be_updated
631 # We check for the '_was' values just in case the update operation
632 # includes a change on current_version_uuid or uuid.
633 if current_version_uuid_was != uuid_was
634 errors.add(:base, "past versions cannot be updated")
639 def versioning_metadata_updates
641 if (current_version_uuid_was == uuid_was) && current_version_uuid_changed?
642 errors.add(:current_version_uuid, "cannot be updated")
646 errors.add(:version, "cannot be updated")
654 self.current_version_uuid ||= self.uuid