1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
6 require 'sweep_trashed_collections'
8 class Collection < ArvadosModel
9 extend CurrentApiClient
13 include CommonApiTemplate
15 serialize :properties, Hash
17 before_validation :set_validation_timestamp
18 before_validation :default_empty_manifest
19 before_validation :check_encoding
20 before_validation :check_manifest_validity
21 before_validation :check_signatures
22 before_validation :strip_signatures_and_update_replication_confirmed
23 before_validation :ensure_trash_at_not_in_past
24 before_validation :sync_trash_state
25 before_validation :default_trash_interval
26 validate :ensure_pdh_matches_manifest_text
27 validate :validate_trash_and_delete_timing
28 before_save :set_file_names
30 # Query only untrashed collections by default.
31 default_scope { where("is_trashed = false") }
33 api_accessible :user, extend: :common do |t|
37 t.add :portable_data_hash
38 t.add :signed_manifest_text, as: :manifest_text
39 t.add :manifest_text, as: :unsigned_manifest_text
40 t.add :replication_desired
41 t.add :replication_confirmed
42 t.add :replication_confirmed_at
49 @signatures_checked = false
50 @computed_pdh_for_manifest_text = false
53 def self.attributes_required_columns
55 # If we don't list manifest_text explicitly, the
56 # params[:select] code gets confused by the way we
57 # expose signed_manifest_text as manifest_text in the
58 # API response, and never let clients select the
59 # manifest_text column.
61 # We need trash_at and is_trashed to determine the
62 # correct timestamp in signed_manifest_text.
63 'manifest_text' => ['manifest_text', 'trash_at', 'is_trashed'],
64 'unsigned_manifest_text' => ['manifest_text'],
68 def self.ignored_select_attributes
69 super + ["updated_at", "file_names"]
72 def self.limit_index_columns_read
76 FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
78 return false if self.manifest_text.nil?
80 return true if current_user.andand.is_admin
82 # Provided the manifest_text hasn't changed materially since an
83 # earlier validation, it's safe to pass this validation on
84 # subsequent passes without checking any signatures. This is
85 # important because the signatures have probably been stripped off
86 # by the time we get to a second validation pass!
87 if @signatures_checked && @signatures_checked == computed_pdh
91 if self.manifest_text_changed?
92 # Check permissions on the collection manifest.
93 # If any signature cannot be verified, raise PermissionDeniedError
94 # which will return 403 Permission denied to the client.
95 api_token = current_api_client_authorization.andand.api_token
98 now: @validation_timestamp.to_i,
100 self.manifest_text.each_line do |entry|
101 entry.split.each do |tok|
102 if tok == '.' or tok.starts_with? './'
104 elsif tok =~ FILE_TOKEN
105 # This is a filename token, not a blob locator. Note that we
106 # keep checking tokens after this, even though manifest
107 # format dictates that all subsequent tokens will also be
108 # filenames. Safety first!
109 elsif Blob.verify_signature tok, signing_opts
111 elsif Keep::Locator.parse(tok).andand.signature
112 # Signature provided, but verify_signature did not like it.
113 logger.warn "Invalid signature on locator #{tok}"
114 raise ArvadosModel::PermissionDeniedError
115 elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
116 # No signature provided, but we are running in insecure mode.
117 logger.debug "Missing signature on locator #{tok} ignored"
118 elsif Blob.new(tok).empty?
119 # No signature provided -- but no data to protect, either.
121 logger.warn "Missing signature on locator #{tok}"
122 raise ArvadosModel::PermissionDeniedError
127 @signatures_checked = computed_pdh
130 def strip_signatures_and_update_replication_confirmed
131 if self.manifest_text_changed?
133 if not self.replication_confirmed.nil?
134 self.class.each_manifest_locator(manifest_text_was) do |match|
135 in_old_manifest[match[1]] = true
139 stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
140 if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
141 # If the new manifest_text contains locators whose hashes
142 # weren't in the old manifest_text, storage replication is no
144 self.replication_confirmed_at = nil
145 self.replication_confirmed = nil
148 # Return the locator with all permission signatures removed,
149 # but otherwise intact.
150 match[0].gsub(/\+A[^+]*/, '')
153 if @computed_pdh_for_manifest_text == manifest_text
154 # If the cached PDH was valid before stripping, it is still
155 # valid after stripping.
156 @computed_pdh_for_manifest_text = stripped_manifest.dup
159 self[:manifest_text] = stripped_manifest
164 def ensure_pdh_matches_manifest_text
165 if not manifest_text_changed? and not portable_data_hash_changed?
167 elsif portable_data_hash.nil? or not portable_data_hash_changed?
168 self.portable_data_hash = computed_pdh
169 elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
170 errors.add(:portable_data_hash, "is not a valid locator")
172 elsif portable_data_hash[0..31] != computed_pdh[0..31]
173 errors.add(:portable_data_hash,
174 "'#{portable_data_hash}' does not match computed hash '#{computed_pdh}'")
177 # Ignore the client-provided size part: always store
178 # computed_pdh in the database.
179 self.portable_data_hash = computed_pdh
184 if self.manifest_text_changed?
185 self.file_names = manifest_files
192 if self.manifest_text
193 self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
194 names << name.first.gsub('\040',' ') + "\n"
195 break if names.length > 2**12
199 if self.manifest_text and names.length < 2**12
200 self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
201 names << stream_name.first.gsub('\040',' ') + "\n"
202 break if names.length > 2**12
209 def default_empty_manifest
210 self.manifest_text ||= ''
214 if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
218 # If Ruby thinks the encoding is something else, like 7-bit
219 # ASCII, but its stored bytes are equal to the (valid) UTF-8
220 # encoding of the same string, we declare it to be a UTF-8
223 utf8.force_encoding Encoding::UTF_8
224 if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
225 self.manifest_text = utf8
230 errors.add :manifest_text, "must use UTF-8 encoding"
235 def check_manifest_validity
237 Keep::Manifest.validate! manifest_text
239 rescue ArgumentError => e
240 errors.add :manifest_text, e.message
245 def signed_manifest_text
246 if !has_attribute? :manifest_text
251 token = current_api_client_authorization.andand.api_token
252 exp = [db_current_time.to_i + Rails.configuration.blob_signature_ttl,
253 trash_at].compact.map(&:to_i).min
254 self.class.sign_manifest manifest_text, token, exp
258 def self.sign_manifest manifest, token, exp=nil
260 exp = db_current_time.to_i + Rails.configuration.blob_signature_ttl
266 m = munge_manifest_locators(manifest) do |match|
267 Blob.sign_locator(match[0], signing_opts)
272 def self.munge_manifest_locators manifest
273 # Given a manifest text and a block, yield the regexp MatchData
274 # for each locator. Return a new manifest in which each locator
275 # has been replaced by the block's return value.
276 return nil if !manifest
277 return '' if manifest == ''
280 manifest.each_line do |line|
283 line.split(' ').each do |word|
286 elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
287 new_words << yield(match)
292 new_lines << new_words.join(' ')
294 new_lines.join("\n") + "\n"
297 def self.each_manifest_locator manifest
298 # Given a manifest text and a block, yield the regexp match object
300 manifest.each_line do |line|
301 # line will have a trailing newline, but the last token is never
302 # a locator, so it's harmless here.
303 line.split(' ').each do |word|
304 if match = Keep::Locator::LOCATOR_REGEXP.match(word)
311 def self.normalize_uuid uuid
314 uuid.split('+').each do |token|
315 if token.match(/^[0-9a-f]{32,}$/)
316 raise "uuid #{uuid} has multiple hash parts" if hash_part
318 elsif token.match(/^\d+$/)
319 raise "uuid #{uuid} has multiple size parts" if size_part
323 raise "uuid #{uuid} has no hash part" if !hash_part
324 [hash_part, size_part].compact.join '+'
327 def self.get_compatible_images(readers, pattern, collections)
328 if collections.empty?
333 Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
334 collections.map(&:portable_data_hash),
335 'docker_image_migration',
337 order('links.created_at asc').
339 [l.tail_uuid, l.head_uuid]
342 migrated_collections = Hash[
343 Collection.readable_by(*readers).
344 where('portable_data_hash in (?)', migrations.values).
346 [c.portable_data_hash, c]
349 collections.map { |c|
350 # Check if the listed image is compatible first, if not, then try the
352 manifest = Keep::Manifest.new(c.manifest_text)
353 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
355 elsif m = migrated_collections[migrations[c.portable_data_hash]]
356 manifest = Keep::Manifest.new(m.manifest_text)
357 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
364 # Resolve a Docker repo+tag, hash, or collection PDH to an array of
365 # Collection objects, sorted by timestamp starting with the most recent
368 # If filter_compatible_format is true (the default), only return image
369 # collections which are support by the installation as indicated by
370 # Rails.configuration.docker_image_formats. Will follow
371 # 'docker_image_migration' links if search_term resolves to an incompatible
372 # image, but an equivalent compatible image is available.
373 def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
374 readers ||= [Thread.current[:user]]
376 readable_by(*readers).
377 readable_by(*readers, table_name: "collections").
378 joins("JOIN collections ON links.head_uuid = collections.uuid").
379 order("links.created_at DESC")
381 if (Rails.configuration.docker_image_formats.include? 'v1' and
382 Rails.configuration.docker_image_formats.include? 'v2') or filter_compatible_format == false
383 pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
384 elsif Rails.configuration.docker_image_formats.include? 'v2'
385 pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
386 elsif Rails.configuration.docker_image_formats.include? 'v1'
387 pattern = /^[0-9A-Fa-f]{64}\.tar$/
389 raise "Unrecognized configuration for docker_image_formats #{Rails.configuration.docker_image_formats}"
392 # If the search term is a Collection locator that contains one file
393 # that looks like a Docker image, return it.
394 if loc = Keep::Locator.parse(search_term)
396 coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
397 return get_compatible_images(readers, pattern, coll_match)
400 if search_tag.nil? and (n = search_term.index(":"))
401 search_tag = search_term[n+1..-1]
402 search_term = search_term[0..n-1]
405 # Find Collections with matching Docker image repository+tag pairs.
406 matches = base_search.
407 where(link_class: "docker_image_repo+tag",
408 name: "#{search_term}:#{search_tag || 'latest'}")
410 # If that didn't work, find Collections with matching Docker image hashes.
412 matches = base_search.
413 where("link_class = ? and links.name LIKE ?",
414 "docker_image_hash", "#{search_term}%")
417 # Generate an order key for each result. We want to order the results
418 # so that anything with an image timestamp is considered more recent than
419 # anything without; then we use the link's created_at as a tiebreaker.
421 matches.each do |link|
422 uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
423 -link.created_at.to_i]
426 sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
427 uuid_timestamps[c.uuid]
429 compatible = get_compatible_images(readers, pattern, sorted)
430 if sorted.length > 0 and compatible.empty?
431 raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
436 def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
437 find_all_for_docker_image(search_term, search_tag, readers).first
440 def self.searchable_columns operator
441 super - ["manifest_text"]
444 def self.full_text_searchable_columns
445 super - ["manifest_text"]
449 SweepTrashedCollections.sweep_if_stale
454 def portable_manifest_text
455 self.class.munge_manifest_locators(manifest_text) do |match|
465 portable_manifest = portable_manifest_text
466 (Digest::MD5.hexdigest(portable_manifest) +
468 portable_manifest.bytesize.to_s)
472 if @computed_pdh_for_manifest_text == manifest_text
475 @computed_pdh = compute_pdh
476 @computed_pdh_for_manifest_text = manifest_text.dup
480 def ensure_permission_to_save
481 if (not current_user.andand.is_admin and
482 (replication_confirmed_at_changed? or replication_confirmed_changed?) and
483 not (replication_confirmed_at.nil? and replication_confirmed.nil?))
484 raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
489 # Use a single timestamp for all validations, even though each
490 # validation runs at a different time.
491 def set_validation_timestamp
492 @validation_timestamp = db_current_time
495 # If trash_at is being changed to a time in the past, change it to
496 # now. This allows clients to say "expires {client-current-time}"
497 # without failing due to clock skew, while avoiding odd log entries
498 # like "expiry date changed to {1 year ago}".
499 def ensure_trash_at_not_in_past
500 if trash_at_changed? && trash_at
501 self.trash_at = [@validation_timestamp, trash_at].max
505 # Caller can move into/out of trash by setting/clearing is_trashed
506 # -- however, if the caller also changes trash_at, then any changes
507 # to is_trashed are ignored.
509 if is_trashed_changed? && !trash_at_changed?
511 self.trash_at = @validation_timestamp
517 self.is_trashed = trash_at && trash_at <= @validation_timestamp || false
521 def default_trash_interval
522 if trash_at_changed? && !delete_at_changed?
523 # If trash_at is updated without touching delete_at,
524 # automatically update delete_at to a sensible value.
528 self.delete_at = trash_at + Rails.configuration.default_trash_lifetime.seconds
530 elsif !trash_at || !delete_at || trash_at > delete_at
531 # Not trash, or bogus arguments? Just validate in
532 # validate_trash_and_delete_timing.
533 elsif delete_at_changed? && delete_at >= trash_at
534 # Fix delete_at if needed, so it's not earlier than the expiry
535 # time on any permission tokens that might have been given out.
537 # In any case there are no signatures expiring after now+TTL.
538 # Also, if the existing trash_at time has already passed, we
539 # know we haven't given out any signatures since then.
541 @validation_timestamp,
543 ].compact.min + Rails.configuration.blob_signature_ttl.seconds
545 # The previous value of delete_at is also an upper bound on the
546 # longest-lived permission token. For example, if TTL=14,
547 # trash_at_was=now-7, delete_at_was=now+7, then it is safe to
548 # set trash_at=now+6, delete_at=now+8.
549 earliest_delete = [earliest_delete, delete_at_was].compact.min
551 # If delete_at is too soon, use the earliest possible time.
552 if delete_at < earliest_delete
553 self.delete_at = earliest_delete
558 def validate_trash_and_delete_timing
559 if trash_at.nil? != delete_at.nil?
560 errors.add :delete_at, "must be set if trash_at is set, and must be nil otherwise"
561 elsif delete_at && delete_at < trash_at
562 errors.add :delete_at, "must not be earlier than trash_at"