2 require 'sweep_trashed_collections'
4 class Collection < ArvadosModel
5 extend CurrentApiClient
9 include CommonApiTemplate
11 serialize :properties, Hash
13 before_validation :set_validation_timestamp
14 before_validation :default_empty_manifest
15 before_validation :check_encoding
16 before_validation :check_manifest_validity
17 before_validation :check_signatures
18 before_validation :strip_signatures_and_update_replication_confirmed
19 before_validation :ensure_trash_at_not_in_past
20 before_validation :sync_trash_state
21 before_validation :default_trash_interval
22 validate :ensure_pdh_matches_manifest_text
23 validate :validate_trash_and_delete_timing
24 before_save :set_file_names
26 # Query only untrashed collections by default.
27 default_scope where("is_trashed = false")
29 api_accessible :user, extend: :common do |t|
33 t.add :portable_data_hash
34 t.add :signed_manifest_text, as: :manifest_text
35 t.add :manifest_text, as: :unsigned_manifest_text
36 t.add :replication_desired
37 t.add :replication_confirmed
38 t.add :replication_confirmed_at
45 @signatures_checked = false
46 @computed_pdh_for_manifest_text = false
49 def self.attributes_required_columns
51 # If we don't list manifest_text explicitly, the
52 # params[:select] code gets confused by the way we
53 # expose signed_manifest_text as manifest_text in the
54 # API response, and never let clients select the
55 # manifest_text column.
57 # We need trash_at and is_trashed to determine the
58 # correct timestamp in signed_manifest_text.
59 'manifest_text' => ['manifest_text', 'trash_at', 'is_trashed'],
60 'unsigned_manifest_text' => ['manifest_text'],
64 def self.ignored_select_attributes
65 super + ["updated_at", "file_names"]
68 FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
70 return false if self.manifest_text.nil?
72 return true if current_user.andand.is_admin
74 # Provided the manifest_text hasn't changed materially since an
75 # earlier validation, it's safe to pass this validation on
76 # subsequent passes without checking any signatures. This is
77 # important because the signatures have probably been stripped off
78 # by the time we get to a second validation pass!
79 if @signatures_checked && @signatures_checked == computed_pdh
83 if self.manifest_text_changed?
84 # Check permissions on the collection manifest.
85 # If any signature cannot be verified, raise PermissionDeniedError
86 # which will return 403 Permission denied to the client.
87 api_token = current_api_client_authorization.andand.api_token
90 now: @validation_timestamp.to_i,
92 self.manifest_text.each_line do |entry|
93 entry.split.each do |tok|
94 if tok == '.' or tok.starts_with? './'
96 elsif tok =~ FILE_TOKEN
97 # This is a filename token, not a blob locator. Note that we
98 # keep checking tokens after this, even though manifest
99 # format dictates that all subsequent tokens will also be
100 # filenames. Safety first!
101 elsif Blob.verify_signature tok, signing_opts
103 elsif Keep::Locator.parse(tok).andand.signature
104 # Signature provided, but verify_signature did not like it.
105 logger.warn "Invalid signature on locator #{tok}"
106 raise ArvadosModel::PermissionDeniedError
107 elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
108 # No signature provided, but we are running in insecure mode.
109 logger.debug "Missing signature on locator #{tok} ignored"
110 elsif Blob.new(tok).empty?
111 # No signature provided -- but no data to protect, either.
113 logger.warn "Missing signature on locator #{tok}"
114 raise ArvadosModel::PermissionDeniedError
119 @signatures_checked = computed_pdh
122 def strip_signatures_and_update_replication_confirmed
123 if self.manifest_text_changed?
125 if not self.replication_confirmed.nil?
126 self.class.each_manifest_locator(manifest_text_was) do |match|
127 in_old_manifest[match[1]] = true
131 stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
132 if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
133 # If the new manifest_text contains locators whose hashes
134 # weren't in the old manifest_text, storage replication is no
136 self.replication_confirmed_at = nil
137 self.replication_confirmed = nil
140 # Return the locator with all permission signatures removed,
141 # but otherwise intact.
142 match[0].gsub(/\+A[^+]*/, '')
145 if @computed_pdh_for_manifest_text == manifest_text
146 # If the cached PDH was valid before stripping, it is still
147 # valid after stripping.
148 @computed_pdh_for_manifest_text = stripped_manifest.dup
151 self[:manifest_text] = stripped_manifest
156 def ensure_pdh_matches_manifest_text
157 if not manifest_text_changed? and not portable_data_hash_changed?
159 elsif portable_data_hash.nil? or not portable_data_hash_changed?
160 self.portable_data_hash = computed_pdh
161 elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
162 errors.add(:portable_data_hash, "is not a valid locator")
164 elsif portable_data_hash[0..31] != computed_pdh[0..31]
165 errors.add(:portable_data_hash,
166 "does not match computed hash #{computed_pdh}")
169 # Ignore the client-provided size part: always store
170 # computed_pdh in the database.
171 self.portable_data_hash = computed_pdh
176 if self.manifest_text_changed?
177 self.file_names = manifest_files
184 if self.manifest_text
185 self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
186 names << name.first.gsub('\040',' ') + "\n"
187 break if names.length > 2**12
191 if self.manifest_text and names.length < 2**12
192 self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
193 names << stream_name.first.gsub('\040',' ') + "\n"
194 break if names.length > 2**12
201 def default_empty_manifest
202 self.manifest_text ||= ''
206 if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
210 # If Ruby thinks the encoding is something else, like 7-bit
211 # ASCII, but its stored bytes are equal to the (valid) UTF-8
212 # encoding of the same string, we declare it to be a UTF-8
215 utf8.force_encoding Encoding::UTF_8
216 if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
217 self.manifest_text = utf8
222 errors.add :manifest_text, "must use UTF-8 encoding"
227 def check_manifest_validity
229 Keep::Manifest.validate! manifest_text
231 rescue ArgumentError => e
232 errors.add :manifest_text, e.message
237 def signed_manifest_text
238 if !has_attribute? :manifest_text
243 token = current_api_client_authorization.andand.api_token
244 exp = [db_current_time.to_i + Rails.configuration.blob_signature_ttl,
245 trash_at].compact.map(&:to_i).min
246 self.class.sign_manifest manifest_text, token, exp
250 def self.sign_manifest manifest, token, exp=nil
252 exp = db_current_time.to_i + Rails.configuration.blob_signature_ttl
258 m = munge_manifest_locators(manifest) do |match|
259 Blob.sign_locator(match[0], signing_opts)
264 def self.munge_manifest_locators manifest
265 # Given a manifest text and a block, yield the regexp MatchData
266 # for each locator. Return a new manifest in which each locator
267 # has been replaced by the block's return value.
268 return nil if !manifest
269 return '' if manifest == ''
272 manifest.each_line do |line|
275 line.split(' ').each do |word|
278 elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
279 new_words << yield(match)
284 new_lines << new_words.join(' ')
286 new_lines.join("\n") + "\n"
289 def self.each_manifest_locator manifest
290 # Given a manifest text and a block, yield the regexp match object
292 manifest.each_line do |line|
293 # line will have a trailing newline, but the last token is never
294 # a locator, so it's harmless here.
295 line.split(' ').each do |word|
296 if match = Keep::Locator::LOCATOR_REGEXP.match(word)
303 def self.normalize_uuid uuid
306 uuid.split('+').each do |token|
307 if token.match(/^[0-9a-f]{32,}$/)
308 raise "uuid #{uuid} has multiple hash parts" if hash_part
310 elsif token.match(/^\d+$/)
311 raise "uuid #{uuid} has multiple size parts" if size_part
315 raise "uuid #{uuid} has no hash part" if !hash_part
316 [hash_part, size_part].compact.join '+'
319 def self.get_compatible_images(readers, pattern, collections)
320 if collections.empty?
325 Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
326 collections.map(&:portable_data_hash),
327 'docker_image_migration',
329 order('links.created_at asc').
331 [l.tail_uuid, l.head_uuid]
334 migrated_collections = Hash[
335 Collection.readable_by(*readers).
336 where('portable_data_hash in (?)', migrations.values).
338 [c.portable_data_hash, c]
341 collections.map { |c|
342 # Check if the listed image is compatible first, if not, then try the
344 manifest = Keep::Manifest.new(c.manifest_text)
345 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
347 elsif m = migrated_collections[migrations[c.portable_data_hash]]
348 manifest = Keep::Manifest.new(m.manifest_text)
349 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
356 # Resolve a Docker repo+tag, hash, or collection PDH to an array of
357 # Collection objects, sorted by timestamp starting with the most recent
360 # If filter_compatible_format is true (the default), only return image
361 # collections which are support by the installation as indicated by
362 # Rails.configuration.docker_image_formats. Will follow
363 # 'docker_image_migration' links if search_term resolves to an incompatible
364 # image, but an equivalent compatible image is available.
365 def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format=true)
366 readers ||= [Thread.current[:user]]
368 readable_by(*readers).
369 readable_by(*readers, table_name: "collections").
370 joins("JOIN collections ON links.head_uuid = collections.uuid").
371 order("links.created_at DESC")
373 if (Rails.configuration.docker_image_formats.include? 'v1' and
374 Rails.configuration.docker_image_formats.include? 'v2') or filter_compatible_format == false
375 pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
376 elsif Rails.configuration.docker_image_formats.include? 'v2'
377 pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
378 elsif Rails.configuration.docker_image_formats.include? 'v1'
379 pattern = /^[0-9A-Fa-f]{64}\.tar$/
381 raise "Unrecognized configuration for docker_image_formats #{Rails.configuration.docker_image_formats}"
384 # If the search term is a Collection locator that contains one file
385 # that looks like a Docker image, return it.
386 if loc = Keep::Locator.parse(search_term)
388 coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
389 if compatible_img = get_compatible_images(readers, pattern, coll_match)
390 return compatible_img
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")
483 # Use a single timestamp for all validations, even though each
484 # validation runs at a different time.
485 def set_validation_timestamp
486 @validation_timestamp = db_current_time
489 # If trash_at is being changed to a time in the past, change it to
490 # now. This allows clients to say "expires {client-current-time}"
491 # without failing due to clock skew, while avoiding odd log entries
492 # like "expiry date changed to {1 year ago}".
493 def ensure_trash_at_not_in_past
494 if trash_at_changed? && trash_at
495 self.trash_at = [@validation_timestamp, trash_at].max
499 # Caller can move into/out of trash by setting/clearing is_trashed
500 # -- however, if the caller also changes trash_at, then any changes
501 # to is_trashed are ignored.
503 if is_trashed_changed? && !trash_at_changed?
505 self.trash_at = @validation_timestamp
511 self.is_trashed = trash_at && trash_at <= @validation_timestamp || false
515 # If trash_at is updated without touching delete_at, automatically
516 # update delete_at to a sensible value.
517 def default_trash_interval
518 if trash_at_changed? && !delete_at_changed?
522 self.delete_at = trash_at + Rails.configuration.default_trash_lifetime.seconds
527 def validate_trash_and_delete_timing
528 if trash_at.nil? != delete_at.nil?
529 errors.add :delete_at, "must be set if trash_at is set, and must be nil otherwise"
532 earliest_delete = ([@validation_timestamp, trash_at_was].compact.min +
533 Rails.configuration.blob_signature_ttl.seconds)
534 if delete_at && delete_at < earliest_delete
535 errors.add :delete_at, "#{delete_at} is too soon: earliest allowed is #{earliest_delete}"
538 if delete_at && delete_at < trash_at
539 errors.add :delete_at, "must not be earlier than trash_at"