2 require 'sweep_trashed_collections'
4 class Collection < ArvadosModel
8 include CommonApiTemplate
10 serialize :properties, Hash
12 before_validation :set_validation_timestamp
13 before_validation :default_empty_manifest
14 before_validation :check_encoding
15 before_validation :check_manifest_validity
16 before_validation :check_signatures
17 before_validation :strip_signatures_and_update_replication_confirmed
18 before_validation :ensure_trash_at_not_in_past
19 before_validation :sync_trash_state
20 before_validation :default_trash_interval
21 validate :ensure_pdh_matches_manifest_text
22 validate :validate_trash_and_delete_timing
23 before_save :set_file_names
25 # Query only untrashed collections by default.
26 default_scope where("is_trashed = false")
28 api_accessible :user, extend: :common do |t|
32 t.add :portable_data_hash
33 t.add :signed_manifest_text, as: :manifest_text
34 t.add :manifest_text, as: :unsigned_manifest_text
35 t.add :replication_desired
36 t.add :replication_confirmed
37 t.add :replication_confirmed_at
44 @signatures_checked = false
45 @computed_pdh_for_manifest_text = false
48 def self.attributes_required_columns
50 # If we don't list manifest_text explicitly, the
51 # params[:select] code gets confused by the way we
52 # expose signed_manifest_text as manifest_text in the
53 # API response, and never let clients select the
54 # manifest_text column.
56 # We need trash_at and is_trashed to determine the
57 # correct timestamp in signed_manifest_text.
58 'manifest_text' => ['manifest_text', 'trash_at', 'is_trashed'],
59 'unsigned_manifest_text' => ['manifest_text'],
63 def self.ignored_select_attributes
64 super + ["updated_at", "file_names"]
67 FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
69 return false if self.manifest_text.nil?
71 return true if current_user.andand.is_admin
73 # Provided the manifest_text hasn't changed materially since an
74 # earlier validation, it's safe to pass this validation on
75 # subsequent passes without checking any signatures. This is
76 # important because the signatures have probably been stripped off
77 # by the time we get to a second validation pass!
78 if @signatures_checked && @signatures_checked == computed_pdh
82 if self.manifest_text_changed?
83 # Check permissions on the collection manifest.
84 # If any signature cannot be verified, raise PermissionDeniedError
85 # which will return 403 Permission denied to the client.
86 api_token = current_api_client_authorization.andand.api_token
89 now: @validation_timestamp.to_i,
91 self.manifest_text.each_line do |entry|
92 entry.split.each do |tok|
93 if tok == '.' or tok.starts_with? './'
95 elsif tok =~ FILE_TOKEN
96 # This is a filename token, not a blob locator. Note that we
97 # keep checking tokens after this, even though manifest
98 # format dictates that all subsequent tokens will also be
99 # filenames. Safety first!
100 elsif Blob.verify_signature tok, signing_opts
102 elsif Keep::Locator.parse(tok).andand.signature
103 # Signature provided, but verify_signature did not like it.
104 logger.warn "Invalid signature on locator #{tok}"
105 raise ArvadosModel::PermissionDeniedError
106 elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
107 # No signature provided, but we are running in insecure mode.
108 logger.debug "Missing signature on locator #{tok} ignored"
109 elsif Blob.new(tok).empty?
110 # No signature provided -- but no data to protect, either.
112 logger.warn "Missing signature on locator #{tok}"
113 raise ArvadosModel::PermissionDeniedError
118 @signatures_checked = computed_pdh
121 def strip_signatures_and_update_replication_confirmed
122 if self.manifest_text_changed?
124 if not self.replication_confirmed.nil?
125 self.class.each_manifest_locator(manifest_text_was) do |match|
126 in_old_manifest[match[1]] = true
130 stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
131 if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
132 # If the new manifest_text contains locators whose hashes
133 # weren't in the old manifest_text, storage replication is no
135 self.replication_confirmed_at = nil
136 self.replication_confirmed = nil
139 # Return the locator with all permission signatures removed,
140 # but otherwise intact.
141 match[0].gsub(/\+A[^+]*/, '')
144 if @computed_pdh_for_manifest_text == manifest_text
145 # If the cached PDH was valid before stripping, it is still
146 # valid after stripping.
147 @computed_pdh_for_manifest_text = stripped_manifest.dup
150 self[:manifest_text] = stripped_manifest
155 def ensure_pdh_matches_manifest_text
156 if not manifest_text_changed? and not portable_data_hash_changed?
158 elsif portable_data_hash.nil? or not portable_data_hash_changed?
159 self.portable_data_hash = computed_pdh
160 elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
161 errors.add(:portable_data_hash, "is not a valid locator")
163 elsif portable_data_hash[0..31] != computed_pdh[0..31]
164 errors.add(:portable_data_hash,
165 "does not match computed hash #{computed_pdh}")
168 # Ignore the client-provided size part: always store
169 # computed_pdh in the database.
170 self.portable_data_hash = computed_pdh
175 if self.manifest_text_changed?
176 self.file_names = manifest_files
183 if self.manifest_text
184 self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
185 names << name.first.gsub('\040',' ') + "\n"
186 break if names.length > 2**12
190 if self.manifest_text and names.length < 2**12
191 self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
192 names << stream_name.first.gsub('\040',' ') + "\n"
193 break if names.length > 2**12
200 def default_empty_manifest
201 self.manifest_text ||= ''
205 if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
209 # If Ruby thinks the encoding is something else, like 7-bit
210 # ASCII, but its stored bytes are equal to the (valid) UTF-8
211 # encoding of the same string, we declare it to be a UTF-8
214 utf8.force_encoding Encoding::UTF_8
215 if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
216 self.manifest_text = utf8
221 errors.add :manifest_text, "must use UTF-8 encoding"
226 def check_manifest_validity
228 Keep::Manifest.validate! manifest_text
230 rescue ArgumentError => e
231 errors.add :manifest_text, e.message
236 def signed_manifest_text
237 if !has_attribute? :manifest_text
242 token = current_api_client_authorization.andand.api_token
243 exp = [db_current_time.to_i + Rails.configuration.blob_signature_ttl,
244 trash_at].compact.map(&:to_i).min
245 self.class.sign_manifest manifest_text, token, exp
249 def self.sign_manifest manifest, token, exp=nil
251 exp = db_current_time.to_i + Rails.configuration.blob_signature_ttl
257 m = munge_manifest_locators(manifest) do |match|
258 Blob.sign_locator(match[0], signing_opts)
263 def self.munge_manifest_locators manifest
264 # Given a manifest text and a block, yield the regexp MatchData
265 # for each locator. Return a new manifest in which each locator
266 # has been replaced by the block's return value.
267 return nil if !manifest
268 return '' if manifest == ''
271 manifest.each_line do |line|
274 line.split(' ').each do |word|
277 elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
278 new_words << yield(match)
283 new_lines << new_words.join(' ')
285 new_lines.join("\n") + "\n"
288 def self.each_manifest_locator manifest
289 # Given a manifest text and a block, yield the regexp match object
291 manifest.each_line do |line|
292 # line will have a trailing newline, but the last token is never
293 # a locator, so it's harmless here.
294 line.split(' ').each do |word|
295 if match = Keep::Locator::LOCATOR_REGEXP.match(word)
302 def self.normalize_uuid uuid
305 uuid.split('+').each do |token|
306 if token.match(/^[0-9a-f]{32,}$/)
307 raise "uuid #{uuid} has multiple hash parts" if hash_part
309 elsif token.match(/^\d+$/)
310 raise "uuid #{uuid} has multiple size parts" if size_part
314 raise "uuid #{uuid} has no hash part" if !hash_part
315 [hash_part, size_part].compact.join '+'
318 # Return array of Collection objects
319 def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil)
320 readers ||= [Thread.current[:user]]
322 readable_by(*readers).
323 readable_by(*readers, table_name: "collections").
324 joins("JOIN collections ON links.head_uuid = collections.uuid").
325 order("links.created_at DESC")
327 # If the search term is a Collection locator that contains one file
328 # that looks like a Docker image, return it.
329 if loc = Keep::Locator.parse(search_term)
331 coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1).first
333 # Check if the Collection contains exactly one file whose name
334 # looks like a saved Docker image.
335 manifest = Keep::Manifest.new(coll_match.manifest_text)
336 if manifest.exact_file_count?(1) and
337 (manifest.files[0][1] =~ /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/)
343 if search_tag.nil? and (n = search_term.index(":"))
344 search_tag = search_term[n+1..-1]
345 search_term = search_term[0..n-1]
348 # Find Collections with matching Docker image repository+tag pairs.
349 matches = base_search.
350 where(link_class: "docker_image_repo+tag",
351 name: "#{search_term}:#{search_tag || 'latest'}")
353 # If that didn't work, find Collections with matching Docker image hashes.
355 matches = base_search.
356 where("link_class = ? and links.name LIKE ?",
357 "docker_image_hash", "#{search_term}%")
360 # Generate an order key for each result. We want to order the results
361 # so that anything with an image timestamp is considered more recent than
362 # anything without; then we use the link's created_at as a tiebreaker.
364 matches.all.map do |link|
365 uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
366 -link.created_at.to_i]
368 Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c| uuid_timestamps[c.uuid] }
371 def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
372 find_all_for_docker_image(search_term, search_tag, readers).first
375 def self.searchable_columns operator
376 super - ["manifest_text"]
379 def self.full_text_searchable_columns
380 super - ["manifest_text"]
384 SweepTrashedCollections.sweep_if_stale
389 def portable_manifest_text
390 self.class.munge_manifest_locators(manifest_text) do |match|
400 portable_manifest = portable_manifest_text
401 (Digest::MD5.hexdigest(portable_manifest) +
403 portable_manifest.bytesize.to_s)
407 if @computed_pdh_for_manifest_text == manifest_text
410 @computed_pdh = compute_pdh
411 @computed_pdh_for_manifest_text = manifest_text.dup
415 def ensure_permission_to_save
416 if (not current_user.andand.is_admin and
417 (replication_confirmed_at_changed? or replication_confirmed_changed?) and
418 not (replication_confirmed_at.nil? and replication_confirmed.nil?))
419 raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
424 # Use a single timestamp for all validations, even though each
425 # validation runs at a different time.
426 def set_validation_timestamp
427 @validation_timestamp = db_current_time
430 # If trash_at is being changed to a time in the past, change it to
431 # now. This allows clients to say "expires {client-current-time}"
432 # without failing due to clock skew, while avoiding odd log entries
433 # like "expiry date changed to {1 year ago}".
434 def ensure_trash_at_not_in_past
435 if trash_at_changed? && trash_at
436 self.trash_at = [@validation_timestamp, trash_at].max
440 # Caller can move into/out of trash by setting/clearing is_trashed
441 # -- however, if the caller also changes trash_at, then any changes
442 # to is_trashed are ignored.
444 if is_trashed_changed? && !trash_at_changed?
446 self.trash_at = @validation_timestamp
452 self.is_trashed = trash_at && trash_at <= @validation_timestamp || false
456 # If trash_at is updated without touching delete_at, automatically
457 # update delete_at to a sensible value.
458 def default_trash_interval
459 if trash_at_changed? && !delete_at_changed?
463 self.delete_at = trash_at + Rails.configuration.default_trash_lifetime.seconds
468 def validate_trash_and_delete_timing
469 if trash_at.nil? != delete_at.nil?
470 errors.add :delete_at, "must be set if trash_at is set, and must be nil otherwise"
473 earliest_delete = ([@validation_timestamp, trash_at_was].compact.min +
474 Rails.configuration.blob_signature_ttl.seconds)
475 if delete_at && delete_at < earliest_delete
476 errors.add :delete_at, "#{delete_at} is too soon: earliest allowed is #{earliest_delete}"
479 if delete_at && delete_at < trash_at
480 errors.add :delete_at, "must not be earlier than trash_at"