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
13 before_save :set_file_names
15 # Query only undeleted collections by default.
16 default_scope where("expires_at IS NULL or expires_at > CURRENT_TIMESTAMP")
18 api_accessible :user, extend: :common do |t|
22 t.add :portable_data_hash
23 t.add :signed_manifest_text, as: :manifest_text
26 def self.attributes_required_columns
27 # If we don't list this explicitly, the params[:select] code gets
28 # confused by the way we expose signed_manifest_text as
29 # manifest_text in the API response, and never let clients select
30 # the manifest_text column.
31 super.merge('manifest_text' => ['manifest_text'])
35 return false if self.manifest_text.nil?
37 return true if current_user.andand.is_admin
39 # Provided the manifest_text hasn't changed materially since an
40 # earlier validation, it's safe to pass this validation on
41 # subsequent passes without checking any signatures. This is
42 # important because the signatures have probably been stripped off
43 # by the time we get to a second validation pass!
44 return true if @signatures_checked and @signatures_checked == compute_pdh
46 if self.manifest_text_changed?
47 # Check permissions on the collection manifest.
48 # If any signature cannot be verified, raise PermissionDeniedError
49 # which will return 403 Permission denied to the client.
50 api_token = current_api_client_authorization.andand.api_token
52 key: Rails.configuration.blob_signing_key,
54 ttl: Rails.configuration.blob_signing_ttl,
56 self.manifest_text.lines.each do |entry|
57 entry.split[1..-1].each do |tok|
58 if /^[[:digit:]]+:[[:digit:]]+:/.match tok
59 # This is a filename token, not a blob locator. Note that we
60 # keep checking tokens after this, even though manifest
61 # format dictates that all subsequent tokens will also be
62 # filenames. Safety first!
63 elsif Blob.verify_signature tok, signing_opts
65 elsif Keep::Locator.parse(tok).andand.signature
66 # Signature provided, but verify_signature did not like it.
67 logger.warn "Invalid signature on locator #{tok}"
68 raise ArvadosModel::PermissionDeniedError
69 elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
70 # No signature provided, but we are running in insecure mode.
71 logger.debug "Missing signature on locator #{tok} ignored"
72 elsif Blob.new(tok).empty?
73 # No signature provided -- but no data to protect, either.
75 logger.warn "Missing signature on locator #{tok}"
76 raise ArvadosModel::PermissionDeniedError
81 @signatures_checked = compute_pdh
84 def strip_manifest_text
85 if self.manifest_text_changed?
86 # Remove any permission signatures from the manifest.
87 self.class.munge_manifest_locators!(self[:manifest_text]) do |loc|
88 loc.without_signature.to_s
94 def set_portable_data_hash
95 if (portable_data_hash.nil? or
96 portable_data_hash == "" or
97 (manifest_text_changed? and !portable_data_hash_changed?))
98 @need_pdh_validation = false
99 self.portable_data_hash = compute_pdh
100 elsif portable_data_hash_changed?
101 @need_pdh_validation = true
103 loc = Keep::Locator.parse!(self.portable_data_hash)
106 self.portable_data_hash = loc.to_s
108 self.portable_data_hash = "#{loc.hash}+#{portable_manifest_text.bytesize}"
110 rescue ArgumentError => e
111 errors.add(:portable_data_hash, "#{e}")
118 def ensure_hash_matches_manifest_text
119 return true unless manifest_text_changed? or portable_data_hash_changed?
120 # No need verify it if :set_portable_data_hash just computed it!
121 return true if not @need_pdh_validation
122 expect_pdh = compute_pdh
123 if expect_pdh != portable_data_hash
124 errors.add(:portable_data_hash,
125 "does not match computed hash #{expect_pdh}")
131 if self.manifest_text_changed?
132 self.file_names = manifest_files
139 if self.manifest_text
140 self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
141 names << name.first.gsub('\040',' ') + "\n"
142 break if names.length > 2**12
146 if self.manifest_text and names.length < 2**12
147 self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
148 names << stream_name.first.gsub('\040',' ') + "\n"
149 break if names.length > 2**12
157 if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
161 # If Ruby thinks the encoding is something else, like 7-bit
162 # ASCII, but its stored bytes are equal to the (valid) UTF-8
163 # encoding of the same string, we declare it to be a UTF-8
166 utf8.force_encoding Encoding::UTF_8
167 if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
173 errors.add :manifest_text, "must use UTF-8 encoding"
178 def redundancy_status
179 if redundancy_confirmed_as.nil?
181 elsif redundancy_confirmed_as < redundancy
184 if redundancy_confirmed_at.nil?
186 elsif Time.now - redundancy_confirmed_at < 7.days
194 def signed_manifest_text
195 if has_attribute? :manifest_text
196 token = current_api_client_authorization.andand.api_token
197 @signed_manifest_text = self.class.sign_manifest manifest_text, token
201 def self.sign_manifest manifest, token
203 key: Rails.configuration.blob_signing_key,
205 ttl: Rails.configuration.blob_signing_ttl,
208 munge_manifest_locators!(m) do |loc|
209 Blob.sign_locator(loc.to_s, signing_opts)
214 def self.munge_manifest_locators! manifest
215 # Given a manifest text and a block, yield each locator,
216 # and replace it with whatever the block returns.
217 manifest.andand.gsub!(/ [[:xdigit:]]{32}(\+[[:digit:]]+)?(\+\S+)/) do |word|
218 if loc = Keep::Locator.parse(word.strip)
226 def self.normalize_uuid uuid
229 uuid.split('+').each do |token|
230 if token.match /^[0-9a-f]{32,}$/
231 raise "uuid #{uuid} has multiple hash parts" if hash_part
233 elsif token.match /^\d+$/
234 raise "uuid #{uuid} has multiple size parts" if size_part
238 raise "uuid #{uuid} has no hash part" if !hash_part
239 [hash_part, size_part].compact.join '+'
242 # Return array of Collection objects
243 def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil)
244 readers ||= [Thread.current[:user]]
246 readable_by(*readers).
247 readable_by(*readers, table_name: "collections").
248 joins("JOIN collections ON links.head_uuid = collections.uuid").
249 order("links.created_at DESC")
251 # If the search term is a Collection locator that contains one file
252 # that looks like a Docker image, return it.
253 if loc = Keep::Locator.parse(search_term)
255 coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1).first
257 # Check if the Collection contains exactly one file whose name
258 # looks like a saved Docker image.
259 manifest = Keep::Manifest.new(coll_match.manifest_text)
260 if manifest.exact_file_count?(1) and
261 (manifest.files[0][1] =~ /^[0-9A-Fa-f]{64}\.tar$/)
267 if search_tag.nil? and (n = search_term.index(":"))
268 search_tag = search_term[n+1..-1]
269 search_term = search_term[0..n-1]
272 # Find Collections with matching Docker image repository+tag pairs.
273 matches = base_search.
274 where(link_class: "docker_image_repo+tag",
275 name: "#{search_term}:#{search_tag || 'latest'}")
277 # If that didn't work, find Collections with matching Docker image hashes.
279 matches = base_search.
280 where("link_class = ? and links.name LIKE ?",
281 "docker_image_hash", "#{search_term}%")
284 # Generate an order key for each result. We want to order the results
285 # so that anything with an image timestamp is considered more recent than
286 # anything without; then we use the link's created_at as a tiebreaker.
288 matches.all.map do |link|
289 uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
290 -link.created_at.to_i]
292 Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c| uuid_timestamps[c.uuid] }
295 def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
296 find_all_for_docker_image(search_term, search_tag, readers).first
299 def self.searchable_columns operator
300 super - ["manifest_text"]
303 def self.full_text_searchable_columns
304 super - ["manifest_text"]
308 def portable_manifest_text
309 portable_manifest = self[:manifest_text].dup
310 self.class.munge_manifest_locators!(portable_manifest) do |loc|
311 loc.hash + '+' + loc.size.to_s
317 portable_manifest = portable_manifest_text
318 (Digest::MD5.hexdigest(portable_manifest) +
320 portable_manifest.bytesize.to_s)