3 class Collection < ArvadosModel
6 include CommonApiTemplate
8 before_validation :check_encoding
9 before_validation :check_signatures
10 before_validation :strip_manifest_text
11 before_validation :set_portable_data_hash
12 validate :ensure_hash_matches_manifest_text
14 # Query only undeleted collections by default.
15 default_scope where("expires_at IS NULL or expires_at > CURRENT_TIMESTAMP")
17 api_accessible :user, extend: :common do |t|
21 t.add :portable_data_hash
26 return false if self.manifest_text.nil?
28 return true if current_user.andand.is_admin
30 if self.manifest_text_changed?
31 # Check permissions on the collection manifest.
32 # If any signature cannot be verified, raise PermissionDeniedError
33 # which will return 403 Permission denied to the client.
34 api_token = current_api_client_authorization.andand.api_token
36 key: Rails.configuration.blob_signing_key,
38 ttl: Rails.configuration.blob_signing_ttl,
40 self.manifest_text.lines.each do |entry|
41 entry.split[1..-1].each do |tok|
42 if /^[[:digit:]]+:[[:digit:]]+:/.match tok
43 # This is a filename token, not a blob locator. Note that we
44 # keep checking tokens after this, even though manifest
45 # format dictates that all subsequent tokens will also be
46 # filenames. Safety first!
47 elsif Blob.verify_signature tok, signing_opts
49 elsif Keep::Locator.parse(tok).andand.signature
50 # Signature provided, but verify_signature did not like it.
51 logger.warn "Invalid signature on locator #{tok}"
52 raise ArvadosModel::PermissionDeniedError
53 elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
54 # No signature provided, but we are running in insecure mode.
55 logger.debug "Missing signature on locator #{tok} ignored"
56 elsif Blob.new(tok).empty?
57 # No signature provided -- but no data to protect, either.
59 logger.warn "Missing signature on locator #{tok}"
60 raise ArvadosModel::PermissionDeniedError
68 def strip_manifest_text
69 if self.manifest_text_changed?
70 # Remove any permission signatures from the manifest.
71 Collection.munge_manifest_locators(self[:manifest_text]) do |loc|
72 loc.without_signature.to_s
78 def set_portable_data_hash
79 if (self.portable_data_hash.nil? or (self.portable_data_hash == "") or (manifest_text_changed? and !portable_data_hash_changed?))
80 self.portable_data_hash = "#{Digest::MD5.hexdigest(manifest_text)}+#{manifest_text.bytesize}"
81 elsif portable_data_hash_changed?
83 loc = Keep::Locator.parse!(self.portable_data_hash)
86 self.portable_data_hash = loc.to_s
88 self.portable_data_hash = "#{loc.hash}+#{self.manifest_text.bytesize}"
90 rescue ArgumentError => e
91 errors.add(:portable_data_hash, "#{e}")
98 def ensure_hash_matches_manifest_text
99 if manifest_text_changed? or portable_data_hash_changed?
100 computed_hash = "#{Digest::MD5.hexdigest(manifest_text)}+#{manifest_text.bytesize}"
101 unless computed_hash == portable_data_hash
102 logger.debug "(computed) '#{computed_hash}' != '#{portable_data_hash}' (provided)"
103 errors.add(:portable_data_hash, "does not match hash of manifest_text")
111 if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
115 # If Ruby thinks the encoding is something else, like 7-bit
116 # ASCII, but its stored bytes are equal to the (valid) UTF-8
117 # encoding of the same string, we declare it to be a UTF-8
120 utf8.force_encoding Encoding::UTF_8
121 if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
127 errors.add :manifest_text, "must use UTF-8 encoding"
132 def redundancy_status
133 if redundancy_confirmed_as.nil?
135 elsif redundancy_confirmed_as < redundancy
138 if redundancy_confirmed_at.nil?
140 elsif Time.now - redundancy_confirmed_at < 7.days
148 def self.munge_manifest_locators(manifest)
149 # Given a manifest text and a block, yield each locator,
150 # and replace it with whatever the block returns.
151 manifest.andand.gsub!(/ [[:xdigit:]]{32}(\+[[:digit:]]+)?(\+\S+)/) do |word|
152 if loc = Keep::Locator.parse(word.strip)
160 def self.normalize_uuid uuid
163 uuid.split('+').each do |token|
164 if token.match /^[0-9a-f]{32,}$/
165 raise "uuid #{uuid} has multiple hash parts" if hash_part
167 elsif token.match /^\d+$/
168 raise "uuid #{uuid} has multiple size parts" if size_part
172 raise "uuid #{uuid} has no hash part" if !hash_part
173 [hash_part, size_part].compact.join '+'
176 # Return array of Collection objects
177 def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil)
178 readers ||= [Thread.current[:user]]
180 readable_by(*readers).
181 readable_by(*readers, table_name: "collections").
182 joins("JOIN collections ON links.head_uuid = collections.uuid").
183 order("links.created_at DESC")
185 # If the search term is a Collection locator that contains one file
186 # that looks like a Docker image, return it.
187 if loc = Keep::Locator.parse(search_term)
189 coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1).first
191 # Check if the Collection contains exactly one file whose name
192 # looks like a saved Docker image.
193 manifest = Keep::Manifest.new(coll_match.manifest_text)
194 if manifest.exact_file_count?(1) and
195 (manifest.files[0][1] =~ /^[0-9A-Fa-f]{64}\.tar$/)
201 if search_tag.nil? and (n = search_term.index(":"))
202 search_tag = search_term[n+1..-1]
203 search_term = search_term[0..n-1]
206 # Find Collections with matching Docker image repository+tag pairs.
207 matches = base_search.
208 where(link_class: "docker_image_repo+tag",
209 name: "#{search_term}:#{search_tag || 'latest'}")
211 # If that didn't work, find Collections with matching Docker image hashes.
213 matches = base_search.
214 where("link_class = ? and links.name LIKE ?",
215 "docker_image_hash", "#{search_term}%")
218 # Generate an order key for each result. We want to order the results
219 # so that anything with an image timestamp is considered more recent than
220 # anything without; then we use the link's created_at as a tiebreaker.
222 matches.all.map do |link|
223 uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
224 -link.created_at.to_i]
226 Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c| uuid_timestamps[c.uuid] }
229 def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
230 find_all_for_docker_image(search_term, search_tag, readers).first