12032: Additional refactoring of readable_by. Refactor "trashable" into module.
[arvados.git] / services / api / app / models / collection.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'arvados/keep'
6 require 'sweep_trashed_collections'
7 require 'trashable'
8
9 class Collection < ArvadosModel
10   extend CurrentApiClient
11   extend DbCurrentTime
12   include HasUuid
13   include KindAndEtag
14   include CommonApiTemplate
15   include Trashable
16
17   serialize :properties, Hash
18
19   before_validation :default_empty_manifest
20   before_validation :check_encoding
21   before_validation :check_manifest_validity
22   before_validation :check_signatures
23   before_validation :strip_signatures_and_update_replication_confirmed
24   validate :ensure_pdh_matches_manifest_text
25   before_save :set_file_names
26
27   # Query only untrashed collections by default.
28   default_scope { where("is_trashed = false") }
29
30   api_accessible :user, extend: :common do |t|
31     t.add :name
32     t.add :description
33     t.add :properties
34     t.add :portable_data_hash
35     t.add :signed_manifest_text, as: :manifest_text
36     t.add :manifest_text, as: :unsigned_manifest_text
37     t.add :replication_desired
38     t.add :replication_confirmed
39     t.add :replication_confirmed_at
40     t.add :delete_at
41     t.add :trash_at
42     t.add :is_trashed
43   end
44
45   after_initialize do
46     @signatures_checked = false
47     @computed_pdh_for_manifest_text = false
48   end
49
50   def self.attributes_required_columns
51     super.merge(
52                 # If we don't list manifest_text explicitly, the
53                 # params[:select] code gets confused by the way we
54                 # expose signed_manifest_text as manifest_text in the
55                 # API response, and never let clients select the
56                 # manifest_text column.
57                 #
58                 # We need trash_at and is_trashed to determine the
59                 # correct timestamp in signed_manifest_text.
60                 'manifest_text' => ['manifest_text', 'trash_at', 'is_trashed'],
61                 'unsigned_manifest_text' => ['manifest_text'],
62                 )
63   end
64
65   def self.ignored_select_attributes
66     super + ["updated_at", "file_names"]
67   end
68
69   def self.limit_index_columns_read
70     ["manifest_text"]
71   end
72
73   FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
74   def check_signatures
75     return false if self.manifest_text.nil?
76
77     return true if current_user.andand.is_admin
78
79     # Provided the manifest_text hasn't changed materially since an
80     # earlier validation, it's safe to pass this validation on
81     # subsequent passes without checking any signatures. This is
82     # important because the signatures have probably been stripped off
83     # by the time we get to a second validation pass!
84     if @signatures_checked && @signatures_checked == computed_pdh
85       return true
86     end
87
88     if self.manifest_text_changed?
89       # Check permissions on the collection manifest.
90       # If any signature cannot be verified, raise PermissionDeniedError
91       # which will return 403 Permission denied to the client.
92       api_token = current_api_client_authorization.andand.api_token
93       signing_opts = {
94         api_token: api_token,
95         now: @validation_timestamp.to_i,
96       }
97       self.manifest_text.each_line do |entry|
98         entry.split.each do |tok|
99           if tok == '.' or tok.starts_with? './'
100             # Stream name token.
101           elsif tok =~ FILE_TOKEN
102             # This is a filename token, not a blob locator. Note that we
103             # keep checking tokens after this, even though manifest
104             # format dictates that all subsequent tokens will also be
105             # filenames. Safety first!
106           elsif Blob.verify_signature tok, signing_opts
107             # OK.
108           elsif Keep::Locator.parse(tok).andand.signature
109             # Signature provided, but verify_signature did not like it.
110             logger.warn "Invalid signature on locator #{tok}"
111             raise ArvadosModel::PermissionDeniedError
112           elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
113             # No signature provided, but we are running in insecure mode.
114             logger.debug "Missing signature on locator #{tok} ignored"
115           elsif Blob.new(tok).empty?
116             # No signature provided -- but no data to protect, either.
117           else
118             logger.warn "Missing signature on locator #{tok}"
119             raise ArvadosModel::PermissionDeniedError
120           end
121         end
122       end
123     end
124     @signatures_checked = computed_pdh
125   end
126
127   def strip_signatures_and_update_replication_confirmed
128     if self.manifest_text_changed?
129       in_old_manifest = {}
130       if not self.replication_confirmed.nil?
131         self.class.each_manifest_locator(manifest_text_was) do |match|
132           in_old_manifest[match[1]] = true
133         end
134       end
135
136       stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
137         if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
138           # If the new manifest_text contains locators whose hashes
139           # weren't in the old manifest_text, storage replication is no
140           # longer confirmed.
141           self.replication_confirmed_at = nil
142           self.replication_confirmed = nil
143         end
144
145         # Return the locator with all permission signatures removed,
146         # but otherwise intact.
147         match[0].gsub(/\+A[^+]*/, '')
148       end
149
150       if @computed_pdh_for_manifest_text == manifest_text
151         # If the cached PDH was valid before stripping, it is still
152         # valid after stripping.
153         @computed_pdh_for_manifest_text = stripped_manifest.dup
154       end
155
156       self[:manifest_text] = stripped_manifest
157     end
158     true
159   end
160
161   def ensure_pdh_matches_manifest_text
162     if not manifest_text_changed? and not portable_data_hash_changed?
163       true
164     elsif portable_data_hash.nil? or not portable_data_hash_changed?
165       self.portable_data_hash = computed_pdh
166     elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
167       errors.add(:portable_data_hash, "is not a valid locator")
168       false
169     elsif portable_data_hash[0..31] != computed_pdh[0..31]
170       errors.add(:portable_data_hash,
171                  "'#{portable_data_hash}' does not match computed hash '#{computed_pdh}'")
172       false
173     else
174       # Ignore the client-provided size part: always store
175       # computed_pdh in the database.
176       self.portable_data_hash = computed_pdh
177     end
178   end
179
180   def set_file_names
181     if self.manifest_text_changed?
182       self.file_names = manifest_files
183     end
184     true
185   end
186
187   def manifest_files
188     names = ''
189     if self.manifest_text
190       self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
191         names << name.first.gsub('\040',' ') + "\n"
192         break if names.length > 2**12
193       end
194     end
195
196     if self.manifest_text and names.length < 2**12
197       self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
198         names << stream_name.first.gsub('\040',' ') + "\n"
199         break if names.length > 2**12
200       end
201     end
202
203     names[0,2**12]
204   end
205
206   def default_empty_manifest
207     self.manifest_text ||= ''
208   end
209
210   def check_encoding
211     if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
212       true
213     else
214       begin
215         # If Ruby thinks the encoding is something else, like 7-bit
216         # ASCII, but its stored bytes are equal to the (valid) UTF-8
217         # encoding of the same string, we declare it to be a UTF-8
218         # string.
219         utf8 = manifest_text
220         utf8.force_encoding Encoding::UTF_8
221         if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
222           self.manifest_text = utf8
223           return true
224         end
225       rescue
226       end
227       errors.add :manifest_text, "must use UTF-8 encoding"
228       false
229     end
230   end
231
232   def check_manifest_validity
233     begin
234       Keep::Manifest.validate! manifest_text
235       true
236     rescue ArgumentError => e
237       errors.add :manifest_text, e.message
238       false
239     end
240   end
241
242   def signed_manifest_text
243     if !has_attribute? :manifest_text
244       return nil
245     elsif is_trashed
246       return manifest_text
247     else
248       token = current_api_client_authorization.andand.api_token
249       exp = [db_current_time.to_i + Rails.configuration.blob_signature_ttl,
250              trash_at].compact.map(&:to_i).min
251       self.class.sign_manifest manifest_text, token, exp
252     end
253   end
254
255   def self.sign_manifest manifest, token, exp=nil
256     if exp.nil?
257       exp = db_current_time.to_i + Rails.configuration.blob_signature_ttl
258     end
259     signing_opts = {
260       api_token: token,
261       expire: exp,
262     }
263     m = munge_manifest_locators(manifest) do |match|
264       Blob.sign_locator(match[0], signing_opts)
265     end
266     return m
267   end
268
269   def self.munge_manifest_locators manifest
270     # Given a manifest text and a block, yield the regexp MatchData
271     # for each locator. Return a new manifest in which each locator
272     # has been replaced by the block's return value.
273     return nil if !manifest
274     return '' if manifest == ''
275
276     new_lines = []
277     manifest.each_line do |line|
278       line.rstrip!
279       new_words = []
280       line.split(' ').each do |word|
281         if new_words.empty?
282           new_words << word
283         elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
284           new_words << yield(match)
285         else
286           new_words << word
287         end
288       end
289       new_lines << new_words.join(' ')
290     end
291     new_lines.join("\n") + "\n"
292   end
293
294   def self.each_manifest_locator manifest
295     # Given a manifest text and a block, yield the regexp match object
296     # for each locator.
297     manifest.each_line do |line|
298       # line will have a trailing newline, but the last token is never
299       # a locator, so it's harmless here.
300       line.split(' ').each do |word|
301         if match = Keep::Locator::LOCATOR_REGEXP.match(word)
302           yield(match)
303         end
304       end
305     end
306   end
307
308   def self.normalize_uuid uuid
309     hash_part = nil
310     size_part = nil
311     uuid.split('+').each do |token|
312       if token.match(/^[0-9a-f]{32,}$/)
313         raise "uuid #{uuid} has multiple hash parts" if hash_part
314         hash_part = token
315       elsif token.match(/^\d+$/)
316         raise "uuid #{uuid} has multiple size parts" if size_part
317         size_part = token
318       end
319     end
320     raise "uuid #{uuid} has no hash part" if !hash_part
321     [hash_part, size_part].compact.join '+'
322   end
323
324   def self.get_compatible_images(readers, pattern, collections)
325     if collections.empty?
326       return []
327     end
328
329     migrations = Hash[
330       Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
331                  collections.map(&:portable_data_hash),
332                  'docker_image_migration',
333                  system_user_uuid).
334       order('links.created_at asc').
335       map { |l|
336         [l.tail_uuid, l.head_uuid]
337       }]
338
339     migrated_collections = Hash[
340       Collection.readable_by(*readers).
341       where('portable_data_hash in (?)', migrations.values).
342       map { |c|
343         [c.portable_data_hash, c]
344       }]
345
346     collections.map { |c|
347       # Check if the listed image is compatible first, if not, then try the
348       # migration link.
349       manifest = Keep::Manifest.new(c.manifest_text)
350       if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
351         c
352       elsif m = migrated_collections[migrations[c.portable_data_hash]]
353         manifest = Keep::Manifest.new(m.manifest_text)
354         if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
355           m
356         end
357       end
358     }.compact
359   end
360
361   # Resolve a Docker repo+tag, hash, or collection PDH to an array of
362   # Collection objects, sorted by timestamp starting with the most recent
363   # match.
364   #
365   # If filter_compatible_format is true (the default), only return image
366   # collections which are support by the installation as indicated by
367   # Rails.configuration.docker_image_formats.  Will follow
368   # 'docker_image_migration' links if search_term resolves to an incompatible
369   # image, but an equivalent compatible image is available.
370   def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
371     readers ||= [Thread.current[:user]]
372     base_search = Link.
373       readable_by(*readers).
374       readable_by(*readers, table_name: "collections").
375       joins("JOIN collections ON links.head_uuid = collections.uuid").
376       order("links.created_at DESC")
377
378     if (Rails.configuration.docker_image_formats.include? 'v1' and
379         Rails.configuration.docker_image_formats.include? 'v2') or filter_compatible_format == false
380       pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
381     elsif Rails.configuration.docker_image_formats.include? 'v2'
382       pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
383     elsif Rails.configuration.docker_image_formats.include? 'v1'
384       pattern = /^[0-9A-Fa-f]{64}\.tar$/
385     else
386       raise "Unrecognized configuration for docker_image_formats #{Rails.configuration.docker_image_formats}"
387     end
388
389     # If the search term is a Collection locator that contains one file
390     # that looks like a Docker image, return it.
391     if loc = Keep::Locator.parse(search_term)
392       loc.strip_hints!
393       coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
394       return get_compatible_images(readers, pattern, coll_match)
395     end
396
397     if search_tag.nil? and (n = search_term.index(":"))
398       search_tag = search_term[n+1..-1]
399       search_term = search_term[0..n-1]
400     end
401
402     # Find Collections with matching Docker image repository+tag pairs.
403     matches = base_search.
404       where(link_class: "docker_image_repo+tag",
405             name: "#{search_term}:#{search_tag || 'latest'}")
406
407     # If that didn't work, find Collections with matching Docker image hashes.
408     if matches.empty?
409       matches = base_search.
410         where("link_class = ? and links.name LIKE ?",
411               "docker_image_hash", "#{search_term}%")
412     end
413
414     # Generate an order key for each result.  We want to order the results
415     # so that anything with an image timestamp is considered more recent than
416     # anything without; then we use the link's created_at as a tiebreaker.
417     uuid_timestamps = {}
418     matches.each do |link|
419       uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
420        -link.created_at.to_i]
421      end
422
423     sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
424       uuid_timestamps[c.uuid]
425     }
426     compatible = get_compatible_images(readers, pattern, sorted)
427     if sorted.length > 0 and compatible.empty?
428       raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
429     end
430     compatible
431   end
432
433   def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
434     find_all_for_docker_image(search_term, search_tag, readers).first
435   end
436
437   def self.searchable_columns operator
438     super - ["manifest_text"]
439   end
440
441   def self.full_text_searchable_columns
442     super - ["manifest_text"]
443   end
444
445   def self.where *args
446     SweepTrashedCollections.sweep_if_stale
447     super
448   end
449
450   protected
451   def portable_manifest_text
452     self.class.munge_manifest_locators(manifest_text) do |match|
453       if match[2] # size
454         match[1] + match[2]
455       else
456         match[1]
457       end
458     end
459   end
460
461   def compute_pdh
462     portable_manifest = portable_manifest_text
463     (Digest::MD5.hexdigest(portable_manifest) +
464      '+' +
465      portable_manifest.bytesize.to_s)
466   end
467
468   def computed_pdh
469     if @computed_pdh_for_manifest_text == manifest_text
470       return @computed_pdh
471     end
472     @computed_pdh = compute_pdh
473     @computed_pdh_for_manifest_text = manifest_text.dup
474     @computed_pdh
475   end
476
477   def ensure_permission_to_save
478     if (not current_user.andand.is_admin and
479         (replication_confirmed_at_changed? or replication_confirmed_changed?) and
480         not (replication_confirmed_at.nil? and replication_confirmed.nil?))
481       raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
482     end
483     super
484   end
485
486 end