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 before_save :set_file_names
32 api_accessible :user, extend: :common do |t|
36 t.add :portable_data_hash
37 t.add :signed_manifest_text, as: :manifest_text
38 t.add :manifest_text, as: :unsigned_manifest_text
39 t.add :replication_desired
40 t.add :replication_confirmed
41 t.add :replication_confirmed_at
42 t.add :storage_classes_desired
43 t.add :storage_classes_confirmed
44 t.add :storage_classes_confirmed_at
51 @signatures_checked = false
52 @computed_pdh_for_manifest_text = false
55 def self.attributes_required_columns
57 # If we don't list manifest_text explicitly, the
58 # params[:select] code gets confused by the way we
59 # expose signed_manifest_text as manifest_text in the
60 # API response, and never let clients select the
61 # manifest_text column.
63 # We need trash_at and is_trashed to determine the
64 # correct timestamp in signed_manifest_text.
65 'manifest_text' => ['manifest_text', 'trash_at', 'is_trashed'],
66 'unsigned_manifest_text' => ['manifest_text'],
70 def self.ignored_select_attributes
71 super + ["updated_at", "file_names"]
74 def self.limit_index_columns_read
78 FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
80 return false if self.manifest_text.nil?
82 return true if current_user.andand.is_admin
84 # Provided the manifest_text hasn't changed materially since an
85 # earlier validation, it's safe to pass this validation on
86 # subsequent passes without checking any signatures. This is
87 # important because the signatures have probably been stripped off
88 # by the time we get to a second validation pass!
89 if @signatures_checked && @signatures_checked == computed_pdh
93 if self.manifest_text_changed?
94 # Check permissions on the collection manifest.
95 # If any signature cannot be verified, raise PermissionDeniedError
96 # which will return 403 Permission denied to the client.
97 api_token = Thread.current[:token]
100 now: @validation_timestamp.to_i,
102 self.manifest_text.each_line do |entry|
103 entry.split.each do |tok|
104 if tok == '.' or tok.starts_with? './'
106 elsif tok =~ FILE_TOKEN
107 # This is a filename token, not a blob locator. Note that we
108 # keep checking tokens after this, even though manifest
109 # format dictates that all subsequent tokens will also be
110 # filenames. Safety first!
111 elsif Blob.verify_signature tok, signing_opts
113 elsif Keep::Locator.parse(tok).andand.signature
114 # Signature provided, but verify_signature did not like it.
115 logger.warn "Invalid signature on locator #{tok}"
116 raise ArvadosModel::PermissionDeniedError
117 elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
118 # No signature provided, but we are running in insecure mode.
119 logger.debug "Missing signature on locator #{tok} ignored"
120 elsif Blob.new(tok).empty?
121 # No signature provided -- but no data to protect, either.
123 logger.warn "Missing signature on locator #{tok}"
124 raise ArvadosModel::PermissionDeniedError
129 @signatures_checked = computed_pdh
132 def strip_signatures_and_update_replication_confirmed
133 if self.manifest_text_changed?
135 if not self.replication_confirmed.nil?
136 self.class.each_manifest_locator(manifest_text_was) do |match|
137 in_old_manifest[match[1]] = true
141 stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
142 if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
143 # If the new manifest_text contains locators whose hashes
144 # weren't in the old manifest_text, storage replication is no
146 self.replication_confirmed_at = nil
147 self.replication_confirmed = nil
150 # Return the locator with all permission signatures removed,
151 # but otherwise intact.
152 match[0].gsub(/\+A[^+]*/, '')
155 if @computed_pdh_for_manifest_text == manifest_text
156 # If the cached PDH was valid before stripping, it is still
157 # valid after stripping.
158 @computed_pdh_for_manifest_text = stripped_manifest.dup
161 self[:manifest_text] = stripped_manifest
166 def ensure_pdh_matches_manifest_text
167 if not manifest_text_changed? and not portable_data_hash_changed?
169 elsif portable_data_hash.nil? or not portable_data_hash_changed?
170 self.portable_data_hash = computed_pdh
171 elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
172 errors.add(:portable_data_hash, "is not a valid locator")
174 elsif portable_data_hash[0..31] != computed_pdh[0..31]
175 errors.add(:portable_data_hash,
176 "'#{portable_data_hash}' does not match computed hash '#{computed_pdh}'")
179 # Ignore the client-provided size part: always store
180 # computed_pdh in the database.
181 self.portable_data_hash = computed_pdh
186 if self.manifest_text_changed?
187 self.file_names = manifest_files
193 return '' if !self.manifest_text
196 self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
197 names << name.first.gsub('\040',' ') + "\n"
199 self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
200 names << stream_name.first.gsub('\040',' ') + "\n"
205 def default_empty_manifest
206 self.manifest_text ||= ''
210 if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
214 # If Ruby thinks the encoding is something else, like 7-bit
215 # ASCII, but its stored bytes are equal to the (valid) UTF-8
216 # encoding of the same string, we declare it to be a UTF-8
219 utf8.force_encoding Encoding::UTF_8
220 if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
221 self.manifest_text = utf8
226 errors.add :manifest_text, "must use UTF-8 encoding"
231 def check_manifest_validity
233 Keep::Manifest.validate! manifest_text
235 rescue ArgumentError => e
236 errors.add :manifest_text, e.message
241 def signed_manifest_text
242 if !has_attribute? :manifest_text
247 token = Thread.current[:token]
248 exp = [db_current_time.to_i + Rails.configuration.blob_signature_ttl,
249 trash_at].compact.map(&:to_i).min
250 self.class.sign_manifest manifest_text, token, exp
254 def self.sign_manifest manifest, token, exp=nil
256 exp = db_current_time.to_i + Rails.configuration.blob_signature_ttl
262 m = munge_manifest_locators(manifest) do |match|
263 Blob.sign_locator(match[0], signing_opts)
268 def self.munge_manifest_locators manifest
269 # Given a manifest text and a block, yield the regexp MatchData
270 # for each locator. Return a new manifest in which each locator
271 # has been replaced by the block's return value.
272 return nil if !manifest
273 return '' if manifest == ''
276 manifest.each_line do |line|
279 line.split(' ').each do |word|
282 elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
283 new_words << yield(match)
288 new_lines << new_words.join(' ')
290 new_lines.join("\n") + "\n"
293 def self.each_manifest_locator manifest
294 # Given a manifest text and a block, yield the regexp match object
296 manifest.each_line do |line|
297 # line will have a trailing newline, but the last token is never
298 # a locator, so it's harmless here.
299 line.split(' ').each do |word|
300 if match = Keep::Locator::LOCATOR_REGEXP.match(word)
307 def self.normalize_uuid uuid
310 uuid.split('+').each do |token|
311 if token.match(/^[0-9a-f]{32,}$/)
312 raise "uuid #{uuid} has multiple hash parts" if hash_part
314 elsif token.match(/^\d+$/)
315 raise "uuid #{uuid} has multiple size parts" if size_part
319 raise "uuid #{uuid} has no hash part" if !hash_part
320 [hash_part, size_part].compact.join '+'
323 def self.get_compatible_images(readers, pattern, collections)
324 if collections.empty?
329 Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
330 collections.map(&:portable_data_hash),
331 'docker_image_migration',
333 order('links.created_at asc').
335 [l.tail_uuid, l.head_uuid]
338 migrated_collections = Hash[
339 Collection.readable_by(*readers).
340 where('portable_data_hash in (?)', migrations.values).
342 [c.portable_data_hash, c]
345 collections.map { |c|
346 # Check if the listed image is compatible first, if not, then try the
348 manifest = Keep::Manifest.new(c.manifest_text)
349 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
351 elsif m = migrated_collections[migrations[c.portable_data_hash]]
352 manifest = Keep::Manifest.new(m.manifest_text)
353 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
360 # Resolve a Docker repo+tag, hash, or collection PDH to an array of
361 # Collection objects, sorted by timestamp starting with the most recent
364 # If filter_compatible_format is true (the default), only return image
365 # collections which are support by the installation as indicated by
366 # Rails.configuration.docker_image_formats. Will follow
367 # 'docker_image_migration' links if search_term resolves to an incompatible
368 # image, but an equivalent compatible image is available.
369 def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
370 readers ||= [Thread.current[:user]]
372 readable_by(*readers).
373 readable_by(*readers, table_name: "collections").
374 joins("JOIN collections ON links.head_uuid = collections.uuid").
375 order("links.created_at DESC")
377 if (Rails.configuration.docker_image_formats.include? 'v1' and
378 Rails.configuration.docker_image_formats.include? 'v2') or filter_compatible_format == false
379 pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
380 elsif Rails.configuration.docker_image_formats.include? 'v2'
381 pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
382 elsif Rails.configuration.docker_image_formats.include? 'v1'
383 pattern = /^[0-9A-Fa-f]{64}\.tar$/
385 raise "Unrecognized configuration for docker_image_formats #{Rails.configuration.docker_image_formats}"
388 # If the search term is a Collection locator that contains one file
389 # that looks like a Docker image, return it.
390 if loc = Keep::Locator.parse(search_term)
392 coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
393 return get_compatible_images(readers, pattern, coll_match)
396 if search_tag.nil? and (n = search_term.index(":"))
397 search_tag = search_term[n+1..-1]
398 search_term = search_term[0..n-1]
401 # Find Collections with matching Docker image repository+tag pairs.
402 matches = base_search.
403 where(link_class: "docker_image_repo+tag",
404 name: "#{search_term}:#{search_tag || 'latest'}")
406 # If that didn't work, find Collections with matching Docker image hashes.
408 matches = base_search.
409 where("link_class = ? and links.name LIKE ?",
410 "docker_image_hash", "#{search_term}%")
413 # Generate an order key for each result. We want to order the results
414 # so that anything with an image timestamp is considered more recent than
415 # anything without; then we use the link's created_at as a tiebreaker.
417 matches.each do |link|
418 uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
419 -link.created_at.to_i]
422 sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
423 uuid_timestamps[c.uuid]
425 compatible = get_compatible_images(readers, pattern, sorted)
426 if sorted.length > 0 and compatible.empty?
427 raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
432 def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
433 find_all_for_docker_image(search_term, search_tag, readers).first
436 def self.searchable_columns operator
437 super - ["manifest_text"]
440 def self.full_text_searchable_columns
441 super - ["manifest_text", "storage_classes_desired", "storage_classes_confirmed"]
445 SweepTrashedObjects.sweep_if_stale
451 # Although the defaults for these columns is already set up on the schema,
452 # collection creation from an API client seems to ignore them, making the
453 # validation on empty desired storage classes return an error.
454 def default_storage_classes
455 if self.storage_classes_desired.nil? || self.storage_classes_desired.empty?
456 self.storage_classes_desired = ["default"]
458 self.storage_classes_confirmed ||= []
461 def portable_manifest_text
462 self.class.munge_manifest_locators(manifest_text) do |match|
472 portable_manifest = portable_manifest_text
473 (Digest::MD5.hexdigest(portable_manifest) +
475 portable_manifest.bytesize.to_s)
479 if @computed_pdh_for_manifest_text == manifest_text
482 @computed_pdh = compute_pdh
483 @computed_pdh_for_manifest_text = manifest_text.dup
487 def ensure_permission_to_save
488 if (not current_user.andand.is_admin)
489 if (replication_confirmed_at_changed? or replication_confirmed_changed?) and
490 not (replication_confirmed_at.nil? and replication_confirmed.nil?)
491 raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
493 if (storage_classes_confirmed_changed? or storage_classes_confirmed_at_changed?) and
494 not (storage_classes_confirmed == [] and storage_classes_confirmed_at.nil?)
495 raise ArvadosModel::PermissionDeniedError.new("storage_classes_confirmed and storage_classes_confirmed_at attributes cannot be changed, except by setting them to [] and nil respectively")
501 def ensure_storage_classes_desired_is_not_empty
502 if self.storage_classes_desired.empty?
503 raise ArvadosModel::InvalidStateTransitionError.new("storage_classes_desired shouldn't be empty")
507 def ensure_storage_classes_contain_non_empty_strings
508 (self.storage_classes_desired + self.storage_classes_confirmed).each do |c|
509 if !c.is_a?(String) || c == ''
510 raise ArvadosModel::InvalidStateTransitionError.new("storage classes should only be non-empty strings")