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