3 class Collection < ArvadosModel
7 include CommonApiTemplate
9 serialize :properties, Hash
11 before_validation :check_encoding
12 before_validation :check_signatures
13 before_validation :strip_manifest_text
14 before_validation :set_portable_data_hash
15 before_validation :maybe_clear_replication_confirmed
16 validate :ensure_hash_matches_manifest_text
17 before_save :set_file_names
19 # Query only undeleted collections by default.
20 default_scope where("expires_at IS NULL or expires_at > CURRENT_TIMESTAMP")
22 api_accessible :user, extend: :common do |t|
26 t.add :portable_data_hash
27 t.add :signed_manifest_text, as: :manifest_text
28 t.add :replication_desired
29 t.add :replication_confirmed
30 t.add :replication_confirmed_at
33 LOCATOR_REGEXP = /^([[:xdigit:]]{32})(\+([[:digit:]]+))?(\+([[:upper:]][[:alnum:]+@_-]*))?$/
35 def self.attributes_required_columns
37 # If we don't list manifest_text explicitly, the
38 # params[:select] code gets confused by the way we
39 # expose signed_manifest_text as manifest_text in the
40 # API response, and never let clients select the
41 # manifest_text column.
42 'manifest_text' => ['manifest_text'],
47 return false if self.manifest_text.nil?
49 return true if current_user.andand.is_admin
51 # Provided the manifest_text hasn't changed materially since an
52 # earlier validation, it's safe to pass this validation on
53 # subsequent passes without checking any signatures. This is
54 # important because the signatures have probably been stripped off
55 # by the time we get to a second validation pass!
56 computed_pdh = compute_pdh
57 return true if @signatures_checked and @signatures_checked == computed_pdh
59 if self.manifest_text_changed?
60 # Check permissions on the collection manifest.
61 # If any signature cannot be verified, raise PermissionDeniedError
62 # which will return 403 Permission denied to the client.
63 api_token = current_api_client_authorization.andand.api_token
66 now: db_current_time.to_i,
68 self.manifest_text.lines.each do |entry|
69 entry.split[1..-1].each do |tok|
70 if /^[[:digit:]]+:[[:digit:]]+:/.match tok
71 # This is a filename token, not a blob locator. Note that we
72 # keep checking tokens after this, even though manifest
73 # format dictates that all subsequent tokens will also be
74 # filenames. Safety first!
75 elsif Blob.verify_signature tok, signing_opts
77 elsif Keep::Locator.parse(tok).andand.signature
78 # Signature provided, but verify_signature did not like it.
79 logger.warn "Invalid signature on locator #{tok}"
80 raise ArvadosModel::PermissionDeniedError
81 elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
82 # No signature provided, but we are running in insecure mode.
83 logger.debug "Missing signature on locator #{tok} ignored"
84 elsif Blob.new(tok).empty?
85 # No signature provided -- but no data to protect, either.
87 logger.warn "Missing signature on locator #{tok}"
88 raise ArvadosModel::PermissionDeniedError
93 @signatures_checked = computed_pdh
96 def strip_manifest_text
97 if self.manifest_text_changed?
98 # Remove any permission signatures from the manifest.
99 self.class.munge_manifest_locators!(self[:manifest_text]) do |match|
100 self.class.locator_without_signature(match)
106 def self.locator_without_signature match
107 without_signature = match[1]
108 without_signature += match[2] if match[2]
110 hints = match[4].split('+').reject { |hint| hint.start_with?("A") }
111 without_signature += hints.join('+')
116 def set_portable_data_hash
117 if (portable_data_hash.nil? or
118 portable_data_hash == "" or
119 (manifest_text_changed? and !portable_data_hash_changed?))
120 @need_pdh_validation = false
121 self.portable_data_hash = compute_pdh
122 elsif portable_data_hash_changed?
123 @need_pdh_validation = true
125 loc = Keep::Locator.parse!(self.portable_data_hash)
128 self.portable_data_hash = loc.to_s
130 self.portable_data_hash = "#{loc.hash}+#{portable_manifest_text.bytesize}"
132 rescue ArgumentError => e
133 errors.add(:portable_data_hash, "#{e}")
140 def ensure_hash_matches_manifest_text
141 return true unless manifest_text_changed? or portable_data_hash_changed?
142 # No need verify it if :set_portable_data_hash just computed it!
143 return true if not @need_pdh_validation
144 expect_pdh = compute_pdh
145 if expect_pdh != portable_data_hash
146 errors.add(:portable_data_hash,
147 "does not match computed hash #{expect_pdh}")
153 if self.manifest_text_changed?
154 self.file_names = manifest_files
161 if self.manifest_text
162 self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
163 names << name.first.gsub('\040',' ') + "\n"
164 break if names.length > 2**12
168 if self.manifest_text and names.length < 2**12
169 self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
170 names << stream_name.first.gsub('\040',' ') + "\n"
171 break if names.length > 2**12
179 if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
183 # If Ruby thinks the encoding is something else, like 7-bit
184 # ASCII, but its stored bytes are equal to the (valid) UTF-8
185 # encoding of the same string, we declare it to be a UTF-8
188 utf8.force_encoding Encoding::UTF_8
189 if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
195 errors.add :manifest_text, "must use UTF-8 encoding"
200 def signed_manifest_text
201 if has_attribute? :manifest_text
202 token = current_api_client_authorization.andand.api_token
203 @signed_manifest_text = self.class.sign_manifest manifest_text, token
207 def self.sign_manifest manifest, token
210 expire: db_current_time.to_i + Rails.configuration.blob_signature_ttl,
213 munge_manifest_locators!(m) do |match|
214 Blob.sign_locator(locator_without_signature(match), signing_opts)
219 def self.munge_manifest_locators! manifest
220 # Given a manifest text and a block, yield each locator,
221 # and replace it with whatever the block returns.
223 lines = manifest.andand.split("\n")
224 lines.andand.each do |line|
225 words = line.split(' ')
228 if match = LOCATOR_REGEXP.match(word.strip)
229 new_words << yield(match)
234 new_lines << new_words.join(' ')
236 manifest = new_lines.join("\n")+"\n"
239 def self.each_manifest_locator manifest
240 # Given a manifest text and a block, yield each locator.
241 manifest.andand.scan(/ ([[:xdigit:]]{32}(\+\S+)?)/) do |word, _|
242 if loc = Keep::Locator.parse(word)
248 def self.normalize_uuid uuid
251 uuid.split('+').each do |token|
252 if token.match /^[0-9a-f]{32,}$/
253 raise "uuid #{uuid} has multiple hash parts" if hash_part
255 elsif token.match /^\d+$/
256 raise "uuid #{uuid} has multiple size parts" if size_part
260 raise "uuid #{uuid} has no hash part" if !hash_part
261 [hash_part, size_part].compact.join '+'
264 # Return array of Collection objects
265 def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil)
266 readers ||= [Thread.current[:user]]
268 readable_by(*readers).
269 readable_by(*readers, table_name: "collections").
270 joins("JOIN collections ON links.head_uuid = collections.uuid").
271 order("links.created_at DESC")
273 # If the search term is a Collection locator that contains one file
274 # that looks like a Docker image, return it.
275 if loc = Keep::Locator.parse(search_term)
277 coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1).first
279 # Check if the Collection contains exactly one file whose name
280 # looks like a saved Docker image.
281 manifest = Keep::Manifest.new(coll_match.manifest_text)
282 if manifest.exact_file_count?(1) and
283 (manifest.files[0][1] =~ /^[0-9A-Fa-f]{64}\.tar$/)
289 if search_tag.nil? and (n = search_term.index(":"))
290 search_tag = search_term[n+1..-1]
291 search_term = search_term[0..n-1]
294 # Find Collections with matching Docker image repository+tag pairs.
295 matches = base_search.
296 where(link_class: "docker_image_repo+tag",
297 name: "#{search_term}:#{search_tag || 'latest'}")
299 # If that didn't work, find Collections with matching Docker image hashes.
301 matches = base_search.
302 where("link_class = ? and links.name LIKE ?",
303 "docker_image_hash", "#{search_term}%")
306 # Generate an order key for each result. We want to order the results
307 # so that anything with an image timestamp is considered more recent than
308 # anything without; then we use the link's created_at as a tiebreaker.
310 matches.all.map do |link|
311 uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
312 -link.created_at.to_i]
314 Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c| uuid_timestamps[c.uuid] }
317 def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
318 find_all_for_docker_image(search_term, search_tag, readers).first
321 def self.searchable_columns operator
322 super - ["manifest_text"]
325 def self.full_text_searchable_columns
326 super - ["manifest_text"]
330 def portable_manifest_text
331 portable_manifest = self[:manifest_text].dup
332 portable_manifest = self.class.munge_manifest_locators!(portable_manifest) do |match|
343 return @computed_pdh if @computed_pdh
344 portable_manifest = portable_manifest_text
345 @computed_pdh = (Digest::MD5.hexdigest(portable_manifest) +
347 portable_manifest.bytesize.to_s)
351 def maybe_clear_replication_confirmed
352 if manifest_text_changed?
353 # If the new manifest_text contains locators whose hashes
354 # weren't in the old manifest_text, storage replication is no
357 self.class.each_manifest_locator(manifest_text_was) do |loc|
358 in_old_manifest[loc.hash] = true
360 self.class.each_manifest_locator(manifest_text) do |loc|
361 if not in_old_manifest[loc.hash]
362 self.replication_confirmed_at = nil
363 self.replication_confirmed = nil
370 def ensure_permission_to_save
371 if (not current_user.andand.is_admin and
372 (replication_confirmed_at_changed? or replication_confirmed_changed?) and
373 not (replication_confirmed_at.nil? and replication_confirmed.nil?))
374 raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")