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 api_accessible :user, extend: :common do |t|
31 t.add :portable_data_hash
32 t.add :signed_manifest_text, as: :manifest_text
33 t.add :manifest_text, as: :unsigned_manifest_text
34 t.add :replication_desired
35 t.add :replication_confirmed
36 t.add :replication_confirmed_at
43 @signatures_checked = false
44 @computed_pdh_for_manifest_text = false
47 def self.attributes_required_columns
49 # If we don't list manifest_text explicitly, the
50 # params[:select] code gets confused by the way we
51 # expose signed_manifest_text as manifest_text in the
52 # API response, and never let clients select the
53 # manifest_text column.
55 # We need trash_at and is_trashed to determine the
56 # correct timestamp in signed_manifest_text.
57 'manifest_text' => ['manifest_text', 'trash_at', 'is_trashed'],
58 'unsigned_manifest_text' => ['manifest_text'],
62 def self.ignored_select_attributes
63 super + ["updated_at", "file_names"]
66 def self.limit_index_columns_read
70 FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
72 return false if self.manifest_text.nil?
74 return true if current_user.andand.is_admin
76 # Provided the manifest_text hasn't changed materially since an
77 # earlier validation, it's safe to pass this validation on
78 # subsequent passes without checking any signatures. This is
79 # important because the signatures have probably been stripped off
80 # by the time we get to a second validation pass!
81 if @signatures_checked && @signatures_checked == computed_pdh
85 if self.manifest_text_changed?
86 # Check permissions on the collection manifest.
87 # If any signature cannot be verified, raise PermissionDeniedError
88 # which will return 403 Permission denied to the client.
89 api_token = current_api_client_authorization.andand.api_token
92 now: @validation_timestamp.to_i,
94 self.manifest_text.each_line do |entry|
95 entry.split.each do |tok|
96 if tok == '.' or tok.starts_with? './'
98 elsif tok =~ FILE_TOKEN
99 # This is a filename token, not a blob locator. Note that we
100 # keep checking tokens after this, even though manifest
101 # format dictates that all subsequent tokens will also be
102 # filenames. Safety first!
103 elsif Blob.verify_signature tok, signing_opts
105 elsif Keep::Locator.parse(tok).andand.signature
106 # Signature provided, but verify_signature did not like it.
107 logger.warn "Invalid signature on locator #{tok}"
108 raise ArvadosModel::PermissionDeniedError
109 elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
110 # No signature provided, but we are running in insecure mode.
111 logger.debug "Missing signature on locator #{tok} ignored"
112 elsif Blob.new(tok).empty?
113 # No signature provided -- but no data to protect, either.
115 logger.warn "Missing signature on locator #{tok}"
116 raise ArvadosModel::PermissionDeniedError
121 @signatures_checked = computed_pdh
124 def strip_signatures_and_update_replication_confirmed
125 if self.manifest_text_changed?
127 if not self.replication_confirmed.nil?
128 self.class.each_manifest_locator(manifest_text_was) do |match|
129 in_old_manifest[match[1]] = true
133 stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
134 if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
135 # If the new manifest_text contains locators whose hashes
136 # weren't in the old manifest_text, storage replication is no
138 self.replication_confirmed_at = nil
139 self.replication_confirmed = nil
142 # Return the locator with all permission signatures removed,
143 # but otherwise intact.
144 match[0].gsub(/\+A[^+]*/, '')
147 if @computed_pdh_for_manifest_text == manifest_text
148 # If the cached PDH was valid before stripping, it is still
149 # valid after stripping.
150 @computed_pdh_for_manifest_text = stripped_manifest.dup
153 self[:manifest_text] = stripped_manifest
158 def ensure_pdh_matches_manifest_text
159 if not manifest_text_changed? and not portable_data_hash_changed?
161 elsif portable_data_hash.nil? or not portable_data_hash_changed?
162 self.portable_data_hash = computed_pdh
163 elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
164 errors.add(:portable_data_hash, "is not a valid locator")
166 elsif portable_data_hash[0..31] != computed_pdh[0..31]
167 errors.add(:portable_data_hash,
168 "'#{portable_data_hash}' does not match computed hash '#{computed_pdh}'")
171 # Ignore the client-provided size part: always store
172 # computed_pdh in the database.
173 self.portable_data_hash = computed_pdh
178 if self.manifest_text_changed?
179 self.file_names = manifest_files
186 if self.manifest_text
187 self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
188 names << name.first.gsub('\040',' ') + "\n"
189 break if names.length > 2**12
193 if self.manifest_text and names.length < 2**12
194 self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
195 names << stream_name.first.gsub('\040',' ') + "\n"
196 break if names.length > 2**12
203 def default_empty_manifest
204 self.manifest_text ||= ''
208 if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
212 # If Ruby thinks the encoding is something else, like 7-bit
213 # ASCII, but its stored bytes are equal to the (valid) UTF-8
214 # encoding of the same string, we declare it to be a UTF-8
217 utf8.force_encoding Encoding::UTF_8
218 if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
219 self.manifest_text = utf8
224 errors.add :manifest_text, "must use UTF-8 encoding"
229 def check_manifest_validity
231 Keep::Manifest.validate! manifest_text
233 rescue ArgumentError => e
234 errors.add :manifest_text, e.message
239 def signed_manifest_text
240 if !has_attribute? :manifest_text
245 token = current_api_client_authorization.andand.api_token
246 exp = [db_current_time.to_i + Rails.configuration.blob_signature_ttl,
247 trash_at].compact.map(&:to_i).min
248 self.class.sign_manifest manifest_text, token, exp
252 def self.sign_manifest manifest, token, exp=nil
254 exp = db_current_time.to_i + Rails.configuration.blob_signature_ttl
260 m = munge_manifest_locators(manifest) do |match|
261 Blob.sign_locator(match[0], signing_opts)
266 def self.munge_manifest_locators manifest
267 # Given a manifest text and a block, yield the regexp MatchData
268 # for each locator. Return a new manifest in which each locator
269 # has been replaced by the block's return value.
270 return nil if !manifest
271 return '' if manifest == ''
274 manifest.each_line do |line|
277 line.split(' ').each do |word|
280 elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
281 new_words << yield(match)
286 new_lines << new_words.join(' ')
288 new_lines.join("\n") + "\n"
291 def self.each_manifest_locator manifest
292 # Given a manifest text and a block, yield the regexp match object
294 manifest.each_line do |line|
295 # line will have a trailing newline, but the last token is never
296 # a locator, so it's harmless here.
297 line.split(' ').each do |word|
298 if match = Keep::Locator::LOCATOR_REGEXP.match(word)
305 def self.normalize_uuid uuid
308 uuid.split('+').each do |token|
309 if token.match(/^[0-9a-f]{32,}$/)
310 raise "uuid #{uuid} has multiple hash parts" if hash_part
312 elsif token.match(/^\d+$/)
313 raise "uuid #{uuid} has multiple size parts" if size_part
317 raise "uuid #{uuid} has no hash part" if !hash_part
318 [hash_part, size_part].compact.join '+'
321 def self.get_compatible_images(readers, pattern, collections)
322 if collections.empty?
327 Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
328 collections.map(&:portable_data_hash),
329 'docker_image_migration',
331 order('links.created_at asc').
333 [l.tail_uuid, l.head_uuid]
336 migrated_collections = Hash[
337 Collection.readable_by(*readers).
338 where('portable_data_hash in (?)', migrations.values).
340 [c.portable_data_hash, c]
343 collections.map { |c|
344 # Check if the listed image is compatible first, if not, then try the
346 manifest = Keep::Manifest.new(c.manifest_text)
347 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
349 elsif m = migrated_collections[migrations[c.portable_data_hash]]
350 manifest = Keep::Manifest.new(m.manifest_text)
351 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
358 # Resolve a Docker repo+tag, hash, or collection PDH to an array of
359 # Collection objects, sorted by timestamp starting with the most recent
362 # If filter_compatible_format is true (the default), only return image
363 # collections which are support by the installation as indicated by
364 # Rails.configuration.docker_image_formats. Will follow
365 # 'docker_image_migration' links if search_term resolves to an incompatible
366 # image, but an equivalent compatible image is available.
367 def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
368 readers ||= [Thread.current[:user]]
370 readable_by(*readers).
371 readable_by(*readers, table_name: "collections").
372 joins("JOIN collections ON links.head_uuid = collections.uuid").
373 order("links.created_at DESC")
375 if (Rails.configuration.docker_image_formats.include? 'v1' and
376 Rails.configuration.docker_image_formats.include? 'v2') or filter_compatible_format == false
377 pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
378 elsif Rails.configuration.docker_image_formats.include? 'v2'
379 pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
380 elsif Rails.configuration.docker_image_formats.include? 'v1'
381 pattern = /^[0-9A-Fa-f]{64}\.tar$/
383 raise "Unrecognized configuration for docker_image_formats #{Rails.configuration.docker_image_formats}"
386 # If the search term is a Collection locator that contains one file
387 # that looks like a Docker image, return it.
388 if loc = Keep::Locator.parse(search_term)
390 coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
391 return get_compatible_images(readers, pattern, coll_match)
394 if search_tag.nil? and (n = search_term.index(":"))
395 search_tag = search_term[n+1..-1]
396 search_term = search_term[0..n-1]
399 # Find Collections with matching Docker image repository+tag pairs.
400 matches = base_search.
401 where(link_class: "docker_image_repo+tag",
402 name: "#{search_term}:#{search_tag || 'latest'}")
404 # If that didn't work, find Collections with matching Docker image hashes.
406 matches = base_search.
407 where("link_class = ? and links.name LIKE ?",
408 "docker_image_hash", "#{search_term}%")
411 # Generate an order key for each result. We want to order the results
412 # so that anything with an image timestamp is considered more recent than
413 # anything without; then we use the link's created_at as a tiebreaker.
415 matches.each do |link|
416 uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
417 -link.created_at.to_i]
420 sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
421 uuid_timestamps[c.uuid]
423 compatible = get_compatible_images(readers, pattern, sorted)
424 if sorted.length > 0 and compatible.empty?
425 raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
430 def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
431 find_all_for_docker_image(search_term, search_tag, readers).first
434 def self.searchable_columns operator
435 super - ["manifest_text"]
438 def self.full_text_searchable_columns
439 super - ["manifest_text"]
443 SweepTrashedCollections.sweep_if_stale
448 def portable_manifest_text
449 self.class.munge_manifest_locators(manifest_text) do |match|
459 portable_manifest = portable_manifest_text
460 (Digest::MD5.hexdigest(portable_manifest) +
462 portable_manifest.bytesize.to_s)
466 if @computed_pdh_for_manifest_text == manifest_text
469 @computed_pdh = compute_pdh
470 @computed_pdh_for_manifest_text = manifest_text.dup
474 def ensure_permission_to_save
475 if (not current_user.andand.is_admin and
476 (replication_confirmed_at_changed? or replication_confirmed_changed?) and
477 not (replication_confirmed_at.nil? and replication_confirmed.nil?))
478 raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")