3 class Collection < ArvadosModel
6 include CommonApiTemplate
8 before_validation :check_signatures
9 before_validation :strip_manifest_text
10 before_validation :set_portable_data_hash
11 validate :ensure_hash_matches_manifest_text
13 api_accessible :user, extend: :common do |t|
17 t.add :portable_data_hash
22 return false if self.manifest_text.nil?
24 return true if current_user.andand.is_admin
26 if self.manifest_text_changed?
27 # Check permissions on the collection manifest.
28 # If any signature cannot be verified, raise PermissionDeniedError
29 # which will return 403 Permission denied to the client.
30 api_token = current_api_client_authorization.andand.api_token
32 key: Rails.configuration.blob_signing_key,
34 ttl: Rails.configuration.blob_signing_ttl,
36 self.manifest_text.lines.each do |entry|
37 entry.split[1..-1].each do |tok|
38 if /^[[:digit:]]+:[[:digit:]]+:/.match tok
39 # This is a filename token, not a blob locator. Note that we
40 # keep checking tokens after this, even though manifest
41 # format dictates that all subsequent tokens will also be
42 # filenames. Safety first!
43 elsif Blob.verify_signature tok, signing_opts
45 elsif Keep::Locator.parse(tok).andand.signature
46 # Signature provided, but verify_signature did not like it.
47 logger.warn "Invalid signature on locator #{tok}"
48 raise ArvadosModel::PermissionDeniedError
49 elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
50 # No signature provided, but we are running in insecure mode.
51 logger.debug "Missing signature on locator #{tok} ignored"
52 elsif Blob.new(tok).empty?
53 # No signature provided -- but no data to protect, either.
55 logger.warn "Missing signature on locator #{tok}"
56 raise ArvadosModel::PermissionDeniedError
64 def strip_manifest_text
65 if self.manifest_text_changed?
66 # Remove any permission signatures from the manifest.
67 Collection.munge_manifest_locators(self[:manifest_text]) do |loc|
68 loc.without_signature.to_s
74 def set_portable_data_hash
75 if (self.portable_data_hash.nil? or (self.portable_data_hash == "") or (manifest_text_changed? and !portable_data_hash_changed?))
76 self.portable_data_hash = "#{Digest::MD5.hexdigest(manifest_text)}+#{manifest_text.length}"
77 elsif portable_data_hash_changed?
79 loc = Keep::Locator.parse!(self.portable_data_hash)
82 self.portable_data_hash = loc.to_s
84 self.portable_data_hash = "#{loc.hash}+#{self.manifest_text.length}"
86 rescue ArgumentError => e
87 errors.add(:portable_data_hash, "#{e}")
94 def ensure_hash_matches_manifest_text
95 if manifest_text_changed? or portable_data_hash_changed?
96 computed_hash = "#{Digest::MD5.hexdigest(manifest_text)}+#{manifest_text.length}"
97 unless computed_hash == portable_data_hash
98 logger.debug "(computed) '#{computed_hash}' != '#{portable_data_hash}' (provided)"
99 errors.add(:portable_data_hash, "does not match hash of manifest_text")
106 def redundancy_status
107 if redundancy_confirmed_as.nil?
109 elsif redundancy_confirmed_as < redundancy
112 if redundancy_confirmed_at.nil?
114 elsif Time.now - redundancy_confirmed_at < 7.days
122 def self.munge_manifest_locators(manifest)
123 # Given a manifest text and a block, yield each locator,
124 # and replace it with whatever the block returns.
125 manifest.andand.gsub!(/ [[:xdigit:]]{32}(\+[[:digit:]]+)?(\+\S+)/) do |word|
126 if loc = Keep::Locator.parse(word.strip)
134 def self.normalize_uuid uuid
137 uuid.split('+').each do |token|
138 if token.match /^[0-9a-f]{32,}$/
139 raise "uuid #{uuid} has multiple hash parts" if hash_part
141 elsif token.match /^\d+$/
142 raise "uuid #{uuid} has multiple size parts" if size_part
146 raise "uuid #{uuid} has no hash part" if !hash_part
147 [hash_part, size_part].compact.join '+'
150 # Return array of Collection objects
151 def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil)
152 readers ||= [Thread.current[:user]]
154 readable_by(*readers).
155 readable_by(*readers, table_name: "collections").
156 joins("JOIN collections ON links.head_uuid = collections.uuid").
157 order("links.created_at DESC")
159 # If the search term is a Collection locator that contains one file
160 # that looks like a Docker image, return it.
161 if loc = Keep::Locator.parse(search_term)
163 coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1).first
165 # Check if the Collection contains exactly one file whose name
166 # looks like a saved Docker image. We only take up to two
167 # files, because any number >1 means there's no match.
168 coll_files = Keep::Manifest.new(coll_match.manifest_text).each_file.take(2)
169 if (coll_files.size == 1) and
170 (coll_files[0][1] =~ /^[0-9A-Fa-f]{64}\.tar$/)
176 if search_tag.nil? and (n = search_term.index(":"))
177 search_tag = search_term[n+1..-1]
178 search_term = search_term[0..n-1]
181 # Find Collections with matching Docker image repository+tag pairs.
182 matches = base_search.
183 where(link_class: "docker_image_repo+tag",
184 name: "#{search_term}:#{search_tag || 'latest'}")
186 # If that didn't work, find Collections with matching Docker image hashes.
188 matches = base_search.
189 where("link_class = ? and links.name LIKE ?",
190 "docker_image_hash", "#{search_term}%")
193 # Generate an order key for each result. We want to order the results
194 # so that anything with an image timestamp is considered more recent than
195 # anything without; then we use the link's created_at as a tiebreaker.
197 matches.all.map do |link|
198 uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
199 -link.created_at.to_i]
201 Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c| uuid_timestamps[c.uuid] }
204 def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
205 find_all_for_docker_image(search_term, search_tag, readers).first