1 class Collection < ArvadosModel
4 include CommonApiTemplate
6 before_validation :check_signatures
7 before_validation :strip_manifest_text
8 before_validation :set_portable_data_hash
9 validate :ensure_hash_matches_manifest_text
11 api_accessible :user, extend: :common do |t|
17 t.add :portable_data_hash
21 def self.attributes_required_columns
22 super.merge({ "data_size" => ["manifest_text"],
23 "files" => ["manifest_text"],
28 return false if self.manifest_text.nil?
30 return true if current_user.andand.is_admin
32 if self.manifest_text_changed?
33 # Check permissions on the collection manifest.
34 # If any signature cannot be verified, raise PermissionDeniedError
35 # which will return 403 Permission denied to the client.
36 api_token = current_api_client_authorization.andand.api_token
38 key: Rails.configuration.blob_signing_key,
40 ttl: Rails.configuration.blob_signing_ttl,
42 self.manifest_text.lines.each do |entry|
43 entry.split[1..-1].each do |tok|
44 if /^[[:digit:]]+:[[:digit:]]+:/.match tok
45 # This is a filename token, not a blob locator. Note that we
46 # keep checking tokens after this, even though manifest
47 # format dictates that all subsequent tokens will also be
48 # filenames. Safety first!
49 elsif Blob.verify_signature tok, signing_opts
51 elsif Locator.parse(tok).andand.signature
52 # Signature provided, but verify_signature did not like it.
53 logger.warn "Invalid signature on locator #{tok}"
54 raise ArvadosModel::PermissionDeniedError
55 elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
56 # No signature provided, but we are running in insecure mode.
57 logger.debug "Missing signature on locator #{tok} ignored"
58 elsif Blob.new(tok).empty?
59 # No signature provided -- but no data to protect, either.
61 logger.warn "Missing signature on locator #{tok}"
62 raise ArvadosModel::PermissionDeniedError
70 def strip_manifest_text
71 if self.manifest_text_changed?
72 # Remove any permission signatures from the manifest.
73 Collection.munge_manifest_locators(self[:manifest_text]) do |loc|
74 loc.without_signature.to_s
80 def set_portable_data_hash
81 if (self.portable_data_hash.nil? or (self.portable_data_hash == "") or (manifest_text_changed? and !portable_data_hash_changed?))
82 self.portable_data_hash = "#{Digest::MD5.hexdigest(manifest_text)}+#{manifest_text.length}"
83 elsif portable_data_hash_changed?
85 loc = Locator.parse!(self.portable_data_hash)
87 self.portable_data_hash = loc.to_s
88 rescue ArgumentError => e
89 errors.add(:portable_data_hash, "#{e}")
96 def ensure_hash_matches_manifest_text
97 if manifest_text_changed? or portable_data_hash_changed?
98 computed_hash = "#{Digest::MD5.hexdigest(manifest_text)}+#{manifest_text.length}"
99 unless computed_hash == portable_data_hash
100 logger.debug "(computed) '#{computed_hash}' != '#{portable_data_hash}' (provided)"
101 errors.add(:portable_data_hash, "does not match hash of manifest_text")
108 def redundancy_status
109 if redundancy_confirmed_as.nil?
111 elsif redundancy_confirmed_as < redundancy
114 if redundancy_confirmed_at.nil?
116 elsif Time.now - redundancy_confirmed_at < 7.days
125 inspect_manifest_text if @data_size.nil? or manifest_text_changed?
130 inspect_manifest_text if @files.nil? or manifest_text_changed?
134 def inspect_manifest_text
144 manifest_text.split("\n").each do |stream|
145 toks = stream.split(" ")
147 stream = toks[0].gsub /\\(\\|[0-7]{3})/ do |escape_sequence|
154 toks[1..-1].each do |tok|
155 if (re = tok.match /^[0-9a-f]{32}/)
157 tok.split('+')[1..-1].each do |hint|
158 if !blocksize and hint.match /^\d+$/
159 blocksize = hint.to_i
161 if (re = hint.match /^GS(\d+)$/)
162 blocksize = re[1].to_i
165 @data_size = false if !blocksize
166 @data_size += blocksize if @data_size
168 if (re = tok.match /^(\d+):(\d+):(\S+)$/)
169 filename = re[3].gsub /\\(\\|[0-7]{3})/ do |escape_sequence|
175 fn = stream + '/' + filename
189 re = k.match(/^(.+)\/(.+)/)
190 @files << [re[1], re[2], v]
194 def self.munge_manifest_locators(manifest)
195 # Given a manifest text and a block, yield each locator,
196 # and replace it with whatever the block returns.
197 manifest.andand.gsub!(/ [[:xdigit:]]{32}(\+[[:digit:]]+)?(\+\S+)/) do |word|
198 if loc = Locator.parse(word.strip)
206 def self.normalize_uuid uuid
209 uuid.split('+').each do |token|
210 if token.match /^[0-9a-f]{32,}$/
211 raise "uuid #{uuid} has multiple hash parts" if hash_part
213 elsif token.match /^\d+$/
214 raise "uuid #{uuid} has multiple size parts" if size_part
218 raise "uuid #{uuid} has no hash part" if !hash_part
219 [hash_part, size_part].compact.join '+'
222 # Return array of Collection objects
223 def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil)
224 readers ||= [Thread.current[:user]]
226 readable_by(*readers).
227 readable_by(*readers, table_name: "collections").
228 joins("JOIN collections ON links.head_uuid = collections.uuid").
229 order("links.created_at DESC")
231 # If the search term is a Collection locator that contains one file
232 # that looks like a Docker image, return it.
233 if loc = Locator.parse(search_term)
235 coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1).first
236 if coll_match and (coll_match.files.size == 1) and
237 (coll_match.files[0][1] =~ /^[0-9A-Fa-f]{64}\.tar$/)
242 if search_tag.nil? and (n = search_term.index(":"))
243 search_tag = search_term[n+1..-1]
244 search_term = search_term[0..n-1]
247 # Find Collections with matching Docker image repository+tag pairs.
248 matches = base_search.
249 where(link_class: "docker_image_repo+tag",
250 name: "#{search_term}:#{search_tag || 'latest'}")
252 # If that didn't work, find Collections with matching Docker image hashes.
254 matches = base_search.
255 where("link_class = ? and links.name LIKE ?",
256 "docker_image_hash", "#{search_term}%")
259 # Generate an order key for each result. We want to order the results
260 # so that anything with an image timestamp is considered more recent than
261 # anything without; then we use the link's created_at as a tiebreaker.
263 matches.all.map do |link|
264 uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
265 -link.created_at.to_i]
267 Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c| uuid_timestamps[c.uuid] }
270 def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
271 find_all_for_docker_image(search_term, search_tag, readers).first