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