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