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 :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'],
61 def self.ignored_select_attributes
62 super + ["updated_at", "file_names"]
65 FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
67 return false if self.manifest_text.nil?
69 return true if current_user.andand.is_admin
71 # Provided the manifest_text hasn't changed materially since an
72 # earlier validation, it's safe to pass this validation on
73 # subsequent passes without checking any signatures. This is
74 # important because the signatures have probably been stripped off
75 # by the time we get to a second validation pass!
76 if @signatures_checked && @signatures_checked == computed_pdh
80 if self.manifest_text_changed?
81 # Check permissions on the collection manifest.
82 # If any signature cannot be verified, raise PermissionDeniedError
83 # which will return 403 Permission denied to the client.
84 api_token = current_api_client_authorization.andand.api_token
87 now: @validation_timestamp.to_i,
89 self.manifest_text.each_line do |entry|
90 entry.split.each do |tok|
91 if tok == '.' or tok.starts_with? './'
93 elsif tok =~ FILE_TOKEN
94 # This is a filename token, not a blob locator. Note that we
95 # keep checking tokens after this, even though manifest
96 # format dictates that all subsequent tokens will also be
97 # filenames. Safety first!
98 elsif Blob.verify_signature tok, signing_opts
100 elsif Keep::Locator.parse(tok).andand.signature
101 # Signature provided, but verify_signature did not like it.
102 logger.warn "Invalid signature on locator #{tok}"
103 raise ArvadosModel::PermissionDeniedError
104 elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
105 # No signature provided, but we are running in insecure mode.
106 logger.debug "Missing signature on locator #{tok} ignored"
107 elsif Blob.new(tok).empty?
108 # No signature provided -- but no data to protect, either.
110 logger.warn "Missing signature on locator #{tok}"
111 raise ArvadosModel::PermissionDeniedError
116 @signatures_checked = computed_pdh
119 def strip_signatures_and_update_replication_confirmed
120 if self.manifest_text_changed?
122 if not self.replication_confirmed.nil?
123 self.class.each_manifest_locator(manifest_text_was) do |match|
124 in_old_manifest[match[1]] = true
128 stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
129 if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
130 # If the new manifest_text contains locators whose hashes
131 # weren't in the old manifest_text, storage replication is no
133 self.replication_confirmed_at = nil
134 self.replication_confirmed = nil
137 # Return the locator with all permission signatures removed,
138 # but otherwise intact.
139 match[0].gsub(/\+A[^+]*/, '')
142 if @computed_pdh_for_manifest_text == manifest_text
143 # If the cached PDH was valid before stripping, it is still
144 # valid after stripping.
145 @computed_pdh_for_manifest_text = stripped_manifest.dup
148 self[:manifest_text] = stripped_manifest
153 def ensure_pdh_matches_manifest_text
154 if not manifest_text_changed? and not portable_data_hash_changed?
156 elsif portable_data_hash.nil? or not portable_data_hash_changed?
157 self.portable_data_hash = computed_pdh
158 elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
159 errors.add(:portable_data_hash, "is not a valid locator")
161 elsif portable_data_hash[0..31] != computed_pdh[0..31]
162 errors.add(:portable_data_hash,
163 "does not match computed hash #{computed_pdh}")
166 # Ignore the client-provided size part: always store
167 # computed_pdh in the database.
168 self.portable_data_hash = computed_pdh
173 if self.manifest_text_changed?
174 self.file_names = manifest_files
181 if self.manifest_text
182 self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
183 names << name.first.gsub('\040',' ') + "\n"
184 break if names.length > 2**12
188 if self.manifest_text and names.length < 2**12
189 self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
190 names << stream_name.first.gsub('\040',' ') + "\n"
191 break if names.length > 2**12
198 def default_empty_manifest
199 self.manifest_text ||= ''
203 if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
207 # If Ruby thinks the encoding is something else, like 7-bit
208 # ASCII, but its stored bytes are equal to the (valid) UTF-8
209 # encoding of the same string, we declare it to be a UTF-8
212 utf8.force_encoding Encoding::UTF_8
213 if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
214 self.manifest_text = utf8
219 errors.add :manifest_text, "must use UTF-8 encoding"
224 def check_manifest_validity
226 Keep::Manifest.validate! manifest_text
228 rescue ArgumentError => e
229 errors.add :manifest_text, e.message
234 def signed_manifest_text
235 if !has_attribute? :manifest_text
240 token = current_api_client_authorization.andand.api_token
241 exp = [db_current_time.to_i + Rails.configuration.blob_signature_ttl,
242 trash_at].compact.map(&:to_i).min
243 self.class.sign_manifest manifest_text, token, exp
247 def self.sign_manifest manifest, token, exp=nil
249 exp = db_current_time.to_i + Rails.configuration.blob_signature_ttl
255 m = munge_manifest_locators(manifest) do |match|
256 Blob.sign_locator(match[0], signing_opts)
261 def self.munge_manifest_locators manifest
262 # Given a manifest text and a block, yield the regexp MatchData
263 # for each locator. Return a new manifest in which each locator
264 # has been replaced by the block's return value.
265 return nil if !manifest
266 return '' if manifest == ''
269 manifest.each_line do |line|
272 line.split(' ').each do |word|
275 elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
276 new_words << yield(match)
281 new_lines << new_words.join(' ')
283 new_lines.join("\n") + "\n"
286 def self.each_manifest_locator manifest
287 # Given a manifest text and a block, yield the regexp match object
289 manifest.each_line do |line|
290 # line will have a trailing newline, but the last token is never
291 # a locator, so it's harmless here.
292 line.split(' ').each do |word|
293 if match = Keep::Locator::LOCATOR_REGEXP.match(word)
300 def self.normalize_uuid uuid
303 uuid.split('+').each do |token|
304 if token.match(/^[0-9a-f]{32,}$/)
305 raise "uuid #{uuid} has multiple hash parts" if hash_part
307 elsif token.match(/^\d+$/)
308 raise "uuid #{uuid} has multiple size parts" if size_part
312 raise "uuid #{uuid} has no hash part" if !hash_part
313 [hash_part, size_part].compact.join '+'
316 # Return array of Collection objects
317 def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil)
318 readers ||= [Thread.current[:user]]
320 readable_by(*readers).
321 readable_by(*readers, table_name: "collections").
322 joins("JOIN collections ON links.head_uuid = collections.uuid").
323 order("links.created_at DESC")
325 # If the search term is a Collection locator that contains one file
326 # that looks like a Docker image, return it.
327 if loc = Keep::Locator.parse(search_term)
329 coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1).first
331 # Check if the Collection contains exactly one file whose name
332 # looks like a saved Docker image.
333 manifest = Keep::Manifest.new(coll_match.manifest_text)
334 if manifest.exact_file_count?(1) and
335 (manifest.files[0][1] =~ /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/)
341 if search_tag.nil? and (n = search_term.index(":"))
342 search_tag = search_term[n+1..-1]
343 search_term = search_term[0..n-1]
346 # Find Collections with matching Docker image repository+tag pairs.
347 matches = base_search.
348 where(link_class: "docker_image_repo+tag",
349 name: "#{search_term}:#{search_tag || 'latest'}")
351 # If that didn't work, find Collections with matching Docker image hashes.
353 matches = base_search.
354 where("link_class = ? and links.name LIKE ?",
355 "docker_image_hash", "#{search_term}%")
358 # Generate an order key for each result. We want to order the results
359 # so that anything with an image timestamp is considered more recent than
360 # anything without; then we use the link's created_at as a tiebreaker.
362 matches.all.map do |link|
363 uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
364 -link.created_at.to_i]
366 Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c| uuid_timestamps[c.uuid] }
369 def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
370 find_all_for_docker_image(search_term, search_tag, readers).first
373 def self.searchable_columns operator
374 super - ["manifest_text"]
377 def self.full_text_searchable_columns
378 super - ["manifest_text"]
382 SweepTrashedCollections.sweep_if_stale
387 def portable_manifest_text
388 self.class.munge_manifest_locators(manifest_text) do |match|
398 portable_manifest = portable_manifest_text
399 (Digest::MD5.hexdigest(portable_manifest) +
401 portable_manifest.bytesize.to_s)
405 if @computed_pdh_for_manifest_text == manifest_text
408 @computed_pdh = compute_pdh
409 @computed_pdh_for_manifest_text = manifest_text.dup
413 def ensure_permission_to_save
414 if (not current_user.andand.is_admin and
415 (replication_confirmed_at_changed? or replication_confirmed_changed?) and
416 not (replication_confirmed_at.nil? and replication_confirmed.nil?))
417 raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
422 # Use a single timestamp for all validations, even though each
423 # validation runs at a different time.
424 def set_validation_timestamp
425 @validation_timestamp = db_current_time
428 # If trash_at is being changed to a time in the past, change it to
429 # now. This allows clients to say "expires {client-current-time}"
430 # without failing due to clock skew, while avoiding odd log entries
431 # like "expiry date changed to {1 year ago}".
432 def ensure_trash_at_not_in_past
433 if trash_at_changed? && trash_at
434 self.trash_at = [@validation_timestamp, trash_at].max
438 # Caller can move into/out of trash by setting/clearing is_trashed
439 # -- however, if the caller also changes trash_at, then any changes
440 # to is_trashed are ignored.
442 if is_trashed_changed? && !trash_at_changed?
444 self.trash_at = @validation_timestamp
450 self.is_trashed = trash_at && trash_at <= @validation_timestamp || false
454 # If trash_at is updated without touching delete_at, automatically
455 # update delete_at to a sensible value.
456 def default_trash_interval
457 if trash_at_changed? && !delete_at_changed?
461 self.delete_at = trash_at + Rails.configuration.default_trash_lifetime.seconds
466 def validate_trash_and_delete_timing
467 if trash_at.nil? != delete_at.nil?
468 errors.add :delete_at, "must be set if trash_at is set, and must be nil otherwise"
471 earliest_delete = ([@validation_timestamp, trash_at_was].compact.min +
472 Rails.configuration.blob_signature_ttl.seconds)
473 if delete_at && delete_at < earliest_delete
474 errors.add :delete_at, "#{delete_at} is too soon: earliest allowed is #{earliest_delete}"
477 if delete_at && delete_at < trash_at
478 errors.add :delete_at, "must not be earlier than trash_at"