1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
6 require 'sweep_trashed_collections'
9 class Collection < ArvadosModel
10 extend CurrentApiClient
14 include CommonApiTemplate
17 serialize :properties, Hash
19 before_validation :default_empty_manifest
20 before_validation :check_encoding
21 before_validation :check_manifest_validity
22 before_validation :check_signatures
23 before_validation :strip_signatures_and_update_replication_confirmed
24 validate :ensure_pdh_matches_manifest_text
25 before_save :set_file_names
27 # Query only untrashed collections by default.
28 default_scope { where("is_trashed = false") }
30 api_accessible :user, extend: :common do |t|
34 t.add :portable_data_hash
35 t.add :signed_manifest_text, as: :manifest_text
36 t.add :manifest_text, as: :unsigned_manifest_text
37 t.add :replication_desired
38 t.add :replication_confirmed
39 t.add :replication_confirmed_at
46 @signatures_checked = false
47 @computed_pdh_for_manifest_text = false
50 def self.attributes_required_columns
52 # If we don't list manifest_text explicitly, the
53 # params[:select] code gets confused by the way we
54 # expose signed_manifest_text as manifest_text in the
55 # API response, and never let clients select the
56 # manifest_text column.
58 # We need trash_at and is_trashed to determine the
59 # correct timestamp in signed_manifest_text.
60 'manifest_text' => ['manifest_text', 'trash_at', 'is_trashed'],
61 'unsigned_manifest_text' => ['manifest_text'],
65 def self.ignored_select_attributes
66 super + ["updated_at", "file_names"]
69 def self.limit_index_columns_read
73 FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
75 return false if self.manifest_text.nil?
77 return true if current_user.andand.is_admin
79 # Provided the manifest_text hasn't changed materially since an
80 # earlier validation, it's safe to pass this validation on
81 # subsequent passes without checking any signatures. This is
82 # important because the signatures have probably been stripped off
83 # by the time we get to a second validation pass!
84 if @signatures_checked && @signatures_checked == computed_pdh
88 if self.manifest_text_changed?
89 # Check permissions on the collection manifest.
90 # If any signature cannot be verified, raise PermissionDeniedError
91 # which will return 403 Permission denied to the client.
92 api_token = current_api_client_authorization.andand.api_token
95 now: @validation_timestamp.to_i,
97 self.manifest_text.each_line do |entry|
98 entry.split.each do |tok|
99 if tok == '.' or tok.starts_with? './'
101 elsif tok =~ FILE_TOKEN
102 # This is a filename token, not a blob locator. Note that we
103 # keep checking tokens after this, even though manifest
104 # format dictates that all subsequent tokens will also be
105 # filenames. Safety first!
106 elsif Blob.verify_signature tok, signing_opts
108 elsif Keep::Locator.parse(tok).andand.signature
109 # Signature provided, but verify_signature did not like it.
110 logger.warn "Invalid signature on locator #{tok}"
111 raise ArvadosModel::PermissionDeniedError
112 elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
113 # No signature provided, but we are running in insecure mode.
114 logger.debug "Missing signature on locator #{tok} ignored"
115 elsif Blob.new(tok).empty?
116 # No signature provided -- but no data to protect, either.
118 logger.warn "Missing signature on locator #{tok}"
119 raise ArvadosModel::PermissionDeniedError
124 @signatures_checked = computed_pdh
127 def strip_signatures_and_update_replication_confirmed
128 if self.manifest_text_changed?
130 if not self.replication_confirmed.nil?
131 self.class.each_manifest_locator(manifest_text_was) do |match|
132 in_old_manifest[match[1]] = true
136 stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
137 if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
138 # If the new manifest_text contains locators whose hashes
139 # weren't in the old manifest_text, storage replication is no
141 self.replication_confirmed_at = nil
142 self.replication_confirmed = nil
145 # Return the locator with all permission signatures removed,
146 # but otherwise intact.
147 match[0].gsub(/\+A[^+]*/, '')
150 if @computed_pdh_for_manifest_text == manifest_text
151 # If the cached PDH was valid before stripping, it is still
152 # valid after stripping.
153 @computed_pdh_for_manifest_text = stripped_manifest.dup
156 self[:manifest_text] = stripped_manifest
161 def ensure_pdh_matches_manifest_text
162 if not manifest_text_changed? and not portable_data_hash_changed?
164 elsif portable_data_hash.nil? or not portable_data_hash_changed?
165 self.portable_data_hash = computed_pdh
166 elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
167 errors.add(:portable_data_hash, "is not a valid locator")
169 elsif portable_data_hash[0..31] != computed_pdh[0..31]
170 errors.add(:portable_data_hash,
171 "'#{portable_data_hash}' does not match computed hash '#{computed_pdh}'")
174 # Ignore the client-provided size part: always store
175 # computed_pdh in the database.
176 self.portable_data_hash = computed_pdh
181 if self.manifest_text_changed?
182 self.file_names = manifest_files
189 if self.manifest_text
190 self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
191 names << name.first.gsub('\040',' ') + "\n"
192 break if names.length > 2**12
196 if self.manifest_text and names.length < 2**12
197 self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
198 names << stream_name.first.gsub('\040',' ') + "\n"
199 break if names.length > 2**12
206 def default_empty_manifest
207 self.manifest_text ||= ''
211 if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
215 # If Ruby thinks the encoding is something else, like 7-bit
216 # ASCII, but its stored bytes are equal to the (valid) UTF-8
217 # encoding of the same string, we declare it to be a UTF-8
220 utf8.force_encoding Encoding::UTF_8
221 if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
222 self.manifest_text = utf8
227 errors.add :manifest_text, "must use UTF-8 encoding"
232 def check_manifest_validity
234 Keep::Manifest.validate! manifest_text
236 rescue ArgumentError => e
237 errors.add :manifest_text, e.message
242 def signed_manifest_text
243 if !has_attribute? :manifest_text
248 token = current_api_client_authorization.andand.api_token
249 exp = [db_current_time.to_i + Rails.configuration.blob_signature_ttl,
250 trash_at].compact.map(&:to_i).min
251 self.class.sign_manifest manifest_text, token, exp
255 def self.sign_manifest manifest, token, exp=nil
257 exp = db_current_time.to_i + Rails.configuration.blob_signature_ttl
263 m = munge_manifest_locators(manifest) do |match|
264 Blob.sign_locator(match[0], signing_opts)
269 def self.munge_manifest_locators manifest
270 # Given a manifest text and a block, yield the regexp MatchData
271 # for each locator. Return a new manifest in which each locator
272 # has been replaced by the block's return value.
273 return nil if !manifest
274 return '' if manifest == ''
277 manifest.each_line do |line|
280 line.split(' ').each do |word|
283 elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
284 new_words << yield(match)
289 new_lines << new_words.join(' ')
291 new_lines.join("\n") + "\n"
294 def self.each_manifest_locator manifest
295 # Given a manifest text and a block, yield the regexp match object
297 manifest.each_line do |line|
298 # line will have a trailing newline, but the last token is never
299 # a locator, so it's harmless here.
300 line.split(' ').each do |word|
301 if match = Keep::Locator::LOCATOR_REGEXP.match(word)
308 def self.normalize_uuid uuid
311 uuid.split('+').each do |token|
312 if token.match(/^[0-9a-f]{32,}$/)
313 raise "uuid #{uuid} has multiple hash parts" if hash_part
315 elsif token.match(/^\d+$/)
316 raise "uuid #{uuid} has multiple size parts" if size_part
320 raise "uuid #{uuid} has no hash part" if !hash_part
321 [hash_part, size_part].compact.join '+'
324 def self.get_compatible_images(readers, pattern, collections)
325 if collections.empty?
330 Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
331 collections.map(&:portable_data_hash),
332 'docker_image_migration',
334 order('links.created_at asc').
336 [l.tail_uuid, l.head_uuid]
339 migrated_collections = Hash[
340 Collection.readable_by(*readers).
341 where('portable_data_hash in (?)', migrations.values).
343 [c.portable_data_hash, c]
346 collections.map { |c|
347 # Check if the listed image is compatible first, if not, then try the
349 manifest = Keep::Manifest.new(c.manifest_text)
350 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
352 elsif m = migrated_collections[migrations[c.portable_data_hash]]
353 manifest = Keep::Manifest.new(m.manifest_text)
354 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
361 # Resolve a Docker repo+tag, hash, or collection PDH to an array of
362 # Collection objects, sorted by timestamp starting with the most recent
365 # If filter_compatible_format is true (the default), only return image
366 # collections which are support by the installation as indicated by
367 # Rails.configuration.docker_image_formats. Will follow
368 # 'docker_image_migration' links if search_term resolves to an incompatible
369 # image, but an equivalent compatible image is available.
370 def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
371 readers ||= [Thread.current[:user]]
373 readable_by(*readers).
374 readable_by(*readers, table_name: "collections").
375 joins("JOIN collections ON links.head_uuid = collections.uuid").
376 order("links.created_at DESC")
378 if (Rails.configuration.docker_image_formats.include? 'v1' and
379 Rails.configuration.docker_image_formats.include? 'v2') or filter_compatible_format == false
380 pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
381 elsif Rails.configuration.docker_image_formats.include? 'v2'
382 pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
383 elsif Rails.configuration.docker_image_formats.include? 'v1'
384 pattern = /^[0-9A-Fa-f]{64}\.tar$/
386 raise "Unrecognized configuration for docker_image_formats #{Rails.configuration.docker_image_formats}"
389 # If the search term is a Collection locator that contains one file
390 # that looks like a Docker image, return it.
391 if loc = Keep::Locator.parse(search_term)
393 coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
394 return get_compatible_images(readers, pattern, coll_match)
397 if search_tag.nil? and (n = search_term.index(":"))
398 search_tag = search_term[n+1..-1]
399 search_term = search_term[0..n-1]
402 # Find Collections with matching Docker image repository+tag pairs.
403 matches = base_search.
404 where(link_class: "docker_image_repo+tag",
405 name: "#{search_term}:#{search_tag || 'latest'}")
407 # If that didn't work, find Collections with matching Docker image hashes.
409 matches = base_search.
410 where("link_class = ? and links.name LIKE ?",
411 "docker_image_hash", "#{search_term}%")
414 # Generate an order key for each result. We want to order the results
415 # so that anything with an image timestamp is considered more recent than
416 # anything without; then we use the link's created_at as a tiebreaker.
418 matches.each do |link|
419 uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
420 -link.created_at.to_i]
423 sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
424 uuid_timestamps[c.uuid]
426 compatible = get_compatible_images(readers, pattern, sorted)
427 if sorted.length > 0 and compatible.empty?
428 raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
433 def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
434 find_all_for_docker_image(search_term, search_tag, readers).first
437 def self.searchable_columns operator
438 super - ["manifest_text"]
441 def self.full_text_searchable_columns
442 super - ["manifest_text"]
446 SweepTrashedCollections.sweep_if_stale
451 def portable_manifest_text
452 self.class.munge_manifest_locators(manifest_text) do |match|
462 portable_manifest = portable_manifest_text
463 (Digest::MD5.hexdigest(portable_manifest) +
465 portable_manifest.bytesize.to_s)
469 if @computed_pdh_for_manifest_text == manifest_text
472 @computed_pdh = compute_pdh
473 @computed_pdh_for_manifest_text = manifest_text.dup
477 def ensure_permission_to_save
478 if (not current_user.andand.is_admin and
479 (replication_confirmed_at_changed? or replication_confirmed_changed?) and
480 not (replication_confirmed_at.nil? and replication_confirmed.nil?))
481 raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")