Add 'sdk/java-v2/' from commit '55f103e336ca9fb8bf1720d2ef4ee8dd4e221118'
[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   validate :versioning_metadata_updates, on: :update
31   validate :past_versions_cannot_be_updated, on: :update
32   before_save :set_file_names
33   around_update :manage_versioning
34
35   api_accessible :user, extend: :common do |t|
36     t.add :name
37     t.add :description
38     t.add :properties
39     t.add :portable_data_hash
40     t.add :signed_manifest_text, as: :manifest_text
41     t.add :manifest_text, as: :unsigned_manifest_text
42     t.add :replication_desired
43     t.add :replication_confirmed
44     t.add :replication_confirmed_at
45     t.add :storage_classes_desired
46     t.add :storage_classes_confirmed
47     t.add :storage_classes_confirmed_at
48     t.add :delete_at
49     t.add :trash_at
50     t.add :is_trashed
51     t.add :version
52     t.add :current_version_uuid
53     t.add :preserve_version
54   end
55
56   after_initialize do
57     @signatures_checked = false
58     @computed_pdh_for_manifest_text = false
59   end
60
61   def self.attributes_required_columns
62     super.merge(
63                 # If we don't list manifest_text explicitly, the
64                 # params[:select] code gets confused by the way we
65                 # expose signed_manifest_text as manifest_text in the
66                 # API response, and never let clients select the
67                 # manifest_text column.
68                 #
69                 # We need trash_at and is_trashed to determine the
70                 # correct timestamp in signed_manifest_text.
71                 'manifest_text' => ['manifest_text', 'trash_at', 'is_trashed'],
72                 'unsigned_manifest_text' => ['manifest_text'],
73                 )
74   end
75
76   def self.ignored_select_attributes
77     super + ["updated_at", "file_names"]
78   end
79
80   def self.limit_index_columns_read
81     ["manifest_text"]
82   end
83
84   FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
85   def check_signatures
86     return false if self.manifest_text.nil?
87
88     return true if current_user.andand.is_admin
89
90     # Provided the manifest_text hasn't changed materially since an
91     # earlier validation, it's safe to pass this validation on
92     # subsequent passes without checking any signatures. This is
93     # important because the signatures have probably been stripped off
94     # by the time we get to a second validation pass!
95     if @signatures_checked && @signatures_checked == computed_pdh
96       return true
97     end
98
99     if self.manifest_text_changed?
100       # Check permissions on the collection manifest.
101       # If any signature cannot be verified, raise PermissionDeniedError
102       # which will return 403 Permission denied to the client.
103       api_token = Thread.current[:token]
104       signing_opts = {
105         api_token: api_token,
106         now: @validation_timestamp.to_i,
107       }
108       self.manifest_text.each_line do |entry|
109         entry.split.each do |tok|
110           if tok == '.' or tok.starts_with? './'
111             # Stream name token.
112           elsif tok =~ FILE_TOKEN
113             # This is a filename token, not a blob locator. Note that we
114             # keep checking tokens after this, even though manifest
115             # format dictates that all subsequent tokens will also be
116             # filenames. Safety first!
117           elsif Blob.verify_signature tok, signing_opts
118             # OK.
119           elsif Keep::Locator.parse(tok).andand.signature
120             # Signature provided, but verify_signature did not like it.
121             logger.warn "Invalid signature on locator #{tok}"
122             raise ArvadosModel::PermissionDeniedError
123           elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
124             # No signature provided, but we are running in insecure mode.
125             logger.debug "Missing signature on locator #{tok} ignored"
126           elsif Blob.new(tok).empty?
127             # No signature provided -- but no data to protect, either.
128           else
129             logger.warn "Missing signature on locator #{tok}"
130             raise ArvadosModel::PermissionDeniedError
131           end
132         end
133       end
134     end
135     @signatures_checked = computed_pdh
136   end
137
138   def strip_signatures_and_update_replication_confirmed
139     if self.manifest_text_changed?
140       in_old_manifest = {}
141       if not self.replication_confirmed.nil?
142         self.class.each_manifest_locator(manifest_text_was) do |match|
143           in_old_manifest[match[1]] = true
144         end
145       end
146
147       stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
148         if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
149           # If the new manifest_text contains locators whose hashes
150           # weren't in the old manifest_text, storage replication is no
151           # longer confirmed.
152           self.replication_confirmed_at = nil
153           self.replication_confirmed = nil
154         end
155
156         # Return the locator with all permission signatures removed,
157         # but otherwise intact.
158         match[0].gsub(/\+A[^+]*/, '')
159       end
160
161       if @computed_pdh_for_manifest_text == manifest_text
162         # If the cached PDH was valid before stripping, it is still
163         # valid after stripping.
164         @computed_pdh_for_manifest_text = stripped_manifest.dup
165       end
166
167       self[:manifest_text] = stripped_manifest
168     end
169     true
170   end
171
172   def ensure_pdh_matches_manifest_text
173     if not manifest_text_changed? and not portable_data_hash_changed?
174       true
175     elsif portable_data_hash.nil? or not portable_data_hash_changed?
176       self.portable_data_hash = computed_pdh
177     elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
178       errors.add(:portable_data_hash, "is not a valid locator")
179       false
180     elsif portable_data_hash[0..31] != computed_pdh[0..31]
181       errors.add(:portable_data_hash,
182                  "'#{portable_data_hash}' does not match computed hash '#{computed_pdh}'")
183       false
184     else
185       # Ignore the client-provided size part: always store
186       # computed_pdh in the database.
187       self.portable_data_hash = computed_pdh
188     end
189   end
190
191   def set_file_names
192     if self.manifest_text_changed?
193       self.file_names = manifest_files
194     end
195     true
196   end
197
198   def manifest_files
199     return '' if !self.manifest_text
200
201     done = {}
202     names = ''
203     self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
204       next if done[name]
205       done[name] = true
206       names << name.first.gsub('\040',' ') + "\n"
207     end
208     self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
209       next if done[stream_name]
210       done[stream_name] = true
211       names << stream_name.first.gsub('\040',' ') + "\n"
212     end
213     names
214   end
215
216   def default_empty_manifest
217     self.manifest_text ||= ''
218   end
219
220   def skip_uuid_existence_check
221     # Avoid checking the existence of current_version_uuid, as it's
222     # assigned on creation of a new 'current version' collection, so
223     # the collection's UUID only lives on memory when the validation check
224     # is performed.
225     ['current_version_uuid']
226   end
227
228   def manage_versioning
229     should_preserve_version = should_preserve_version? # Time sensitive, cache value
230     return(yield) unless (should_preserve_version || syncable_updates.any?)
231
232     # Put aside the changes because with_lock forces a record reload
233     changes = self.changes
234     snapshot = nil
235     with_lock do
236       # Copy the original state to save it as old version
237       if should_preserve_version
238         snapshot = self.dup
239         snapshot.uuid = nil # Reset UUID so it's created as a new record
240         snapshot.created_at = self.created_at
241       end
242
243       # Restore requested changes on the current version
244       changes.keys.each do |attr|
245         if attr == 'preserve_version' && changes[attr].last == false
246           next # Ignore false assignment, once true it'll be true until next version
247         end
248         self.attributes = {attr => changes[attr].last}
249         if attr == 'uuid'
250           # Also update the current version reference
251           self.attributes = {'current_version_uuid' => changes[attr].last}
252         end
253       end
254
255       if should_preserve_version
256         self.version += 1
257         self.preserve_version = false
258       end
259
260       yield
261
262       sync_past_versions if syncable_updates.any?
263       if snapshot
264         snapshot.attributes = self.syncable_updates
265         snapshot.manifest_text = snapshot.signed_manifest_text
266         snapshot.save
267       end
268     end
269   end
270
271   def syncable_updates
272     updates = {}
273     (syncable_attrs & self.changes.keys).each do |attr|
274       if attr == 'uuid'
275         # Point old versions to current version's new UUID
276         updates['current_version_uuid'] = self.changes[attr].last
277       else
278         updates[attr] = self.changes[attr].last
279       end
280     end
281     return updates
282   end
283
284   def sync_past_versions
285     updates = self.syncable_updates
286     Collection.where('current_version_uuid = ? AND uuid != ?', self.uuid_was, self.uuid_was).each do |c|
287       c.attributes = updates
288       # Use a different validation context to skip the 'old_versions_cannot_be_updated'
289       # validator, as on this case it is legal to update some fields.
290       leave_modified_by_user_alone do
291         leave_modified_at_alone do
292           c.save(context: :update_old_versions)
293         end
294       end
295     end
296   end
297
298   def versionable_updates?(attrs)
299     (['manifest_text', 'description', 'properties', 'name'] & attrs).any?
300   end
301
302   def syncable_attrs
303     ['uuid', 'owner_uuid', 'delete_at', 'trash_at', 'is_trashed', 'replication_desired', 'storage_classes_desired']
304   end
305
306   def should_preserve_version?
307     return false unless (Rails.configuration.collection_versioning && versionable_updates?(self.changes.keys))
308
309     idle_threshold = Rails.configuration.preserve_version_if_idle
310     if !self.preserve_version_was &&
311       (idle_threshold < 0 ||
312         (idle_threshold > 0 && self.modified_at_was > db_current_time-idle_threshold.seconds))
313       return false
314     end
315     return true
316   end
317
318   def check_encoding
319     if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
320       true
321     else
322       begin
323         # If Ruby thinks the encoding is something else, like 7-bit
324         # ASCII, but its stored bytes are equal to the (valid) UTF-8
325         # encoding of the same string, we declare it to be a UTF-8
326         # string.
327         utf8 = manifest_text
328         utf8.force_encoding Encoding::UTF_8
329         if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
330           self.manifest_text = utf8
331           return true
332         end
333       rescue
334       end
335       errors.add :manifest_text, "must use UTF-8 encoding"
336       false
337     end
338   end
339
340   def check_manifest_validity
341     begin
342       Keep::Manifest.validate! manifest_text
343       true
344     rescue ArgumentError => e
345       errors.add :manifest_text, e.message
346       false
347     end
348   end
349
350   def signed_manifest_text
351     if !has_attribute? :manifest_text
352       return nil
353     elsif is_trashed
354       return manifest_text
355     else
356       token = Thread.current[:token]
357       exp = [db_current_time.to_i + Rails.configuration.blob_signature_ttl,
358              trash_at].compact.map(&:to_i).min
359       self.class.sign_manifest manifest_text, token, exp
360     end
361   end
362
363   def self.sign_manifest manifest, token, exp=nil
364     if exp.nil?
365       exp = db_current_time.to_i + Rails.configuration.blob_signature_ttl
366     end
367     signing_opts = {
368       api_token: token,
369       expire: exp,
370     }
371     m = munge_manifest_locators(manifest) do |match|
372       Blob.sign_locator(match[0], signing_opts)
373     end
374     return m
375   end
376
377   def self.munge_manifest_locators manifest
378     # Given a manifest text and a block, yield the regexp MatchData
379     # for each locator. Return a new manifest in which each locator
380     # has been replaced by the block's return value.
381     return nil if !manifest
382     return '' if manifest == ''
383
384     new_lines = []
385     manifest.each_line do |line|
386       line.rstrip!
387       new_words = []
388       line.split(' ').each do |word|
389         if new_words.empty?
390           new_words << word
391         elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
392           new_words << yield(match)
393         else
394           new_words << word
395         end
396       end
397       new_lines << new_words.join(' ')
398     end
399     new_lines.join("\n") + "\n"
400   end
401
402   def self.each_manifest_locator manifest
403     # Given a manifest text and a block, yield the regexp match object
404     # for each locator.
405     manifest.each_line do |line|
406       # line will have a trailing newline, but the last token is never
407       # a locator, so it's harmless here.
408       line.split(' ').each do |word|
409         if match = Keep::Locator::LOCATOR_REGEXP.match(word)
410           yield(match)
411         end
412       end
413     end
414   end
415
416   def self.normalize_uuid uuid
417     hash_part = nil
418     size_part = nil
419     uuid.split('+').each do |token|
420       if token.match(/^[0-9a-f]{32,}$/)
421         raise "uuid #{uuid} has multiple hash parts" if hash_part
422         hash_part = token
423       elsif token.match(/^\d+$/)
424         raise "uuid #{uuid} has multiple size parts" if size_part
425         size_part = token
426       end
427     end
428     raise "uuid #{uuid} has no hash part" if !hash_part
429     [hash_part, size_part].compact.join '+'
430   end
431
432   def self.get_compatible_images(readers, pattern, collections)
433     if collections.empty?
434       return []
435     end
436
437     migrations = Hash[
438       Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
439                  collections.map(&:portable_data_hash),
440                  'docker_image_migration',
441                  system_user_uuid).
442       order('links.created_at asc').
443       map { |l|
444         [l.tail_uuid, l.head_uuid]
445       }]
446
447     migrated_collections = Hash[
448       Collection.readable_by(*readers).
449       where('portable_data_hash in (?)', migrations.values).
450       map { |c|
451         [c.portable_data_hash, c]
452       }]
453
454     collections.map { |c|
455       # Check if the listed image is compatible first, if not, then try the
456       # migration link.
457       manifest = Keep::Manifest.new(c.manifest_text)
458       if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
459         c
460       elsif m = migrated_collections[migrations[c.portable_data_hash]]
461         manifest = Keep::Manifest.new(m.manifest_text)
462         if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
463           m
464         end
465       end
466     }.compact
467   end
468
469   # Resolve a Docker repo+tag, hash, or collection PDH to an array of
470   # Collection objects, sorted by timestamp starting with the most recent
471   # match.
472   #
473   # If filter_compatible_format is true (the default), only return image
474   # collections which are support by the installation as indicated by
475   # Rails.configuration.docker_image_formats.  Will follow
476   # 'docker_image_migration' links if search_term resolves to an incompatible
477   # image, but an equivalent compatible image is available.
478   def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
479     readers ||= [Thread.current[:user]]
480     base_search = Link.
481       readable_by(*readers).
482       readable_by(*readers, table_name: "collections").
483       joins("JOIN collections ON links.head_uuid = collections.uuid").
484       order("links.created_at DESC")
485
486     if (Rails.configuration.docker_image_formats.include? 'v1' and
487         Rails.configuration.docker_image_formats.include? 'v2') or filter_compatible_format == false
488       pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
489     elsif Rails.configuration.docker_image_formats.include? 'v2'
490       pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
491     elsif Rails.configuration.docker_image_formats.include? 'v1'
492       pattern = /^[0-9A-Fa-f]{64}\.tar$/
493     else
494       raise "Unrecognized configuration for docker_image_formats #{Rails.configuration.docker_image_formats}"
495     end
496
497     # If the search term is a Collection locator that contains one file
498     # that looks like a Docker image, return it.
499     if loc = Keep::Locator.parse(search_term)
500       loc.strip_hints!
501       coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
502       if coll_match.any? or Rails.configuration.remote_hosts.length == 0
503         return get_compatible_images(readers, pattern, coll_match)
504       else
505         # Allow bare pdh that doesn't exist in the local database so
506         # that federated container requests which refer to remotely
507         # stored containers will validate.
508         return [Collection.new(portable_data_hash: loc.to_s)]
509       end
510     end
511
512     if search_tag.nil? and (n = search_term.index(":"))
513       search_tag = search_term[n+1..-1]
514       search_term = search_term[0..n-1]
515     end
516
517     # Find Collections with matching Docker image repository+tag pairs.
518     matches = base_search.
519       where(link_class: "docker_image_repo+tag",
520             name: "#{search_term}:#{search_tag || 'latest'}")
521
522     # If that didn't work, find Collections with matching Docker image hashes.
523     if matches.empty?
524       matches = base_search.
525         where("link_class = ? and links.name LIKE ?",
526               "docker_image_hash", "#{search_term}%")
527     end
528
529     # Generate an order key for each result.  We want to order the results
530     # so that anything with an image timestamp is considered more recent than
531     # anything without; then we use the link's created_at as a tiebreaker.
532     uuid_timestamps = {}
533     matches.each do |link|
534       uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
535        -link.created_at.to_i]
536      end
537
538     sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
539       uuid_timestamps[c.uuid]
540     }
541     compatible = get_compatible_images(readers, pattern, sorted)
542     if sorted.length > 0 and compatible.empty?
543       raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
544     end
545     compatible
546   end
547
548   def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
549     find_all_for_docker_image(search_term, search_tag, readers).first
550   end
551
552   def self.searchable_columns operator
553     super - ["manifest_text"]
554   end
555
556   def self.full_text_searchable_columns
557     super - ["manifest_text", "storage_classes_desired", "storage_classes_confirmed", "current_version_uuid"]
558   end
559
560   def self.where *args
561     SweepTrashedObjects.sweep_if_stale
562     super
563   end
564
565   protected
566
567   # Although the defaults for these columns is already set up on the schema,
568   # collection creation from an API client seems to ignore them, making the
569   # validation on empty desired storage classes return an error.
570   def default_storage_classes
571     if self.storage_classes_desired.nil? || self.storage_classes_desired.empty?
572       self.storage_classes_desired = ["default"]
573     end
574     self.storage_classes_confirmed ||= []
575   end
576
577   def portable_manifest_text
578     self.class.munge_manifest_locators(manifest_text) do |match|
579       if match[2] # size
580         match[1] + match[2]
581       else
582         match[1]
583       end
584     end
585   end
586
587   def compute_pdh
588     portable_manifest = portable_manifest_text
589     (Digest::MD5.hexdigest(portable_manifest) +
590      '+' +
591      portable_manifest.bytesize.to_s)
592   end
593
594   def computed_pdh
595     if @computed_pdh_for_manifest_text == manifest_text
596       return @computed_pdh
597     end
598     @computed_pdh = compute_pdh
599     @computed_pdh_for_manifest_text = manifest_text.dup
600     @computed_pdh
601   end
602
603   def ensure_permission_to_save
604     if (not current_user.andand.is_admin)
605       if (replication_confirmed_at_changed? or replication_confirmed_changed?) and
606         not (replication_confirmed_at.nil? and replication_confirmed.nil?)
607         raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
608       end
609       if (storage_classes_confirmed_changed? or storage_classes_confirmed_at_changed?) and
610         not (storage_classes_confirmed == [] and storage_classes_confirmed_at.nil?)
611         raise ArvadosModel::PermissionDeniedError.new("storage_classes_confirmed and storage_classes_confirmed_at attributes cannot be changed, except by setting them to [] and nil respectively")
612       end
613     end
614     super
615   end
616
617   def ensure_storage_classes_desired_is_not_empty
618     if self.storage_classes_desired.empty?
619       raise ArvadosModel::InvalidStateTransitionError.new("storage_classes_desired shouldn't be empty")
620     end
621   end
622
623   def ensure_storage_classes_contain_non_empty_strings
624     (self.storage_classes_desired + self.storage_classes_confirmed).each do |c|
625       if !c.is_a?(String) || c == ''
626         raise ArvadosModel::InvalidStateTransitionError.new("storage classes should only be non-empty strings")
627       end
628     end
629   end
630
631   def past_versions_cannot_be_updated
632     # We check for the '_was' values just in case the update operation
633     # includes a change on current_version_uuid or uuid.
634     if current_version_uuid_was != uuid_was
635       errors.add(:base, "past versions cannot be updated")
636       false
637     end
638   end
639
640   def versioning_metadata_updates
641     valid = true
642     if (current_version_uuid_was == uuid_was) && current_version_uuid_changed?
643       errors.add(:current_version_uuid, "cannot be updated")
644       valid = false
645     end
646     if version_changed?
647       errors.add(:version, "cannot be updated")
648       valid = false
649     end
650     valid
651   end
652
653   def assign_uuid
654     super
655     self.current_version_uuid ||= self.uuid
656     true
657   end
658 end